Saturday, January 19, 2013

Google Address AutoComplete Tutorial

This is very basic for google address lookup/auto completion tutorial.
First thing you need to do is include google maps javascript to your page.

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>

Next step is to initialize Autocomplete. When you initialize Autocomplete, it basically starts a listener which listens for an input. Following code does that.

var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);

When you start typeing it looks like this.



When user selects an address, value of input field get updated to selected address. You do not need to have nay extra code. However in case if you want to read selected address, you will need to add "place_changed" google maps event listener. It returns PlaceResult object. Following code shows how you can get PlaceResult object.

google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
alert(place.formatted_address);

You can find a demo here: Google Address Auto Complete Demo In this example, I am loading address lookup form using an ajax.

You can download demo source from github: View source code


Here is the complete snippet.

Wednesday, January 2, 2013

PSQL: find current database, schema, user

Commands:
SELECT current_database();
SELECT current_schema();
SELECT current_user();
More commands like this, you can find it here. http://www.postgresql.org/docs/7.3/static/functions-misc.html

Friday, December 14, 2012

DJango Python 101

DJango commands cheatsheet


How to start server:
./manage.py runserver

How to create new app
./manage.py startapp newappname

Database stuff
How to create database from models (Use South instead)
./manage.py syncdb

How to use South
http://south.readthedocs.org/en/latest/commands.html

For existing app
you will need to convert into South supported app first.
./manage.py convert_to_south myappname

For new apps
Create db (Similar to syncdb command)
./manage.py schemamigration myappname --initial

Update db with schema changes
./manage.py schemamigration myappname --auto

These commands generates migration scripts only.
Run this command for changes to take effect in db
./manage.py migrate myappname

Sunday, November 18, 2012

PSQL 101

How to create a database
CREATE DATABASE mydatabase;

How to create a user
CREATE USER priyank with password 'passw0rd';

How to grant access to a user
GRANT ALL PRIVILEGES ON DATABASE mydatabase to priyank

How to see list of databases
psql -l -U priyank
Alternatively you can connect to database first and then type '\l'
\l

How to see list of tables
#Connect to database first.
\d

Friday, November 9, 2012

Shell: How to increment a value in a shell script

This is a very basic question that comes into our mind many times while writing a shell script.

Here is a small code that you may find it useful.

#!/bin/sh
i=0
j=5
while [ $i -le $j ]
do
i=`expr $i + 1`
echo $i
done

Here I am using expr unix command. This command evaluates arguments as expressions. You can find more details about expr by typing man expr in your terminal or check this link for online manual.

Tuesday, August 28, 2012

Monitor cURL traffic in fiddler

If you want to view your curl request-response in fiddler, you need to tell curl to use fiddler proxy.
You can do that by passing -x parameter.
e.g.
curl -x 127.0.0.1:8888 http://www.priyankgandhi.com

If your url is https, then you will need to pass -k parameter. This will disable curl's ssl verification.
curl -k -x 127.0.0.1:8888 https://www.google.com

Tuesday, August 21, 2012

PostgreSQL: login without entering password

If you want to connect to your postgre database without entering password every time, you can achieve that by creating PGPASS file in your home directory.
e.g. Create a file called .pgpass in your home directory. Add and entry in this format.

hostname:port:database:username:password

priyank@localhost:~$ vi .pgpass
192.168.1.101:5432:restaurant:priyank:passwordispassword

Here is a documentation from postgresql site.
http://www.postgresql.org/docs/9.1/static/libpq-pgpass.html

Friday, August 10, 2012

MYSQL: Connect to mysql using command

How to connect to mysql using a command - from terminal

mysql -u <user> -p -h <host ip> -P <port> <dbname>

Example:

mysql -u root -p -h priyankgandhi.com -P 3306 testdb

Tuesday, May 1, 2012

XAMPP: How to change default language for phpmyadmin

Today I installed XAMPP. After installing, First thing I wanted to do was change mysql password. After searching on xampp site, I found out I can change mysql password using phpMyAdmin. (Ref: link) When I went to phpMyAdmin, everything was in German. After some search, I found out that you have to add two lines in config file.
C:\xampp\phpMyAdmin\config.inc.php
In this file add following line.
$cfg['DefaultLang'] = 'en-utf-8';
After this just reload phpmyadmin page.

Thursday, February 9, 2012

Cygwin: rebaseall utility

You may sometimes see cygwin error like this.
bash 4944 exception::handle: Exception: STATUS_ACCESS_VIOLATION
emap to same address as parent

Short answer

To fix these errors, run these commands from your MS-DOS command prompt.
cd \cygwin\bin
ash
PATH=. rebaseall -v

More Details

Rebaseall utility
Rebaseall utility should be available under /cygwin/bin/ directory.
To check if rebaseall is available or not. If it is available it will print something like this.
priyank@~:>which rebaseall
/usr/bin/rebaseall

Only ash process is allowed to run rebaseall. Means you cannot run rebaseall directly from cygwin.
Open MS-DOS command prompt and follow these steps to to run rebaseall.
cd \cygwin\bin
ash
PATH=. rebaseall -v

Thursday, December 29, 2011

JAVA: SAXParseException - entiry must end with ';' delimiter

Exception: org.xml.sax.SAXParseException: The reference to entity “T” must end with the ';' delimiter

The problem is with an XML which you are trying to parse. Your xml contains special character "&". It should be replaced with "&"

Thursday, September 22, 2011

How to generate ssh public/private key (using command)
Use following command:
ssh-keygen -t rsa

where
-t: specifies type of key to create
rsa: is a type to create You can to check more options by using man command.
man ssh-keygen

Friday, August 19, 2011

Some advice

I stumbled upon this while reading a blog.

- An hour of sleep before midnight is worth two, and an hour of work before noon is worth two.

- Always pick your kids up from school. That’s when they want to talk.

- Never let your skill exceed your virtue.

- Never take less than two weeks off when you have a child or for your honeymoon. Don’t let them talk you down.

- When you mess up, admit it frankly and quickly, and move on.

- Always do your very best in your job, but if you don’t like what you’re doing enough that you would do it for free, quit.

Friday, July 15, 2011

MYSQL: Change mysql db schema name

How to change mysql database schema name?

Here s what you need to do:
1. Use mysqldump to dump old mysql database.
2. Create new database using mysqladmin.
3. And run the sql generated via mysqldump.

e.g. if you want to change database named "school_old" to "school_new"
Here are the commands.
mysqldump -u username -p -v school_old > old_db_dump.sql
mysqladmin -u username -p create school_new
mysql -u username -p school_new < old_db_dump.sql

Wednesday, June 15, 2011

Updated twitter bookmarklet

Recently twitter updated the way you post tweets. So the previous version of bookmarklet stopped working.

So here is the updated version. Just drag this bookmarklet to your bookmarks bar.

Twitter Bookmarklet

Check out his link if you want to know what this bookmarklet does.
Click here

Here is the code:
javascript: var longUrl=document.location; var url = 'http://api.bit.ly/shorten?version=2.0.1&login=tweetthees&apiKey=R_e1266a2cb3177ea0a9e1114cc49d8ad9&longUrl='+longUrl; loadScript(url+'&callback=tweetme'); function loadScript(scriptURL){ var scriptElem = document.createElement('SCRIPT'); scriptElem.setAttribute('language','JavaScript'); scriptElem.setAttribute('src', scriptURL); document.body.appendChild(scriptElem); } function tweetme(json){ var shortLink=json.results[longUrl].shortUrl; window.location='http://twitter.com/intent/tweet?text=Reading: '+document.title+' '+shortLink }

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