We had a nice time with one on my old friends – Yogesh, and his family. Enjoyed a memorable time with his daughter Yukta, and enjoyed delicious ‘parathas’ by his wife Hema. After a hearty chat, we bid farewell to 2012 over a sumptuous Indian dinner at Swagat, Roppongi.
Tag: new
-
Happy New Year 2011 Wishes
I wish ALL of you a very Happy & Prosperous New Year 2011 !
-
Happy New Year 2011 – Wishes to my wife
My best wishes, and sincere feelings for my wife Elena, expressed as a little poem.
-
Nicolas performing You should be dancing tonight
Hilarious, isn't it?
-
Spring and Logback
IoC, or DI definitely takes a perspective turnaround inside your head, but you get around it slowly. I was playing around ways to integrate LogBack, and Spring – essentially around having Spring give me a pre-created instance of LogBack logger.
I searched around posts, but most people seem to be against using Spring just for substituting one-line of Logback (
Logger log = LoggerFactory.getLogger("LogbackTest");
) to get your logger.I, on the other hand, was more interested in how to get Spring give me a LogBack logger instance without too much contrived hand-written code to achieve so. And with a bit of reading through Spring principles, documentation I found the way.
Essentially, when using Logback’s LoggerFactory you have access to only a single getLogger() factory method. This is static which makes things a bit different for what Spring would call a bean – a class providing constructor, getter, setter methods. To circumvent this non-bean style, Spring provides what you call as static initializers a.k.a substitutes for constructors, which allow you to call a static method in lieu of calling a constructor on an object.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="bean1" class="org.slf4j.LoggerFactory" factory-method="getLogger"> <constructor-arg value="LogbackTest" /> </bean> </beans>
Now, this bean1 can be used as a regular bean inside your class
ApplicationContext ctx = new FileSystemXmlApplicationContext("logbacktest.xml"); Logger log = (Logger) ctx.getBean("bean1"); log.debug("This is my first message"); log.info("How about this information message");
Throw in a logback.xml in your classpath, and viola you have a nice Spring injected dependency – log in your code, while still using Logback!
-
Racking brains – a Javascript string combination generator
After racking my brains for almost 4 days (yeah I am a slow learner) I finally created a simple Javascript string combination generator
See the demo http://naiksblog.info/stringcombinations.html
I tried modeling the logic to how databases combine sets in a cross join. All rows from left side are combined with all rows from right side.
The script is as below
function combine(a, b) { var r= new Array(); for(var i= 0, k= 0; i < a.length; i++) { for(var j= 0; j < b.length; j++) { if(-1==a[i].indexOf(b[j])) r[k++]= a[i]+ b[j]; } } return(r); }
You can call this as below
function permute() { var a= "abcd"; var p= new Array(); for(var i= 0; i< a.length; i++) p[i]= a.charAt(i); var r= p; // Input string as-is is first permutation for(var i= 1; i< a.length; i++) r= combine(r, p); // Get the permutations // r.length - Get the combinations // r contains all combinations as an array }
Some points worth noting
- If any character is repeated, the combination does not happen successfully since the logic tries to remove same character matching elsewhere
- The number of combinations increase by factorial of the number of characters, hence it will be a good idea to perform this on server side ideally otherwise javascript will hang for large strings
- Logic could be optimized to generate combination in a different better way than using crossjoin strategy
-
Extremely useful tips for Java
- A .java class can contain only one top-level public class. All other top level classes in same .java file cannot be private or protected or public, only default (package-level access) is allowed.
- If no package is specified for class, it belongs to unnamed package – which cannot be imported.
- Unlike Linux utilities, long parameters or short parameters to java(c) need just a space before parameter value. e.g. -classpath <classpath> or -cp <classpath> are same. There is no -classpath=<classpath> syntax in java(c) command line.
- 8 primitive types (byte, short, int, long, float, double, char, boolean), special type void, and base type for all objects – java.lang.Object.
- null is not a keyword, type. It is a value.
- String objects created using short-hand
String A= "a string";
syntax creates Strings on pool in heap. A is pointer (32-bit to max. 64-bit) to a String object “a string” on heap memory allocated to your program. Using short-hand syntax to “a string” onString B= "a string";
will point to same string object on heap. - Object gets garbage-collected, not it’s reference.
- Garbage collection is indeterminate. You cannot guarantee freeing of memory by forcing
System.gc()
finalize
method is invoked only once before being removed from memory. Always callsuper.finalize()
if you override it.- Parameters (primitive, references) are always passed-by-value. There is no pass-by-reference in Java. The references passed can be used to modify the object the reference points, but not the reference itself is not modified.
- Return values from function are also passed by value, never by reference.
- Compound operators (+=, -=, *= etc) automatically cast. Compiler never throws any error on data mismatch.
- & (and) results in 1 if both are 1, | (or) results in 0 if both are 0, ^ (xor) results in 1 if either operand is 1
- char supports increment, decrement operators.
- The default isequal() implementation of Object tests for reference equality, which is same as ==.
- When using operators, Java automatically promotes values to int or higher. For values below int – byte, short – an explicit cast is required.
- extends comes first then implements
- Java tokenizes your source into separators (tab or space), keywords, operators, literals, identifiers (variable names).
- new zeroes Object’s fields (instance variables), hence explicit initialization can be skipped.
- import static allows importing static variables like System.out into your program. Hence, you can simply use out without prefixing it with class name System.
- local variables must be initialized before using. Though method parameters are local variables too, since methods are called with parameters, they are initialized.
- arrays are fixed size data structures, where as collections are dynamically sized data structures.
- For multidimensional arrays, it is easier to imagine the first dimension as a single row containing the other dimensions.
- Array initialization always requires dimension to be provided when initializing through new (caught at compile time). If using array initializer, you can specify {} empty braces, but accessing any index at runtime will only result in index out of bounds exception.
- There is always a default constructor – empty body – available for your class only if you do not declare any constructor.
- super, this must be the first line in constructor. this() or super() both cannot be placed.
- Parent class constructor super() is always called. For this reason, you need to have an empty constructor always in parent class.
- Method signature is composed of method name and parameters. Modifiers, return type, exception list has nothing to do with it. Access-specifiers however control visibility.
- Javabean properties are get-, set- methods provided over a field in Javabean style.
- Variable length parameters always come at the end of the list, and they can be empty (meaning nothing was passed). Being at end of the list automatically implies that only variable length parameters is allowed. (Java 5.0)
- Overloading means providing different method signatures in same or inheriting class. Overriding means providing same return type, method signature in inheriting class.
- Covariant return types means overriding method returns a subclass of return type in parent class. (Java 5.0)
- Method hiding means overriding of static methods.
- Abstract method has no body. Interface methods are all abstract, while Abstract class can contain zero or more abstract methods.
- All abstract method of Interface are public, it’s fields are public, static and final. No static methods are allowed.
- Abstract method compiles with static modifier, but generates runtime error if directly accessed. If abstract static method is overridden in child class, child class works fine.
- Enum constructors are invoked for each element.
- Anonymous inner class can have only one instance. Local inner class can have multiple instances.
- Static nested class is similar to any top-level class.
- Static fields in class always need default value; otherwise code does not compile.
- false is boolean, 0 is not false, it is int zero
- switch…case does not allow case null, since a constant (and final) expression is required for case
- You can put break in default for switch
- enum classes can have main method
- for(;;) is a valid for-loop. It never finishes, since it is an infinite loop.
- In enhanced for loop, the variable used for iteration must be declared only in for loop, not outside it.
- Java complains if you have unreachable while loop code e.g while(false) is not allowed. However, contrarily if(false) is allowed!
- Variables declared inside do…while loop are not available in while to test for condition!
- It is a good idea to add labels to your loops to enhance readability
- Assertion is put in places in your code where you think it should be always true
- Though not a good design, but assertions do allow modification on variables while asserting them e.g. assert ++i
- try…catch – catch can never have an exception which is a subclass of previous catch clause. It throws compile error.
- Checked exceptions always derive from Exception, runtime exceptions derive from RuntimeException, errors derive from Error. Java enforces checked exceptions are either handled or thrown. For runtime, error there is no such rule, even if RuntimeException derives from Exception.
- try… must have either catch or finally atleast, otherwise compile gives error
-
Interesting alternatives to databases in opensource
I stumbled upon this url. The list of various options on databases is pretty amazing.
http://www.webresourcesdepot.com/25-alternative-open-source-databases-engines/
It’s a definite read. I never knew so many existed.