Tuesday, April 12, 2011

Tuesday, July 6, 2010

JAVA: Convert String to InputStream

You can use ByteArrayInputStream to convert String to InputStream.
ByteArrayInputStream extends InputStream.

Example:
String content = "Convert string to inputstream";
ByteArrayInputStream stream = new ByteArrayInputStream(content.getBytes());



Reference:
1. http://forums.sun.com/thread.jspa?threadID=670188

2. http://java.sun.com/j2se/1.4.2/docs/api/java/io/ByteArrayInputStream.html

Wednesday, May 12, 2010

JSTL: Find length of a collection

To get a length of a collection:
${fn:length(tvPackageGroup.addonOptions)}

Include <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> namespace.
http://stackoverflow.com/questions/851880/check-a-collection-size-with-jstl

Sorting a collection in JSTL

javadoc: http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/fn/tld-summary.html

Tuesday, February 2, 2010

JAVA: reverse string interview question

When you go for an interview, lot of companies ask String manipulation questions.


Some of the most common questions are:

  • Reverse words in a string (words are separated by spaces) - Most Common
  • Reverse String
  • Revers the order of words

I have written a code that performs all these functions. Hope this will help you.

/**
* Created by IntelliJ IDEA.
* User: priyank
* Date: Feb 2, 2010
*/
public class StringTest {

public static void main(String[] args) {
String str = "My name is khan";
// String result = reverseString(str);
// String result = reverseWords(str);
// String result = reverseSequence(str);
String result = iReverseSequence(str);

System.out.println(result);
}

static String reverseString(String str) {
char[] ch = str.toCharArray();
StringBuilder sb = new StringBuilder();
for (int i=(ch.length-1);i>=0;i--) {
sb.append(ch[i]);
}
return sb.toString();
}

static String reverseWords(String str) {
String[] st = str.split("\\s");
StringBuilder sb = new StringBuilder();
for(int i=0; i < st.length;i++) {
sb.append(reverseString(st[i])+" ");
}
return sb.toString();
}

static String reverseSequence(String str) {
String[] st = str.split("\\s");
StringBuilder sb = new StringBuilder();
for(int i=(st.length-1);i>=0;i--) {
sb.append(st[i]+" ");
}
return sb.toString();
}


// Without using inbuilt java functions (for ex without using split())
// I still used substr() though
static String iReverseSequence(String str) {
String word = "";
int lastIndex = str.length();
for(int i=(str.length()-1);i>=0;i--) {
if(str.charAt(i) == ' ') {
word += str.substring(i+1,lastIndex)+" ";
lastIndex = i;
}
}
word += str.substring(0,lastIndex);
return word;
}
}

Tuesday, October 13, 2009

My regex Notes

These are notes I have created for regex. It is not formatted right now but I will update this post soon.

[] = use square brackets [] as OR operator. You can also call it a character class.
[^xyz] = ^ in the beginning of [] means "(not x) or y or z"
^abc means start char must be a
abc$ means end characted must be c
example:
^\s+ = beginning with whitespace-charater one or more times
\s+$ matches trailing white space
in perl trim function can be $input =~ s/^\s+|\s+$//g

Word boundaries:
[a-zA-A0-9_] are word characters. [a-zA-A0-9] = \w
\b is used to define boundary
\bis => "my name is priyank" and "I like Hawai islands" will match. But "this was a book" won't.
\bis\b => Only "my name is priyank" will match.
is\b => "my name is priyank" and "this was a book" will match "I like Hawai islands" won't.

Regex is Eager
ref: http://www.regular-expressions.info/alternation.html

You use "?" for optional items. ? means 1 or 0 times
B4?U matched both BU and B4U.
(Jan)?uary mathces Jan and January
* means 0 or more times.
+ means 1 or more times.

You use "?" to make regex non-greedy.
So in "tennis is a nice sport. ", if your regex is (.*is)will match the string "tennis is" but if your regex is "(.*?is).*" will find only "this".
SO "?" makes the regex lazy or ungreedy.

Round brackets are used for grouping.
Round bracket also create a 'backreference'.
What is a "back reference" in regex?
Ans: A backreference stores the part of the string matched by the of the regex inside the parantheses.
Backreference slows down the regex engine as it has to some more work.
You use "?:" to tell regex engine not to create any back reference.
How to use a backreference ?
Backreference allows you to re-use matched part of a regex. You can re-use it inside the regex itself.
A very good example ofr backreference is find starting and closing html tag ans contetnt inside that tag.
<([A-Z][A-Z0-9]*)\b[^>]*>.*?


Download regex cheatsheet

Sunday, October 11, 2009

How to show line number in VI editor

Use following command to view line numbers
:set number

To remove line numbers, use following command.
:set nonumber

Wednesday, August 26, 2009

Twitter bookmarklet

Updated version of this bookmarklet is here Twitter bookmarklet


What does this bookmarklet do?

You are reading a great article on the web or you found a great website. Now you want to share it with everyone on twitter. Just click on "TweetThis" bookmark in your bookmarks tab and it will take you to twitter with url already shortened with bit.ly.

Drag this Twitter Bookmarklet to your favorite browser's Bookmarks Toolbar.


Old: TweetThis Check out the latest one below.

UPDATED bookmarklet - includes page title in a your tweet.

New: TweetThis

1. You found a great article on yahoo and you want to share it on twitter. To do this- Click on TweetThis bookmarklet.



2. Once you click on the bookmarklet, it will create bitly url for the webpage and take you to twitter.com to post.


If you want to view what it is doing, check this.

Source code:
javascript:function loadScript(scriptURL) { var scriptElem = document.createElement('SCRIPT'); scriptElem.setAttribute('language', 'JavaScript'); scriptElem.setAttribute('src', scriptURL); document.body.appendChild(scriptElem);}var url = 'http://api.bit.ly/shorten?version=2.0.1&login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&longUrl='+document.location;var longUrl=document.location;loadScript(url+'&callback=tweetme');function tweetme(json){var shortLink = json.results[longUrl].shortUrl;document.location='http://twitter.com/home?status=I+found+this+great+thing+'+shortLink}