<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom"><title>varun pant</title><subtitle>Cloud,maps,GIS,Google Cloud,Google Maps,Openlayer,Javascript,go,Hadoop,BigData,Spark</subtitle><link href="http://www.varunpant.com/" /><link href="http://www.varunpant.com/feed.xml" rel="self" /><id>http://www.varunpant.com//</id><rights>Copyright (c) 2017 Varun Pant. The content on this feed is licensed under Creative Commons Attribution 3.0 License.</rights><icon>http://www.varunpant.com/static/images/favicon.ico</icon><updated>2019-09-09T00:00:00z</updated><author><name>varun pant</name><email>varun@varunpant.com</email></author><entry><title>how to install the latest python 3 on mac</title><link href="http://www.varunpant.com/posts/how-to-install-the-latest-python-3-on-mac" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-install-the-latest-python-3-on-mac</id><published>2019-09-09T00:00:00z</published><updated>2019-09-09T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Here is a quick guide on installing Python3 on a mac&lt;/p&gt;

&lt;h3&gt;Installation&lt;/h3&gt;

&lt;pre&gt;brew update
brew upgrade
sudo mkdir -p /usr/local/Frameworks
sudo chown -R $(whoami) /usr/local/* 
brew install python3
brew link python3
brew doctor
&lt;/pre&gt;
 

&lt;h3&gt;Aliasing&lt;/h3&gt;
 &lt;pre&gt;echo &#34;alias python=/usr/local/bin/python3.7&#34; &amp;gt;&amp;gt; ~/.zshrc&lt;/pre&gt;
&lt;p&gt;or&lt;/p&gt;
&lt;pre&gt;echo &#34;alias python=/usr/local/bin/python3.7&#34; &amp;gt;&amp;gt; ~/.bashrc&lt;/pre&gt;
&lt;p&gt;You could probably have just done this as well&lt;/p&gt;
&lt;pre&gt;alias python=&#39;python3&#39;
alias pip=&#39;pip3&#39;
&lt;/pre&gt;

&lt;p&gt;I hope this is useful&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category></entry><entry><title>how to play apple music on alexa in uk</title><link href="http://www.varunpant.com/posts/how-to-play-apple-music-on-alexa-in-uk" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-play-apple-music-on-alexa-in-uk</id><published>2019-04-10T00:00:00z</published><updated>2019-04-10T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;&amp;nbsp;You can now use Alexa to play Apple Music on Amazon Echo speakers.&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&amp;nbsp;It&#39;s just available for Echo devices and now customers in UK can also connect their apple music account with Alexa.&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;&amp;nbsp;1. Open the Alexa app then sign into your Amazon account and make sure that your Echo device is connected.&lt;/p&gt;&lt;p&gt;&amp;nbsp;2. Open Menu (top left icon), then select settings.&lt;/p&gt;&lt;p&gt;&amp;nbsp;3. Select Music.&lt;/p&gt;&lt;p&gt;&amp;nbsp;4. Select &#34;Link New Service&#34;&lt;/p&gt;&lt;p&gt;&amp;nbsp;5. Tap, Apple music Icon&lt;/p&gt;&lt;p&gt;&amp;nbsp;6. You will be prompted to enable Apple music skill and asked to sign into Apple account and provide access.&lt;/p&gt;&lt;p&gt;&amp;nbsp;7. Finally choose apple music as default music service.&amp;nbsp;&lt;/p&gt;</content><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category></entry><entry><title>download file using webdriver firefox and python selenium</title><link href="http://www.varunpant.com/posts/download-file-using-webdriver-firefox-and-python-selenium" rel="alternate" /><id>http://www.varunpant.com/posts/download-file-using-webdriver-firefox-and-python-selenium</id><published>2019-02-24T00:00:00z</published><updated>2019-02-24T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Selenium is one of my favourite tool for automation.&lt;/p&gt;&lt;p&gt;In this post, I will demonstrate some basic code to download a file from a website in a headless mode , and also provide a docker file to make things simpler.&lt;/p&gt;&lt;h3&gt;Python Code&lt;/h3&gt;&lt;p&gt;Here is some basic code which will make an attempt to download a &lt;strong&gt;7zip exe. &lt;/strong&gt;&lt;/p&gt;&lt;pre class=&#34;ql-syntax&#34; spellcheck=&#34;false&#34;&gt;from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import os
import time

print(&#34;******************************** STARTING ********************************&#34;)

display = Display(visible=0, size=(1024, 768))
display.start()

# To prevent download dialog
profile = webdriver.FirefoxProfile()
profile.set_preference(&#39;browser.download.folderList&#39;, 2) # custom location
profile.set_preference(&#39;browser.download.manager.showWhenStarting&#39;, False)
profile.set_preference(&#39;browser.download.dir&#39;, &#39;/srv/download&#39;)
profile.set_preference(&#34;browser.download.manager.alertOnEXEOpen&#34;, False)
profile.set_preference(&#34;browser.download.manager.closeWhenDone&#34;, False)
profile.set_preference(&#34;browser.download.manager.focusWhenStarting&#34;, False)
#application/octet-stream,application/vnd.ms-excel&amp;nbsp;
profile.set_preference(&#39;browser.helperApps.neverAsk.saveToDisk&#39;, &#39;application/x-msdownload,application/octet-stream&#39;)
try:
&amp;nbsp; &amp;nbsp; browser = webdriver.Firefox(profile)
&amp;nbsp; &amp;nbsp; browser.get(&#39;https://www.7-zip.org/&#39;)
&amp;nbsp; &amp;nbsp; download_button = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, &#39;td.Item a&#39;)))
&amp;nbsp; &amp;nbsp; download_button.click()
&amp;nbsp; &amp;nbsp; print(&#34;clicked...&#34;)
&amp;nbsp; &amp;nbsp; time.sleep(10)&amp;nbsp;
&amp;nbsp; &amp;nbsp; print (os.listdir(&#34;/srv/download&#34;))
except Exception as ex:
&amp;nbsp; &amp;nbsp; print(ex)
&amp;nbsp;
browser.close()
display.stop()


print(&#34;******************************** FINITO ********************************&#34;)
&lt;/pre&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;The code is fairly simple , we need&lt;/p&gt;&lt;ol&gt;&lt;li&gt;pyvirtualdisplay, to support the webdriver .&lt;/li&gt;&lt;li&gt;FirefoxProfile, to auto accept the firefox download model screen.&lt;/li&gt;&lt;li&gt;The code sets /srv/download as the download location, more details in Makefile shown in the end of this post.&lt;/li&gt;&lt;li&gt;Finally, we set &#39;application/x-msdownload,application/octet-stream&#39; as our allowed file mime type.&lt;/li&gt;&lt;/ol&gt;&lt;h3&gt;Python dependencies&lt;/h3&gt;&lt;ol&gt;&lt;li&gt;selenium&lt;/li&gt;&lt;li&gt;pyvirtualdisplay&lt;/li&gt;&lt;/ol&gt;&lt;pre class=&#34;ql-syntax&#34; spellcheck=&#34;false&#34;&gt;pip install selenium pyvirtualdisplay
&lt;/pre&gt;&lt;h3&gt;DockerFile&lt;/h3&gt;&lt;pre class=&#34;ql-syntax&#34; spellcheck=&#34;false&#34;&gt;FROM python:2.7-stretch


RUN apt-get update &amp;amp;&amp;amp; apt-get install -yq \
&amp;nbsp; &amp;nbsp; firefox-esr \
&amp;nbsp; &amp;nbsp; chromium \
&amp;nbsp; &amp;nbsp; git-core \
&amp;nbsp; &amp;nbsp; xvfb \
&amp;nbsp; &amp;nbsp; xsel \
&amp;nbsp; &amp;nbsp; unzip \
&amp;nbsp; &amp;nbsp; python-pytest \
&amp;nbsp; &amp;nbsp; libgconf2-4 \
&amp;nbsp; &amp;nbsp; libncurses5 \
&amp;nbsp; &amp;nbsp; libxml2-dev \
&amp;nbsp; &amp;nbsp; libxslt-dev \
&amp;nbsp; &amp;nbsp; libz-dev \
&amp;nbsp; &amp;nbsp; xclip=0.12+svn84-4+b1


# GeckoDriver v0.19.1
RUN wget -q &#34;https://github.com/mozilla/geckodriver/releases/download/v0.19.1/geckodriver-v0.19.1-linux64.tar.gz&#34; -O /tmp/geckodriver.tgz \
&amp;nbsp; &amp;nbsp; &amp;amp;&amp;amp; tar zxf /tmp/geckodriver.tgz -C /usr/bin/ \
&amp;nbsp; &amp;nbsp; &amp;amp;&amp;amp; rm /tmp/geckodriver.tgz


# chromeDriver v2.35
RUN wget -q &#34;https://chromedriver.storage.googleapis.com/2.35/chromedriver_linux64.zip&#34; -O /tmp/chromedriver.zip \
&amp;nbsp; &amp;nbsp; &amp;amp;&amp;amp; unzip /tmp/chromedriver.zip -d /usr/bin/ \
&amp;nbsp; &amp;nbsp; &amp;amp;&amp;amp; rm /tmp/chromedriver.zip


# create symlinks to chromedriver and geckodriver (to the PATH)
RUN ln -s /usr/bin/geckodriver /usr/bin/chromium-browser \
&amp;nbsp; &amp;nbsp; &amp;amp;&amp;amp; chmod 777 /usr/bin/geckodriver \
&amp;nbsp; &amp;nbsp; &amp;amp;&amp;amp; chmod 777 /usr/bin/chromium-browser


RUN pip install selenium pyvirtualdisplay
&lt;/pre&gt;&lt;h3&gt;Running python code inside Docker container&lt;/h3&gt;&lt;p&gt;A simple command as shown below will execute the script in docker, which will create a folder locally called download and download the 7zip.exe into it.&lt;/p&gt;&lt;pre class=&#34;ql-syntax&#34; spellcheck=&#34;false&#34;&gt;#Build image from Dockerfile
docker build -t docker-selenium
#Run image after mounting the folder at &#34;${PWD}:/srv&#34; and mapping it with /srv in docker container.
docker run -v &#34;${PWD}:/srv&#34;&amp;nbsp; -w /srv --name img -d docker-selenium tail -f /dev/null
# I have used a make file locally to execute python command python run main.py
docker exec img make run
docker stop img
docker rm img
&lt;/pre&gt;&lt;h3&gt;Makefile&lt;/h3&gt;&lt;p&gt;Here is the make file which will makes things easier.&lt;/p&gt;&lt;pre class=&#34;ql-syntax&#34; spellcheck=&#34;false&#34;&gt;img_name := docker-selenium


deps:
	pip install selenium pyvirtualdisplay


run:
	python main.py


docker-run:
	docker run -v &#34;${PWD}:/srv&#34;&amp;nbsp; -w /srv --name img -d $(img_name) tail -f /dev/null
	docker exec img make run
	docker stop img
	docker rm img


build:
	docker build -t $(img_name) .
&lt;/pre&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;h3&gt;Chorme in UI Mode&lt;/h3&gt;&lt;pre class=&#34;ql-syntax&#34; spellcheck=&#34;false&#34;&gt;from selenium import webdriver
import os
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


browser = webdriver.Chrome()
browser.get(&#39;https://www.7-zip.org/&#39;)
download_button = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, &#39;td.Item a&#39;)))
download_button.click()
time.sleep(10)&amp;nbsp;
&lt;/pre&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;The Code above is just a snippet if someone needs to quickly download any file from web url using selenium.&lt;/p&gt;&lt;p&gt;Hope this helps.&lt;/p&gt;</content><category label="docker" scheme="http://www.varunpant.com/topics/docker/1" term="docker"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category></entry><entry><title>web crawling or scraping using scrapy in python</title><link href="http://www.varunpant.com/posts/web-crawling-or-scraping-using-scrapy-in-python" rel="alternate" /><id>http://www.varunpant.com/posts/web-crawling-or-scraping-using-scrapy-in-python</id><published>2018-12-02T00:00:00z</published><updated>2018-12-02T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;
  &lt;g class=&#34;gr_ gr_39 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace&#34; id=&#34;39&#34; data-gr-id=&#34;39&#34;&gt;Scrapy&lt;/g&gt; is a very popular web scraping/crawling framework, I have been using it for quite some time now.&lt;/p&gt;

&lt;p&gt;In this post, I will demonstrate creating a very basic web crawler.&lt;/p&gt;

&lt;h3 id=&#34;toc_0&#34;&gt;Install Scrapy&lt;/h3&gt;

&lt;p&gt;Installation is via pip &lt;code&gt;pip install scrapy&lt;/code&gt;&lt;/p&gt;

&lt;h3 id=&#34;toc_1&#34;&gt;Minimalistic Code&lt;/h3&gt;

&lt;p&gt;A very simple scraper is created like this&lt;/p&gt;

&lt;div&gt;&lt;pre&gt;&lt;code class=&#34;language-none&#34;&gt;import scrapy
class MySpider(scrapy.Spider):
    name = &#34;MySpider&#34;
    start_urls = [&#39;https://varunpant.com&#39;] 
    def parse(self, response):
        # Get page title using xpath.
        page_title = response.xpath(&#39;//title/text()&#39;).extract_first()
        print(page_title)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;To &lt;strong&gt;&lt;g class=&#34;gr_ gr_58 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace&#34; id=&#34;58&#34; data-gr-id=&#34;58&#34;&gt;Run&lt;/g&gt;&lt;/strong&gt;
  &lt;g class=&#34;gr_ gr_58 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace&#34; id=&#34;58&#34; data-gr-id=&#34;58&#34;&gt; ,&lt;/g&gt; simply type &lt;code&gt;scrapy runspider scraper.py&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Running, above code will output something like below&lt;/p&gt;

&lt;div&gt;&lt;pre&gt;&lt;code class=&#34;language-none&#34;&gt;2018-12-02 14:01:18 [scrapy.utils.log] INFO: Scrapy 1.5.1 started (bot: scrapybot)
2018-12-02 14:01:18 [scrapy.utils.log] INFO: Versions: lxml 4.2.5.0, libxml2 2.9.8, cssselect 1.0.3, parsel 1.5.1, w3lib 1.19.0, Twisted 18.9.0, Python 2.7.15 (default, Oct  2 2018, 11:42:04) - [GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.11.45.2)], pyOpenSSL 18.0.0 (OpenSSL 1.1.0j  20 Nov 2018), cryptography 2.4.2, Platform Darwin-18.2.0-x86_64-i386-64bit
2018-12-02 14:01:18 [scrapy.crawler] INFO: Overridden settings: {&#39;SPIDER_LOADER_WARN_ONLY&#39;: True}
2018-12-02 14:01:18 [scrapy.middleware] INFO: Enabled extensions:
[&#39;scrapy.extensions.memusage.MemoryUsage&#39;,
 &#39;scrapy.extensions.logstats.LogStats&#39;,
 &#39;scrapy.extensions.telnet.TelnetConsole&#39;,
 &#39;scrapy.extensions.corestats.CoreStats&#39;]
2018-12-02 14:01:18 [scrapy.middleware] INFO: Enabled downloader middlewares:
[&#39;scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware&#39;,
 &#39;scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware&#39;,
 &#39;scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware&#39;,
 &#39;scrapy.downloadermiddlewares.useragent.UserAgentMiddleware&#39;,
 &#39;scrapy.downloadermiddlewares.retry.RetryMiddleware&#39;,
 &#39;scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware&#39;,
 &#39;scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware&#39;,
 &#39;scrapy.downloadermiddlewares.redirect.RedirectMiddleware&#39;,
 &#39;scrapy.downloadermiddlewares.cookies.CookiesMiddleware&#39;,
 &#39;scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware&#39;,
 &#39;scrapy.downloadermiddlewares.stats.DownloaderStats&#39;]
2018-12-02 14:01:18 [scrapy.middleware] INFO: Enabled spider middlewares:
[&#39;scrapy.spidermiddlewares.httperror.HttpErrorMiddleware&#39;,
 &#39;scrapy.spidermiddlewares.offsite.OffsiteMiddleware&#39;,
 &#39;scrapy.spidermiddlewares.referer.RefererMiddleware&#39;,
 &#39;scrapy.spidermiddlewares.urllength.UrlLengthMiddleware&#39;,
 &#39;scrapy.spidermiddlewares.depth.DepthMiddleware&#39;]
2018-12-02 14:01:18 [scrapy.middleware] INFO: Enabled item pipelines:
[]
2018-12-02 14:01:18 [scrapy.core.engine] INFO: Spider opened
2018-12-02 14:01:18 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2018-12-02 14:01:18 [scrapy.extensions.telnet] DEBUG: Telnet console listening on 127.0.0.1:6023
2018-12-02 14:01:18 [scrapy.core.engine] DEBUG: Crawled (200) &amp;lt;get https:=&#34;&#34; varunpant.com=&#34;&#34;&amp;gt; (referer: None)
2018-12-02 14:01:18 [scrapy.core.engine] INFO: Closing spider (finished)
2018-12-02 14:01:18 [scrapy.statscollectors] INFO: Dumping Scrapy stats:
{&#39;downloader/request_bytes&#39;: 212,
 &#39;downloader/request_count&#39;: 1,
 &#39;downloader/request_method_count/GET&#39;: 1,
 &#39;downloader/response_bytes&#39;: 12403,
 &#39;downloader/response_count&#39;: 1,
 &#39;downloader/response_status_count/200&#39;: 1,
 &#39;finish_reason&#39;: &#39;finished&#39;,
 &#39;finish_time&#39;: datetime.datetime(2018, 12, 2, 14, 1, 18, 850998),
 &#39;log_count/DEBUG&#39;: 2,
 &#39;log_count/INFO&#39;: 7,
 &#39;memusage/max&#39;: 50581504,
 &#39;memusage/startup&#39;: 50577408,
 &#39;response_received_count&#39;: 1,
 &#39;scheduler/dequeued&#39;: 1,
 &#39;scheduler/dequeued/memory&#39;: 1,
 &#39;scheduler/enqueued&#39;: 1,
 &#39;scheduler/enqueued/memory&#39;: 1,
 &#39;start_time&#39;: datetime.datetime(2018, 12, 2, 14, 1, 18, 570736)}
2018-12-02 14:01:18 [scrapy.core.engine] INFO: Spider closed (finished)
Varun Pant Blog | Index&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;In the last line, one can see that the page title &lt;strong&gt;Varun Pant Blog | Index&lt;/strong&gt; was printed.&lt;/p&gt;

&lt;p&gt;The principle of a web scraper is generally quite simple,&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Start from a seed
    &lt;g class=&#34;gr_ gr_36 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace&#34; id=&#34;36&#34; data-gr-id=&#34;36&#34;&gt;url&lt;/g&gt; and extract all hyperlinks.&lt;/li&gt;
  &lt;li&gt;Then crawl each of them, further extracting links until all of them have been visited.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In
  &lt;g class=&#34;gr_ gr_46 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace&#34; id=&#34;46&#34; data-gr-id=&#34;46&#34;&gt;
    &lt;g class=&#34;gr_ gr_42 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del multiReplace&#34; id=&#34;42&#34; data-gr-id=&#34;42&#34;&gt;Scrapy&lt;/g&gt;
  &lt;/g&gt;&lt;code&gt;start_urls&lt;/code&gt;
  &lt;g class=&#34;gr_ gr_46 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace&#34; id=&#34;46&#34; data-gr-id=&#34;46&#34;&gt; is&lt;/g&gt; the list of seed
  &lt;g class=&#34;gr_ gr_43 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace&#34; id=&#34;43&#34; data-gr-id=&#34;43&#34;&gt;urls&lt;/g&gt; to begin scraping.&lt;/p&gt;

&lt;p&gt;One can also provide another
  &lt;g class=&#34;gr_ gr_38 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace&#34; id=&#34;38&#34; data-gr-id=&#34;38&#34;&gt;varibale&lt;/g&gt; to add domain constraint. &lt;code&gt;allowed_domains  = [&#34;varunpant.com&#34;]&lt;/code&gt; so that links which lead out of the principal domain are rejected.&lt;/p&gt;

&lt;p&gt;Scrappy takes care of ensuring that links which have already been visited are not visited again.&lt;/p&gt;

&lt;h3 id=&#34;toc_2&#34;&gt;Extracting Links&lt;/h3&gt;

&lt;p&gt;In the simple example above, the code does not extract hyperlinks from the response body,
  &lt;g class=&#34;gr_ gr_55 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace&#34; id=&#34;55&#34; data-gr-id=&#34;55&#34;&gt;lets&lt;/g&gt; modify it to do so.&lt;/p&gt;

&lt;div&gt;&lt;pre&gt;&lt;code class=&#34;language-none&#34;&gt;import scrapy
class MySpider(scrapy.Spider):
    name = &#34;MySpider&#34;
    start_urls = [&#39;https://varunpant.com&#39;] 
    def parse(self, response):
        all_links = response.xpath(&#39;*//a/@href&#39;).extract()
        for link in all_links:
            print(link)&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;
  &lt;g class=&#34;gr_ gr_52 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace&#34; id=&#34;52&#34; data-gr-id=&#34;52&#34;&gt;
    &lt;g class=&#34;gr_ gr_51 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-del replaceWithoutSep&#34; id=&#34;51&#34; data-gr-id=&#34;51&#34;&gt;Line &lt;/g&gt;
  &lt;/g&gt;&lt;code&gt;all_links = response.xpath(&#39;*//a/@href&#39;).extract()&lt;/code&gt;
  &lt;g class=&#34;gr_ gr_52 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Style multiReplace&#34; id=&#34;52&#34; data-gr-id=&#34;52&#34;&gt;
    &lt;g class=&#34;gr_ gr_51 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Punctuation only-del replaceWithoutSep&#34; id=&#34;51&#34; data-gr-id=&#34;51&#34;&gt;&lt;/g&gt;
    &lt;g class=&#34;gr_ gr_51 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Punctuation only-del replaceWithoutSep&#34; id=&#34;51&#34; data-gr-id=&#34;51&#34;&gt;,&lt;/g&gt;
  &lt;/g&gt; uses
  &lt;g class=&#34;gr_ gr_37 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace&#34; id=&#34;37&#34; data-gr-id=&#34;37&#34;&gt;xpath&lt;/g&gt; and extracts all hyperlinks in the page.&lt;/p&gt;

&lt;div&gt;&lt;pre&gt;&lt;code class=&#34;language-none&#34;&gt;/
/contact
/archives
/feed
/posts/integration-testing-with-apache-beam-using-pubsub-and-bigtable-emulators-and-direct-runner
http://varunpant.com/posts/integration-testing-with-apache-beam-using-pubsub-and-bigtable-emulators-and-direct-runner#disqus_thread
/posts/gdal-2-on-mac-with-homebrew
http://varunpant.com/posts/gdal-2-on-mac-with-homebrew#disqus_thread
/posts/how-to-print-bar-chart-in-chrome-browser-console
http://varunpant.com/posts/how-to-print-bar-chart-in-chrome-browser-console#disqus_thread
/posts/how-to-make-https-requests-with-python-httplib2-ssl
http://varunpant.com/posts/how-to-make-https-requests-with-python-httplib2-ssl#disqus_thread
/posts/how-to-read-json-from-web-http-request-of-url-via-python-urllib
http://varunpant.com/posts/how-to-read-json-from-web-http-request-of-url-via-python-urllib#disqus_thread
/posts/minimum-insertions-to-form-a-palindrome
http://varunpant.com/posts/minimum-insertions-to-form-a-palindrome#disqus_thread
/posts/inverse-weighted-distance-interpolation-in-golang
http://varunpant.com/posts/inverse-weighted-distance-interpolation-in-golang#disqus_thread
/posts/basic-sorting-algorithms-implemented-in-golang
http://varunpant.com/posts/basic-sorting-algorithms-implemented-in-golang#disqus_thread
/posts/reading-and-writing-binary-files-in-go-lang
http://varunpant.com/posts/reading-and-writing-binary-files-in-go-lang#disqus_thread
/posts/create-linear-color-gradient-in-go
http://varunpant.com/posts/create-linear-color-gradient-in-go#disqus_thread
/?page=2
http://stackoverflow.com/users/95967
https://www.linkedin.com/in/varunpant
mailto:varun@varunpant.com
https://github.com/varunpant&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The final step is to make the parse generator method &lt;code&gt;yield&lt;/code&gt; &lt;code&gt;response&lt;/code&gt; like so&lt;/p&gt;

&lt;div&gt;&lt;pre&gt;&lt;code class=&#34;language-none&#34;&gt;import scrapy

class MySpider(scrapy.Spider):
    name = &#34;MySpider&#34;
    start_urls = [&#39;https://varunpant.com&#39;] 
    allowed_domains = [&#34;varunpant.com&#34;]
    def parse(self, response):
        page_title = response.xpath(&#39;//title/text()&#39;).extract_first()
        print(page_title)
        all_links = response.xpath(&#39;*//a/@href&#39;).extract()
        for link in all_links:
            yield scrapy.Request(
                    response.urljoin(link),
                    callback=self.parse
                )&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This should crawl all hyperlinks found with each page.&lt;/p&gt;

&lt;h3 id=&#34;toc_3&#34;&gt;Save all &lt;g class=&#34;gr_ gr_40 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace&#34; id=&#34;40&#34; data-gr-id=&#34;40&#34;&gt;crawlled&lt;/g&gt; pages to link&lt;/h3&gt;

&lt;p&gt;Here is a minimalistic code snippet, which saves all
  &lt;g class=&#34;gr_ gr_41 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace&#34; id=&#34;41&#34; data-gr-id=&#34;41&#34;&gt;crawlled&lt;/g&gt; pages to the disk.&lt;/p&gt;

&lt;div&gt;&lt;pre&gt;&lt;code class=&#34;language-none&#34;&gt;import scrapy
import unicodedata
import re
from pprint import pprint

class MySpider(scrapy.Spider):
    name = &#34;MySpider&#34;
    allowed_domains = [&#34;varunpant.com&#34;]
    start_urls = [&#39;https://varunpant.com&#39;]

    def slugify(self,value): 
        value = unicodedata.normalize(&#39;NFKD&#39;, value).encode(&#39;ascii&#39;, &#39;ignore&#39;)
        value = unicode(re.sub(&#39;[^\w\s-]&#39;, &#39;&#39;, value).strip().lower())
        value = unicode(re.sub(&#39;[-\s]+&#39;, &#39;-&#39;, value))
        return value

    def save(self,name,content):
         #save to html in the pages folder
        p = &#34;pages/%s.html&#34;
        fn = self.slugify(name)
        with open(p%name,&#34;w&#34;) as f:
            f.write(content.encode(&#34;utf-8&#34;))

    def parse(self, response):
        
        page_title = response.xpath(&#39;//title/text()&#39;).extract_first()
        page_body = response.body.decode(&#34;utf-8&#34;)
        self.save(page_title,page_body)
        all_links = response.xpath(&#39;*//a/@href&#39;).extract()
        for link in all_links:
            yield scrapy.Request(
                    response.urljoin(link),
                    callback=self.parse
                )&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category></entry><entry><title>integration testing with apache beam using pubsub and bigtable emulators and direct runner</title><link href="http://www.varunpant.com/posts/integration-testing-with-apache-beam-using-pubsub-and-bigtable-emulators-and-direct-runner" rel="alternate" /><id>http://www.varunpant.com/posts/integration-testing-with-apache-beam-using-pubsub-and-bigtable-emulators-and-direct-runner</id><published>2018-08-03T00:00:00z</published><updated>2018-08-03T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;h3&gt;Summary&lt;/h3&gt;
&lt;p&gt;Recently I have been looking into ways to test my &lt;b&gt;Apache Beam&lt;/b&gt; pipelines at work. Most common use cases of Beam generally involves either batch reading data from GCS and writing to analytical platforms such as Big Query or stream reading data from Pubsub and writing to perhaps Bigtable.&lt;/p&gt;
&lt;p&gt;A pipelines consists of transforms and its generally easy to test them in isolation as a independent unit test per stage, however I am personally a big fan of &#34;end-to-end&#34; testing or “Integration testing” and this is where things can sometimes get tricky.&lt;/p&gt;

&lt;p&gt;
  Apache beam has various &lt;a href=&#34;https://beam.apache.org/documentation/runners/capability-matrix/&#34;&gt;runners&lt;/a&gt;, the&#34; one of interest&#34; for testing purposes is the &lt;a href=&#34;https://beam.apache.org/documentation/runners/direct/&#34;&gt;Direct runner&lt;/a&gt;.

&lt;/p&gt;

&lt;p&gt;From the doc:&lt;/p&gt;
&lt;blockquote&gt;
  The Direct Runner executes pipelines on your machine and is designed to validate that pipelines adhere to the Apache Beam model as closely as possible. Instead of focusing on efficient pipeline execution, the Direct Runner performs additional checks to ensure that users do not rely on semantics that are not guaranteed by the model. Some of these checks include:
  &lt;ul&gt;
    &lt;li&gt;enforcing immutability of elements.&lt;/li&gt;
    &lt;li&gt;enforcing encodability of elements.&lt;/li&gt;
    &lt;li&gt;elements are processed in an arbitrary order at all points.&lt;/li&gt;
    &lt;li&gt;serialization of user functions (DoFn, CombineFn, etc.)&lt;/li&gt;
  &lt;/ul&gt;
&lt;/blockquote&gt;
&lt;p&gt;It’s also important to realise the memory considerations as mentioned below.&lt;/p&gt;
&lt;blockquote&gt;
  Local execution is limited by the memory available in your local environment. It is highly recommended that you run your pipeline with data sets small enough to fit in local memory. You can create a small in-memory data set using a Create transform, or you can use a Read transform to work with small local or remote files.
&lt;/blockquote&gt;
&lt;p&gt;

  I am going to show an example where I have written a basic integration test which listens for some payload from pubsub emulator, transforms the data to Mutation and then writes it to BigTable emulator, there are no aggregations performed hence every thing works in global window and triggering of a write is immediate. This example can also serve as a good way to front your data warehouse with apache beam for dynamically scalable writing,i.e as the pubsub message load would increase, beam would add more workers and as the load would decrease beam would reduce the workers.

&lt;/p&gt;
&lt;h4&gt;SetUp PubSub Emulator&lt;/h4&gt;
&lt;p&gt;Guide is &lt;a href=&#34;https://cloud.google.com/pubsub/docs/emulator&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h5&gt;Code&lt;/h5&gt;
&lt;pre&gt;gcloud components install pubsub-emulator
gcloud components update
gcloud beta emulators pubsub start [options]
&lt;/pre&gt;
&lt;p&gt;
  optional step
&lt;/p&gt;
&lt;pre&gt;$(gcloud beta emulators pubsub env-init)
&lt;/pre&gt;
&lt;p&gt;&lt;i&gt;You don’t need to run the optional step above as we would supply the url in the beam options.
&lt;/i&gt;&lt;/p&gt;




&lt;h4&gt;SetUp BigTable Emulator&lt;/h4&gt;
&lt;p&gt;Guide is &lt;a href=&#34;https://cloud.google.com/bigtable/docs/emulator&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h5&gt;Code&lt;/h5&gt;
&lt;pre&gt;gcloud components update beta
gcloud beta emulators bigtable start
&lt;/pre&gt;

&lt;p&gt;&lt;i&gt;This step is required if you want to use &lt;a href=&#34;https://cloud.google.com/bigtable/docs/cbt-overview&#34;&gt;cbt&lt;/a&gt; to point to BigTable to browse the data.
&lt;/i&gt;&lt;/p&gt;

&lt;pre&gt;$(gcloud beta emulators bigtable env-init)
&lt;/pre&gt;

&lt;h3&gt;Code&lt;/h3&gt;
&lt;p&gt;Here are the steps involved in the pipeline.&lt;/p&gt;
&lt;pre&gt;  		Pipeline p = Pipeline.create(options);

        p.apply(&#34;ReadPubsubMessages&#34;,
               
               PubsubIO.readMessages().fromSubscription(options.getSubscription()))

               .apply(&#34;ConvertMessageToBTMutation&#34;, new PubsubMessageToBigTableMutation())


                .apply(&#34;WriteToBigTable&#34;,

                        CloudBigtableIO.writeToTable(

                                getConfigurationForTable(options).withTableId(BIGTABLE_TABLE_ID).build()
                ));

        p.run().waitUntilFinish();
&lt;/pre&gt;
&lt;p&gt;The pipeline is triggered via main method which is extended to include a testing variable&lt;/p&gt;
&lt;pre&gt;public interface EventListenerOptions extends StreamingOptions, PubsubOptions {
  
        @Description(&#34;Pub/Sub subscription to read from&#34;)
        @Validation.Required
        @Default.String(&#34;projects/test-project/subscriptions/evtsToBigTbl&#34;)
        String getSubscription();

        void setSubscription(String value);

        @Description(&#34;The Google Cloud project ID for the Cloud Bigtable instance.&#34;)
        @Validation.Required
        @Default.String(&#34;BT-PROD-PROJECT&#34;)
        String getBigtableProjectId();

        void setBigtableProjectId(String bigtableProjectId);

        @Description(&#34;The Google Cloud Bigtable instance ID .&#34;)
        @Validation.Required
        @Default.String(&#34;BT-PROD-INSTANCE&#34;)
        String getBigtableInstanceId();

        void setBigtableInstanceId(String bigtableInstanceId);


        @Description(&#34;For integration test.&#34;)
        @Validation.Required
        @Default.Boolean(true)
        Boolean getTesting();

        void setTesting(Boolean testing);


    }
&lt;/pre&gt;
&lt;p&gt;Insure that the project and instance id for bigtable matches those in the cofiguration file &lt;code&gt;~/.cbtrc&lt;/code&gt; for bigtable, you can check this by typing in &lt;code&gt;cbt&lt;/code&gt; in the console.&lt;/p&gt;
&lt;pre&gt; EventListenerOptions options = PipelineOptionsFactory.fromArgs(args).withValidation()
                .as(EventListenerOptions.class);
        options.setProject(&#34;PubSubToBigTable&#34;);

        if (options.getTesting()) {

            options.setPubsubRootUrl(PUBSUB_EMULATOR_HOST);//must point to emulator http://localhost:8085
            options.setBigtableProjectId(BIGTABLE_PROJECT_ID);//must be the same as in ~/.cbtrc
            options.setBigtableInstanceId(BIGTABLE_INSTANCE_ID);//must be the same as in ~/.cbtrc

        }

        RunPipeLine(options);

&lt;/pre&gt;
&lt;p&gt;The intreseting bits are as follows&lt;/p&gt;
&lt;h3&gt;Override PubsubOptions url in Beam &lt;/h3&gt;
&lt;p&gt;This was easy, just make sure your options extend &lt;code&gt;org.apache.beam.sdk.io.gcp.pubsub.PubsubOptions&lt;/code&gt;. This includes a method called &lt;code&gt;options.setPubsubRootUrl&lt;/code&gt;, whcih then can be pointed to emulator.
&lt;/p&gt;
&lt;h3&gt;Point beam to BigTable Emulator.&lt;/h3&gt;
&lt;p&gt;This took me ages to figure out and eventually after digging in the code I was able to locate a bunch of properties which must be overridden.&lt;/p&gt;
&lt;pre&gt;private static CloudBigtableTableConfiguration.Builder getConfigurationForTable(EventListenerOptions options) {

       CloudBigtableTableConfiguration.Builder config = new CloudBigtableTableConfiguration.Builder()
                .withProjectId(options.getBigtableProjectId())
                .withInstanceId(options.getBigtableInstanceId());
                
        if (options.getTesting()) {
            config.withConfiguration(&#34;google.bigtable.instance.admin.endpoint.host&#34;, &#34;localhost&#34;)
                    .withConfiguration(&#34;google.bigtable.admin.endpoint.host&#34;, &#34;localhost&#34;)
                    .withConfiguration(&#34;google.bigtable.endpoint.host&#34;, &#34;localhost&#34;)
                    .withConfiguration(&#34;google.bigtable.endpoint.port&#34;, &#34;8086&#34;)
                    .withConfiguration(&#34;google.bigtable.use.plaintext.negotiation&#34;, &#34;true&#34;)
                    .withConfiguration(&#34;google.bigtable.grpc.read.partial.row.timeout.ms&#34;, &#34;5000&#34;);
        }

        return config;


    }
&lt;/pre&gt;

&lt;p&gt;and thats it, calling &lt;code&gt;  StarterPipeline.main(new String[]{&#34;--testing=true&#34;, &#34;--runner=DirectRunner&#34;});&lt;/code&gt; should do the trick.&lt;/p&gt;

&lt;p&gt;I will soon include full code.&lt;/p&gt;</content><category label="dataflow" scheme="http://www.varunpant.com/topics/dataflow/1" term="dataflow"></category><category label="apache-beam" scheme="http://www.varunpant.com/topics/apache-beam/1" term="apache-beam"></category><category label="java" scheme="http://www.varunpant.com/topics/java/1" term="java"></category><category label="google" scheme="http://www.varunpant.com/topics/google/1" term="google"></category><category label="bigdata" scheme="http://www.varunpant.com/topics/bigdata/1" term="bigdata"></category><category label="testing" scheme="http://www.varunpant.com/topics/testing/1" term="testing"></category></entry><entry><title>gdal 2 on mac with homebrew</title><link href="http://www.varunpant.com/posts/gdal-2-on-mac-with-homebrew" rel="alternate" /><id>http://www.varunpant.com/posts/gdal-2-on-mac-with-homebrew</id><published>2018-02-13T00:00:00z</published><updated>2018-02-13T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;GDAL is one of the most frequently used utility in my toolkit. I am writing this post to make it easier for others to install it from scratch on their macs.&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Setting up GDAL&lt;/h3&gt;
&lt;p&gt;The traditional way has always been to visit the dear old&amp;nbsp;&lt;a href=&#34;http://www.kyngchaos.com/software/frameworks&#34;&gt;kyngchaos.com&lt;/a&gt;, and install&amp;nbsp;&amp;nbsp;“GDAL Complete” Framework vi deb installer. Do make sure that GDAL Framework is in your path otherwise something like this always helps&lt;/p&gt;
&lt;p&gt;
  &lt;code&gt;echo &#39;export PATH=/Library/Frameworks/GDAL.framework/Programs:$PATH&#39; &amp;gt;&amp;gt; ~/.bash_profile &lt;/code&gt;
  &lt;code&gt;source ~/.bash_profile &lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;&amp;nbsp;To test your installation, run the Terminal command&amp;nbsp;&lt;code&gt;gdalinfo --version&lt;/code&gt;.&amp;nbsp;
&lt;/p&gt;
&lt;h3&gt;VIA Homebrew&lt;/h3&gt;
&lt;p&gt;Below is the recipe to upgrade via homebrew to latest GDAL 2.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Update&lt;/b&gt; &lt;/p&gt;
&lt;blockquote&gt; &lt;b&gt;gdal2&lt;/b&gt; is now a proper formulae &lt;code&gt;brew install gdal2&lt;/code&gt; should work.&lt;/blockquote&gt;
&lt;p&gt;&lt;/p&gt;

&lt;p&gt;If you have already installed GDAL via gdal formula &lt;code&gt;brew install gdal&lt;/code&gt;, then you need to do the following to upgrade.&lt;/p&gt;

&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;brew unlink gdal
brew tap osgeo/osgeo4mac &amp;amp;&amp;amp; brew tap --repair
brew install jasper netcdf # gdal dependencies
brew install gdal2 --with-armadillo \
--with-complete --with-libkml --with-unsupported
brew link --force gdal2
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Finally Verify&lt;/p&gt;

&lt;p&gt;&lt;/p&gt;&lt;pre&gt;$&amp;gt; gdal-config --version
2.1.1
$&amp;gt; gdal-config --libs
-L/usr/local/Cellar/gdal2/2.1.1/lib -lgdal
$&amp;gt; gdal-config --cflags
-I/usr/local/Cellar/gdal2/2.1.1/include
&lt;/pre&gt;</content><category label="gdal" scheme="http://www.varunpant.com/topics/gdal/1" term="gdal"></category><category label="homebrew" scheme="http://www.varunpant.com/topics/homebrew/1" term="homebrew"></category><category label="mac" scheme="http://www.varunpant.com/topics/mac/1" term="mac"></category><category label="gis" scheme="http://www.varunpant.com/topics/gis/1" term="gis"></category></entry><entry><title>how to print bar chart in chrome browser console</title><link href="http://www.varunpant.com/posts/how-to-print-bar-chart-in-chrome-browser-console" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-print-bar-chart-in-chrome-browser-console</id><published>2018-02-05T00:00:00z</published><updated>2018-02-05T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;This post doesn&#39;t really have anything valuable to contribute, just some cool console trick.&lt;/p&gt;
&lt;p&gt;Have you ever wanted to plot out a chart, very quickly ? Did you ever had an urge to visualise a bunch of numbers without having to use a charting api or copy pasting the data in a spreadsheet ? If you did then you might even learn something today :)&lt;/p&gt;
&lt;p&gt;Here is a simple , yet neat way to plot out bunch of numbers in chrome console as a&lt;strong&gt; horizontal bar chart.&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;for(i = 5;i&amp;lt;20;i++){console.log(`%c ${Array(Math.round(i*2)).join(&#39;█&#39;)}`, &#39;color: crimson&#39;);}
&lt;/pre&gt;
&lt;p&gt;
  &lt;img src=&#34;/media/image.png&#34; /&gt;&lt;/p&gt;
&lt;p&gt;
  &lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;Hope you like it as much as I do as well :)&lt;/p&gt;</content><category label="fun" scheme="http://www.varunpant.com/topics/fun/1" term="fun"></category><category label="javascript" scheme="http://www.varunpant.com/topics/javascript/1" term="javascript"></category></entry><entry><title>how to make https requests with python httplib2 ssl</title><link href="http://www.varunpant.com/posts/how-to-make-https-requests-with-python-httplib2-ssl" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-make-https-requests-with-python-httplib2-ssl</id><published>2018-02-02T00:00:00z</published><updated>2018-02-02T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Here are few snippets to make &lt;strong&gt;secure&lt;/strong&gt; &lt;strong&gt;http&lt;/strong&gt; requests using various python libraries.&lt;/p&gt;

&lt;h3&gt;httplib2&lt;/h3&gt;

&lt;pre&gt;import httplib2

link = &#34;https://example.com
h = httplib2.Http(&#34;.cache&#34;)
r, content = h.request(link, &#34;GET&#34;)
&lt;/pre&gt;

&lt;h5&gt;another exmaple&lt;/h5&gt;

&lt;pre&gt;import httplib2

h = httplib2.Http(&#34;.cache&#34;)
h.add_credentials(&#39;user&#39;, &#39;pass&#39;)
r, content = h.request(&#34;https://api.github.com&#34;, &#34;GET&#34;)

print r[&#39;status&#39;]
print r[&#39;content-type&#39;]
&lt;/pre&gt;


&lt;h3&gt;Urllib2&lt;/h3&gt;
&lt;p&gt;Here is a simmilar example using &lt;b&gt;urlib2&lt;/b&gt; for comparison and lines of code.&lt;/p&gt;
&lt;pre&gt;import urllib2

gh_url = &#39;https://example.com&#39;

auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(None, gh_url, &#39;user&#39;, &#39;password&#39;)

opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
handler = urllib2.urlopen(gh_url)

print handler.getcode()
print handler.headers.getheader(&#39;content-type&#39;)
&lt;/pre&gt;

&lt;h3&gt;Requests&lt;/h3&gt;

&lt;p&gt;
  The easiest, has always been &lt;b&gt;requests&lt;/b&gt;.
&lt;/p&gt;

&lt;pre&gt;import requests

r = requests.get(&#39;https://example.com&#39;)
#r = requests.get(&#39;https://example.com&#39;, auth=(&#39;user&#39;, &#39;pass&#39;))
print r.status_code
print r.headers[&#39;content-type&#39;]
&lt;/pre&gt;


&lt;p&gt;Hope this helps.&lt;/p&gt;</content><category label="ssl" scheme="http://www.varunpant.com/topics/ssl/1" term="ssl"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="httplib" scheme="http://www.varunpant.com/topics/httplib/1" term="httplib"></category></entry><entry><title>how to read json from web http request of url via python urllib</title><link href="http://www.varunpant.com/posts/how-to-read-json-from-web-http-request-of-url-via-python-urllib" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-read-json-from-web-http-request-of-url-via-python-urllib</id><published>2018-01-30T00:00:00z</published><updated>2018-01-30T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;I generally am looking for a quick snippet to issue an http request using urllib2 lib. &lt;/p&gt;
&lt;p&gt;Here is a quick snippet to do so&lt;/p&gt;

&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;url = &#34;https://api.waqi.info/mapq/bounds/?bounds=%20-180.0,-85.0,180.0,85.0&#34;

import urllib2
import json
from pprint import pprint

req = urllib2.Request(url)
opener = urllib2.build_opener()
f = opener.open(req)

#data varibale recieves the parsed json
data = json.loads(f.read())


print len(data)
for r in data:
    pprint(r)
    print &#34;-&#34;*50
&lt;/pre&gt;
&lt;p&gt;Hope this helps&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="http" scheme="http://www.varunpant.com/topics/http/1" term="http"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category><category label="urllib2" scheme="http://www.varunpant.com/topics/urllib2/1" term="urllib2"></category></entry><entry><title>minimum insertions to form a palindrome</title><link href="http://www.varunpant.com/posts/minimum-insertions-to-form-a-palindrome" rel="alternate" /><id>http://www.varunpant.com/posts/minimum-insertions-to-form-a-palindrome</id><published>2017-10-15T00:00:00z</published><updated>2017-10-15T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;h3&gt;Brute-force approach&lt;/h3&gt;
&lt;p&gt;Here I present a few approaches to deduce &#34;minimum insertions&#34; required to convert a string into a palindrome.&lt;/p&gt;
&lt;p&gt;The basic brute force approach is quite simple, given a string with length L, start comparing, the first character from left and the last character while scanning inwards.&lt;/p&gt;
&lt;p&gt;
  Here is a basic test for a palindrome.&lt;/p&gt;
&lt;pre&gt;def ispalindrome(s):
    L = len(s) 
    for i in range(L):
        if s[i] != s[L - i - 1]:
            return False,i,L-i -1
    return True,0,0
&lt;/pre&gt;

&lt;p&gt;The above code returns &lt;strong&gt;True&lt;/strong&gt; if the string is a palindrome or returns &lt;strong&gt;False&lt;/strong&gt; with &lt;strong&gt;mismatching&lt;/strong&gt; indices.&lt;/p&gt;

&lt;p&gt;

  &lt;code&gt;result,left,right = ispalindrome(&#34;aba&#34;)&lt;/code&gt; will return &lt;code&gt;True,0,0&lt;/code&gt; while &lt;code&gt;result,left,right = ispalindrome(&#34;abc&#34;)&lt;/code&gt; will return &lt;code&gt;False,0,2&lt;/code&gt; indicating the characters at 0&lt;sup&gt;th&lt;/sup&gt; position, &lt;b&gt;a&lt;/b&gt;, does not match with character at 2&lt;sup&gt;nd&lt;/sup&gt; position, &lt;b&gt;c&lt;/b&gt;


&lt;/p&gt;

&lt;p&gt;
  Once the indices are found a basic recursive solution can be written to &lt;b&gt;reflect&lt;/b&gt; the missing strings from the mismatching indices.

&lt;/p&gt;&lt;pre&gt;def to_palendrome_left_reflect(s):
    p,l,r = ispalindrome(s)
    if not p: 
        if l == 0:
            s = s[r] + s
        else:
            s = s[0:l]+ s[r] + s[l:]
        return to_palendrome_left_reflect(s)
    else: 
        return s
        
def to_Palendrome_rigth_reflect(s):
    p,l,r = ispalindrome(s)
    if not p: 
        if l == 0:
            s =  s + s[l]
        else:
            s = s[0:r+1] + s[l] + s[r+1:]
        return to_Palendrome_rigth_reflect(s)
    else: 
        return s
&lt;/pre&gt;
&lt;p&gt;
  Some tests are as follows.
&lt;/p&gt;&lt;pre&gt;print to_palendrome_left_reflect(&#34;ab&#34;) #bab
print to_palendrome_left_reflect(&#34;abc&#34;)#cbabc

print to_Palendrome_rigth_reflect(&#34;ab&#34;) #aba
print to_Palendrome_rigth_reflect(&#34;abc&#34;)#abcba

&lt;/pre&gt;

&lt;p&gt;To find which is smaller we write a quick function as shown below.&lt;/p&gt;
&lt;pre&gt;def find_Minimum_Insertions(s):
    L = len(s)
    left_insertion = to_palendrome_left_reflect(s)
    right_insertion = to_Palendrome_rigth_reflect(s)
    delta_l = len(left_insertion) - L
    delta_r = len(right_insertion) - L

    print &#34;LEFT:&#34;,left_insertion
    print &#34;RIGHT:&#34;,right_insertion
    if delta_l &amp;lt; delta_r:
        print &#34;MIN-LEFT&#34;,delta_l
    else:
        print &#34;MIN-RIGHT&#34;,delta_r
&lt;/pre&gt;

&lt;p&gt;Its important to consider that above mentioned techniques ignores &lt;strong&gt;deletion&lt;/strong&gt; or &lt;strong&gt;susbtitution&lt;/strong&gt;.&lt;/p&gt;


&lt;h3&gt;Another approach which only calculates count, while considering all possible operations.&lt;/h3&gt;

&lt;pre&gt;def findMinInsertions(s,start,end):
    
    if start == end:
        return 0
    if start == end -1:
        if s[start] == s[end]:
            return 0
        return 1
    if s[start] == s[end]:
        return findMinInsertions(s,start+1,end - 1)
    else:
        a = findMinInsertions(s,start,end - 1)
        b = findMinInsertions(s,start+1,end) 
        return min(a,b)+1
&lt;/pre&gt;

&lt;h3&gt;Dynamic Programming approach (fastest)&lt;/h3&gt;
&lt;pre&gt;def findMin_Insertions_count_Dynamicly(s):
    n = len(s)
    table = [[0 for i in range(n)]  for j in range(n)]
    start = 0
    end = 0 
    for y in range(0,n-1):
        a = 0
        for  x in range(n):
            if x&amp;gt;y-1:
                table[y][x] = a
                a+=1
                 
    return table[0][n-1]
&lt;/pre&gt;
&lt;p&gt;This, by far is the fastest of all methods, but only works for string which are not already a&lt;b&gt;palindrome&lt;/b&gt; , the trick is to have a &lt;code&gt;n x n &lt;/code&gt; matrices and then fill in a particual order from left to right, increasing the gaps per row as shown below, for string &lt;b&gt;abcde&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;a b c d e
----------
0 1 2 3 4
0 0 1 2 3 
0 0 0 1 2 
0 0 0 0 1 
0 0 0 0 0
&lt;/pre&gt;

&lt;p&gt;The &lt;code&gt;M[0][n-1]&lt;/code&gt; is &lt;b&gt;3&lt;/b&gt;&lt;/p&gt;

&lt;p&gt;Hope this helps.&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="algorithm" scheme="http://www.varunpant.com/topics/algorithm/1" term="algorithm"></category></entry><entry><title>Inverse weighted distance interpolation in golang</title><link href="http://www.varunpant.com/posts/inverse-weighted-distance-interpolation-in-golang" rel="alternate" /><id>http://www.varunpant.com/posts/inverse-weighted-distance-interpolation-in-golang</id><published>2017-09-07T00:00:00z</published><updated>2017-09-07T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;&lt;strong&gt;Inverse distance weighting&lt;/strong&gt;&amp;nbsp;(IDW) is a type of deterministic method for multivariate&amp;nbsp;&lt;strong&gt;interpolation&lt;/strong&gt;&amp;nbsp;with a known scattered set of points. The assigned values to unknown points are calculated with a&amp;nbsp;&lt;strong&gt;weighted&lt;/strong&gt;&amp;nbsp;average of the values available at the known points.&lt;/p&gt;
&lt;p&gt;This technique, explicitly makes the assumption that things that are close to one another are more alike than those that are farther apart. To predict a value for any unmeasured location, IDW uses the measured values surrounding the prediction location. The measured values closest to the prediction location have more influence on the predicted value than those farther away. IDW assumes that each measured point has a local influence that diminishes with distance. It gives greater weights to points closest to the prediction location, and the weights diminish as a function of distance, hence the name inverse distance weighted.&lt;/p&gt;
&lt;p&gt;Here is an implementation in golang. The code reads from shapefile and then interpolates a &amp;nbsp;100 x 100 grid.&lt;/p&gt;

&lt;pre&gt;package main

import (
	&#34;fmt&#34;

	&#34;github.com/lukeroth/gdal&#34;
	&#34;math&#34;
	&#34;image&#34;
	&#34;image/color&#34;
	&#34;os&#34;
	&#34;image/png&#34;
)

type point struct {
	x      int
	y      int
	weight float64
}

func readShapeFile(path string, rows int, cols int) ([]point, [6]float64) {

	dataset := gdal.OpenDataSource(path, 0)
	defer dataset.Release()

	layer := dataset.LayerByIndex(0)

	extent, _ := layer.Extent(true)
	geotransform := [6]float64{}
	geotransform[0] = extent.MinX()
	geotransform[1] = (extent.MaxX() - extent.MinX()) / float64(cols)
	geotransform[2] = 0
	geotransform[3] = extent.MaxY()
	geotransform[4] = 0
	geotransform[5] = (extent.MinY() - extent.MaxY()) / float64(rows)

	fc, _ := layer.FeatureCount(true)

	var points []point = make([]point, fc)
	for i := 0; i &amp;lt; fc; i++ {
		feature := layer.Feature(i)
		x, y, _ := feature.Geometry().Point(0)
		X := int((x - geotransform[0]) / geotransform[1])
		Y := int((y - geotransform[3]) / geotransform[5])
		points[i] = point{X, Y, feature.FieldAsFloat64(1)}

	}
	return points, geotransform

}

func iwdistance(x int, y int, points []point, power float64, smoothing int) float64 {
	L := len(points)
	nominator := 0.0
	denominator := 0.0
	for i := 0; i &amp;lt; L; i++ {
		pt := points[i]
		dist := math.Sqrt(float64((x-pt.x)*(x-pt.x) + (y-pt.y)*(y-pt.y) + smoothing*smoothing));
		if dist &amp;lt; 0.0000000001 {
			return pt.weight
		}
		nominator = nominator + (pt.weight / math.Pow(dist, power))
		denominator = denominator + (1 / math.Pow(dist, power))
	}

	value := 0.0
	if denominator &amp;gt; 0 {
		value = nominator / denominator
	} else {
		value = -9999
	}
	return value
}

func drawGeoTiff(points []float32, cols int, rows int, geotransform [6]float64) {

	driver, err := gdal.GetDriverByName(&#34;GTiff&#34;)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	dataset := driver.Create(&#34;idw.tif&#34;, cols, rows, 1, gdal.Float32, nil)
	defer dataset.Close()

	spatialRef := gdal.CreateSpatialReference(&#34;&#34;)
	spatialRef.FromEPSG(4326)
	srString, err := spatialRef.ToWKT()
	dataset.SetProjection(srString)
	dataset.SetGeoTransform(geotransform)
	raster := dataset.RasterBand(1)
	raster.SetNoDataValue(-1)
	raster.IO(gdal.Write, 0, 0, cols, rows, points, cols, rows, 0, 0)

}

func HSVtoRGB(h float64, s float64, v float64) (uint8, uint8, uint8) {

	i := math.Floor(h * 6);
	f := h*6 - i;
	p := v * (1 - s);
	q := v * (1 - f*s);
	t := v * (1 - (1-f)*s);
	r := 0.0
	g := 0.0
	b := 0.0
	switch int(i) % 6 {
	case 0:
		{
			r = v
			g = t
			b = p
		}
	case 1:
		{
			r = q
			g = v
			b = p
		}
	case 2:
		{
			r = p
			g = v
			b = t
		}
	case 3:
		{
			r = p
			g = q
			b = v
		}
	case 4:
		{
			r = t
			g = p
			b = v
		}
	case 5:
		{
			r = v
			g = p
			b = q
		}
	}
	return uint8(math.Floor(r * 255)), uint8(math.Floor(g * 255)), uint8(math.Floor(b * 255))
}

func getRGB(value float64) (uint8, uint8, uint8) {

	h := 10 - value/9;
	return HSVtoRGB(h, 1, 1)
}
func drawRaster(points []float32, cols int, rows int, name string) {
	dst := image.NewRGBA(image.Rect(0, 0, cols, rows))

	for x := 0; x &amp;lt; cols; x++ {
		for y := 0; y &amp;lt; rows; y++ {
			pw := float64(points[x+y*cols])
			r, g, b := getRGB(pw)

			c := color.RGBA{

				r,
				g,
				b,
				255,
			}

			dst.Set(x, y, c)
		}
	}

	img, _ := os.Create(name)
	defer img.Close()
	png.Encode(img, dst)
}

func main() {

	w, h := 100, 100
	points, geotransform := readShapeFile(&#34;shp/points.shp&#34;, w, h)

	var power float64 = 2
	var smoothing int = 0

	buffer := make([]float32, w*h)
	for x := 0; x &amp;lt; w; x++ {
		for y := 0; y &amp;lt; h; y++ {
			pw := iwdistance(x, y, points, power, smoothing)
			buffer[x+y*w] = float32(pw)
		}
	}

	drawGeoTiff(buffer, w, h, geotransform)
	drawRaster(buffer, w, h, &#34;idw.png&#34;)

}

&lt;/pre&gt;
&lt;p&gt;
  The results looks like this&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;Geotiff&lt;/p&gt;
&lt;img src=&#34;/media/idw-tiff.jpg&#34; height=&#34;200px&#34; width=&#34;200px&#34; /&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;coloured png&lt;/p&gt;
&lt;img height=&#34;200px&#34; width=&#34;200px&#34; src=&#34;/media/idw.png&#34; /&gt;

&lt;p&gt;&lt;/p&gt;</content><category label="golang" scheme="http://www.varunpant.com/topics/golang/1" term="golang"></category><category label="algorithms" scheme="http://www.varunpant.com/topics/algorithms/1" term="algorithms"></category></entry><entry><title>basic sorting algorithms implemented in golang</title><link href="http://www.varunpant.com/posts/basic-sorting-algorithms-implemented-in-golang" rel="alternate" /><id>http://www.varunpant.com/posts/basic-sorting-algorithms-implemented-in-golang</id><published>2017-09-04T00:00:00z</published><updated>2017-09-04T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;This post includes go-lang based implementation of some of the classic sorting algorithms.&lt;/p&gt;
&lt;p&gt;This article primarily, has been written, as an academic exercise, to not forget the basic principles of sorting.&lt;/p&gt;

&lt;h3&gt;Bubble Sort&lt;/h3&gt;
&lt;p&gt;
  &lt;a href=&#34;http://en.wikipedia.org/wiki/Bubble_sort&#34;&gt;wiki&lt;/a&gt;
  &lt;img src=&#34;https://upload.wikimedia.org/wikipedia/commons/c/c8/Bubble-sort-example-300px.gif&#34; /&gt;
&lt;/p&gt;

&lt;p&gt;Bubble sort is perhaps the simplest of all sorting algorithms, the basic principle is to bubble up the largest (or the smallest) and then the second largest and then the third largest and so on. Each bubble takes the full sweep of the list, hence best-case, average-case as well as the worst-case performance are all O(n&lt;sup&gt;2&lt;/sup&gt;)
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;package main

&lt;l;i++{ for=&#34;&#34; j:=&#34;0;j&amp;lt;&#34; (l-1-i);j++{=&#34;&#34; if=&#34;&#34; items[j]=&#34;&#34;&gt;func BubbleSort( items []int)  {&lt;br /&gt;&lt;br /&gt;   L:=len(items)&lt;br /&gt;&lt;br /&gt;   for  i:=0;i&amp;lt;L;i++{&lt;br /&gt;&lt;br /&gt;      for j:=0;j&amp;lt; (L-1-i);j++{&lt;br /&gt;         if items[j] &amp;gt; items[j+1]{&lt;br /&gt;            items[j], items[j+1] = items[j+1], items[j]&lt;br /&gt;         }&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;}
&lt;/l;i++{&gt;&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;

&lt;h3&gt;Insertion Sort&lt;/h3&gt;
&lt;p&gt;
  &lt;a href=&#34;https://en.wikipedia.org/wiki/Insertion_sort&#34;&gt;wiki&lt;/a&gt;
  &lt;img src=&#34;https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif&#34; /&gt;
&lt;/p&gt;
&lt;p&gt;
  Insertion sort takes each element through the list and inserts it at the right place. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain. Worst-case and average-case performance is O(n2), however the best case is O(n).&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;package main

func InsertionSort(items []int) {&lt;br /&gt;&lt;br /&gt;   L := len(items)&lt;br /&gt;&lt;br /&gt;   for i := 1; i &amp;lt; L; i++ {&lt;br /&gt;&lt;br /&gt;      j := i&lt;br /&gt;      for j &amp;gt; 0 &amp;amp;&amp;amp; items[j] &amp;lt; items[j-1] {&lt;br /&gt;         items[j], items[j-1] = items[j-1], items[j]&lt;br /&gt;         j -= 1&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;}
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;


&lt;h3&gt;Merge Sort&lt;/h3&gt;
&lt;p&gt;
  &lt;a href=&#34;https://en.wikipedia.org/wiki/Merge_sort&#34;&gt;wiki&lt;/a&gt;
  &lt;img src=&#34;https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif&#34; /&gt;
&lt;/p&gt;
&lt;p&gt;
  Mergesort operates by diving the list into two sublist recursively till each sublist contains only one element, it then merges the adjacent list back while sorting each element in the merged list. Best-case, average-case as well as the worst-case eprformance are all O(nlogn)
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;package main&lt;br /&gt;&lt;br /&gt;const NADA int = -1&lt;br /&gt;&lt;br /&gt;func DeepCopy(vals []int) []int {&lt;br /&gt;   tmp := make([]int, len(vals))&lt;br /&gt;   copy(tmp, vals)&lt;br /&gt;   return tmp&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;func MergeSort(items []int) {&lt;br /&gt;&lt;br /&gt;   if len(items) &amp;gt; 1 {&lt;br /&gt;      mid := len(items) / 2&lt;br /&gt;      left := DeepCopy(items[0:mid])&lt;br /&gt;      right := DeepCopy(items[mid:])&lt;br /&gt;&lt;br /&gt;      MergeSort(left)&lt;br /&gt;      MergeSort(right)&lt;br /&gt;&lt;br /&gt;      l := 0&lt;br /&gt;      r := 0&lt;br /&gt;&lt;br /&gt;      for i := 0; i &amp;lt; len(items); i++ {&lt;br /&gt;&lt;br /&gt;         lval := NADA&lt;br /&gt;         rval := NADA&lt;br /&gt;&lt;br /&gt;         if l &amp;lt; len(left) {&lt;br /&gt;            lval = left[l]&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         if r &amp;lt; len(right) {&lt;br /&gt;            rval = right[r]&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;         if (lval != NADA &amp;amp;&amp;amp; rval != NADA &amp;amp;&amp;amp; lval &amp;lt; rval) || rval == NADA {&lt;br /&gt;            items[i] = lval&lt;br /&gt;            l += 1&lt;br /&gt;         } else if (lval != NADA &amp;amp;&amp;amp; rval != NADA &amp;amp;&amp;amp; lval &amp;gt;= rval) || lval == NADA {&lt;br /&gt;            items[i] = rval&lt;br /&gt;            r += 1&lt;br /&gt;         }&lt;br /&gt;&lt;br /&gt;      }&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;

&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;


&lt;h3&gt;Quicksort Sort&lt;/h3&gt;
&lt;p&gt;
  &lt;a href=&#34;https://en.wikipedia.org/wiki/Quicksort&#34;&gt;wiki&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif&#34; /&gt;&lt;/p&gt;
&lt;p&gt;
  Quick sort works by first selecting a pivot element from the list. It then creates two lists, one containing elements less than the pivot and the other containing elements higher than the pivot. It then sorts the two lists and join them with the pivot in between. Just like the Merge sort, when the lists are subdivided to lists of size 1, they are considered as already sorted. Best-case and avergae-case is O(n log n) however the worstcase(very rare) is O(n&lt;sup&gt;2&lt;/sup&gt;)
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;func QuickSort(items []int) {&lt;br /&gt;&lt;br /&gt;   if len(items) &amp;gt; 1 {&lt;br /&gt;      pivot_index := len(items) / 2&lt;br /&gt;      var smaller_items = []int{}&lt;br /&gt;      var larger_items = []int{}&lt;br /&gt;&lt;br /&gt;      for i := range items {&lt;br /&gt;         val := items[i]&lt;br /&gt;         if i != pivot_index {&lt;br /&gt;            if val &amp;lt; items[pivot_index] {&lt;br /&gt;               smaller_items = append(smaller_items, val)&lt;br /&gt;            } else {&lt;br /&gt;               larger_items = append(larger_items, val)&lt;br /&gt;            }&lt;br /&gt;         }&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      QuickSort(smaller_items)&lt;br /&gt;      QuickSort(larger_items)&lt;br /&gt;&lt;br /&gt;      var merged []int = append(append(append([]int{}, smaller_items...), []int{items[pivot_index]}...), larger_items...)&lt;br /&gt;      //merged := MergeLists(smaller_items, items[pivot_index], larger_items)&lt;br /&gt;&lt;br /&gt;      for j := 0; j &amp;lt; len(items); j++ {&lt;br /&gt;         items[j] = merged[j]&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;h3&gt;Heap Sort&lt;/h3&gt;
&lt;p&gt;
  &lt;a href=&#34;http://en.wikipedia.org/wiki/Heapsort&#34;&gt;wiki&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://upload.wikimedia.org/wikipedia/commons/1/1b/Sorting_heapsort_anim.gif&#34; /&gt;
&lt;/p&gt;

&lt;p&gt; Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum,best-case, average-case as well as the worst-caseeprformance are all O(nlogn)
&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;package main

&lt;br /&gt;func heapify(items []int, idx int, size int) {&lt;br /&gt;   l := 2*idx + 1 // left = 2*i + 1&lt;br /&gt;   r := 2*idx + 2 // right = 2*i + 2&lt;br /&gt;&lt;br /&gt;   var largest int;&lt;br /&gt;   if l &amp;lt;= size &amp;amp;&amp;amp; items[l] &amp;gt; items[idx] {&lt;br /&gt;      largest = l&lt;br /&gt;   } else {&lt;br /&gt;      largest = idx&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   if r &amp;lt;= size &amp;amp;&amp;amp; items[r] &amp;gt; items[largest] {&lt;br /&gt;      largest = r&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   if largest != idx {&lt;br /&gt;      t := items[idx]&lt;br /&gt;      items[idx] = items[largest]&lt;br /&gt;      items[largest] = t&lt;br /&gt;      heapify(items, largest, size)&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;func HeapSort(items []int) {&lt;br /&gt;&lt;br /&gt;   L := len(items) //heap size&lt;br /&gt;   m := int(L / 2) //middle&lt;br /&gt;&lt;br /&gt;   for i := m; i &amp;gt;= 0; i-- {&lt;br /&gt;&lt;br /&gt;      heapify(items, i, L-1)&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;   F := L - 1&lt;br /&gt;   for j := F; j &amp;gt;= 0; j-- {&lt;br /&gt;      t := items[0]&lt;br /&gt;      items[0] = items[j]&lt;br /&gt;      items[j] = t&lt;br /&gt;      F -= 1&lt;br /&gt;      heapify(items, 0, F)&lt;br /&gt;   }&lt;br /&gt;&lt;br /&gt;}&lt;br /&gt;
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;

&lt;p&gt;Finally to run these algos I have written a quick main program&lt;/p&gt;


&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;import (
  &#34;fmt&#34;
  &#34;time&#34;
  &#34;math/rand&#34;
)

func main() {

  fmt.Println(&#34;Preparing!&#34;)
  var randomVals = []int{}
  s1 := rand.NewSource(time.Now().UnixNano())
  r1 := rand.New(s1)
  for i := 0; i &amp;lt; 11; i++ {
    randomVals = append(randomVals, r1.Intn(99)+1)
  }

  fmt.Println(&#34;Unsorted!&#34;)
  fmt.Println(randomVals)
  //BubbleSortrandomVals()
  //InsertionSort(randomVals)
  //MergeSort(randomVals)
  //QuickSort(randomVals)
  HeapSort(randomVals)

  fmt.Println(&#34;sorted!&#34;)
  fmt.Println(randomVals)
}&lt;/pre&gt;&lt;pre&gt;finally some nice visuals &lt;a href=&#34;https://imgur.com/gallery/RM3wl&#34;&gt;here&lt;/a&gt;&lt;/pre&gt;</content><category label="golang" scheme="http://www.varunpant.com/topics/golang/1" term="golang"></category><category label="algorithms" scheme="http://www.varunpant.com/topics/algorithms/1" term="algorithms"></category></entry><entry><title>reading and writing binary files in go lang</title><link href="http://www.varunpant.com/posts/reading-and-writing-binary-files-in-go-lang" rel="alternate" /><id>http://www.varunpant.com/posts/reading-and-writing-binary-files-in-go-lang</id><published>2017-08-29T00:00:00z</published><updated>2017-08-29T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Reading and writing binary files can often be a fast and very efficient alternatives to csv. They obviously have their challenges, however in this post I intent to present a very basic example of saving models (struct) into binary file and later reading it.&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;package main

import (
	&#34;log&#34;
	&#34;os&#34;
	&#34;encoding/binary&#34;
	&#34;bytes&#34;
	&#34;fmt&#34;
	&#34;math/rand&#34;
	&#34;time&#34;
)

//this type represnts a record with three fields
type payload struct {
	One float32
	Two float64
	Three uint32
}

func main() {

	writeFile()
	readFile()

}

func readFile() {

	file, err := os.Open(&#34;test.bin&#34;)
	defer file.Close()
	if err != nil {
		log.Fatal(err)
	}

	m := payload{}
	for i := 0; i &amp;lt; 10; i++ {
		data := readNextBytes(file, 16)
		buffer := bytes.NewBuffer(data)
		err = binary.Read(buffer, binary.BigEndian, &amp;amp;m)
		if err != nil {
			log.Fatal(&#34;binary.Read failed&#34;, err)
		}

		fmt.Println(m)
	}

}

func readNextBytes(file *os.File, number int) []byte {
	bytes := make([]byte, number)

	_, err := file.Read(bytes)
	if err != nil {
		log.Fatal(err)
	}

	return bytes
}

func writeFile() {
	file, err := os.Create(&#34;test.bin&#34;)
	defer file.Close()
	if err != nil {
		log.Fatal(err)
	}

	r := rand.New(rand.NewSource(time.Now().UnixNano()))

	for i := 0; i &amp;lt; 10; i++ {


		s := &amp;amp;payload{
			r.Float32(),
			r.Float64(),
			r.Uint32(),
		}
		var bin_buf bytes.Buffer
		binary.Write(&amp;amp;bin_buf, binary.BigEndian, s)
		//b :=bin_buf.Bytes()
		//l := len(b)
		//fmt.Println(l)
		writeNextBytes(file, bin_buf.Bytes())

	}
}
func writeNextBytes(file *os.File, bytes []byte) {

	_, err := file.Write(bytes)

	if err != nil {
		log.Fatal(err)
	}

}


&lt;/pre&gt;

&lt;p&gt;&lt;/p&gt;

&lt;p&gt;The code presented above will randomly populate 10 records of type &lt;code&gt;payload&lt;/code&gt; and save it to a binary file, then it will read those 10 records as well. &lt;/p&gt;

&lt;h3&gt;Performance&lt;/h3&gt;

&lt;p&gt;To see how long it takes to create and then read &lt;code&gt;10000000&lt;/code&gt; records try changeing the &lt;code&gt;10&lt;/code&gt; to &lt;code&gt;10000000&lt;/code&gt; and then building an executable by running &lt;code&gt;go build filename.go&lt;/code&gt;, once built execute by typing &lt;code&gt;time ./filename&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;on my macbook pro it took &lt;code&gt; 0m35.433s&lt;/code&gt; to generate and then read all records (without priniting them on shell)
&lt;/p&gt;&lt;pre&gt;real    0m35.433s
user    0m16.713s
sys     0m19.031s
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;
  hope this helps.
&lt;/p&gt;</content><category label="golang" scheme="http://www.varunpant.com/topics/golang/1" term="golang"></category></entry><entry><title>Create linear color gradient in go </title><link href="http://www.varunpant.com/posts/create-linear-color-gradient-in-go" rel="alternate" /><id>http://www.varunpant.com/posts/create-linear-color-gradient-in-go</id><published>2017-08-28T00:00:00z</published><updated>2017-08-28T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Go doesn&#39;t have any builtin gradient functions to paint/fill the background of a raster, however it has all the required primitives one needs to create a very basic linear gradient.&lt;/p&gt;
&lt;p&gt;Here is a basic code which defines a 256 x 256 image, then calculates the value of each pixel in the raster based on a linear interpolation formula.&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;package main

import (
	&#34;image&#34;
	&#34;image/color&#34;
	&#34;image/png&#34;
	&#34;log&#34;
	&#34;os&#34;
	&#34;os/exec&#34;

)
var(
	colorB = [3]float64{248, 54, 0}
	colorA = [3]float64{254, 140, 0}
)

var(
	width = 256
	height = 256
	max = float64(width)
)

func linearGradient(x, y float64) (uint8, uint8, uint8) {
	d := x/max
	r := colorA[0] + d * (colorB[0] - colorA[0])
	g :=  colorA[1] + d * (colorB[1] - colorA[1])
	b :=  colorA[2] + d * (colorB[2] - colorA[2])
	return uint8(r), uint8(g), uint8(b)
}

func main() {

	var w, h int = width, height
	dst := image.NewRGBA(image.Rect(0, 0, w, h)) //*NRGBA (image.Image interface)

	for x := 0; x &amp;lt; w; x++ {
		for y := 0; y &amp;lt; h; y++ {
			r, g, b := linearGradient(float64(x), float64(y))
			c := color.RGBA{

				r,
				g,
				b,
				255,
			}
			dst.Set(x, y, c)
		}
	}

	img, _ := os.Create(&#34;new.png&#34;)
	defer img.Close()
	png.Encode(img, dst) //Encode writes the Image m to w in PNG format.

	Show(img.Name())

}

// show  a specified file by Preview.app for OS X(darwin)
func Show(name string) {
	command := &#34;open&#34;
	arg1 := &#34;-a&#34;
	arg2 := &#34;/Applications/Preview.app&#34;
	cmd := exec.Command(command, arg1, arg2, name)
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
}


&lt;/pre&gt;
&lt;p&gt;Here is how the generated image looks like&lt;/p&gt;
&lt;p&gt;
  &lt;img src=&#34;/media/new.png&#34; /&gt;
&lt;/p&gt;
&lt;p&gt;
  Function &lt;code&gt;linearGradient&lt;/code&gt; is where all the magic happens, this method takes in x and y pixel locations and then calculates the appropriate gradient value based on the maximum width (256) to produce a horizontal gradient, now if one was to change the the &lt;code&gt;d := x/max&lt;/code&gt; to &lt;code&gt;d := y/max&lt;/code&gt;, this now becomes a top down-gradient instead of left-right (our image is 256x256 hence max of both width and height is 256) like so
&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/media/linear-gradient-vertical.png&#34; /&gt;&lt;/p&gt; or swap colors arrays to get a differrent affect.

&lt;h3&gt;Circular Gradient&lt;/h3&gt;
&lt;p&gt;To get something like a circular gradient replace &lt;code&gt;linearGradient&lt;/code&gt; function with &lt;code&gt;circularRadient&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;func circularGradient(x, y float64) (uint8, uint8, uint8) {
	var dx, dy float64 = cenX - x, cenY - y
	d:= math.Sqrt(dx*dx+dy*dy)
	p := d/255
	 
		r := colorA[0] + p*(colorB[0]-colorA[0])
		g := colorA[1] + p*(colorB[1]-colorA[1])
		b := colorA[2] + p*(colorB[2]-colorA[2])
		return uint8(r), uint8(g), uint8(b)
	 
}
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;This should result in an image like below &lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/media/circular-gradient.png&#34; /&gt;&lt;/p&gt; or if you want to confine it to the circle try this
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;func circularGradient(x, y float64) (uint8, uint8, uint8) {
	var dx, dy float64 = cenX - x, cenY - y
	d:= math.Sqrt(dx*dx+dy*dy)
	p := d/255
	if d &amp;lt; 128 {
		r := colorA[0] + p*(colorB[0]-colorA[0])
		g := colorA[1] + p*(colorB[1]-colorA[1])
		b := colorA[2] + p*(colorB[2]-colorA[2])
		return uint8(r), uint8(g), uint8(b)
	}

	return 0,0,0

}

&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/media/circular-gradient-2.png&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Hope this helps.&lt;/p&gt;</content><category label="golang" scheme="http://www.varunpant.com/topics/golang/1" term="golang"></category></entry><entry><title>merge sort in python</title><link href="http://www.varunpant.com/posts/merge-sort-in-python" rel="alternate" /><id>http://www.varunpant.com/posts/merge-sort-in-python</id><published>2017-07-23T00:00:00z</published><updated>2017-07-23T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;div&gt;Many useful algorithms are recursive in structure: to solve a given problem, they call themselves recursively one or more times to deal with closely related subproblems.&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;div&gt;These algorithms typically follow a divide-and-conquer approach: they break the problem into several subproblems that are similar to the original problem&lt;/div&gt;
&lt;div&gt;but smaller in size, solve the subproblems recursively, and then combine these solutions to create a solution to the original problem.&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;ul&gt;
  &lt;div&gt;The divide-and-conquer paradigm involves three steps at each level of the recursion:&lt;/div&gt;
  &lt;div&gt;
    &lt;br /&gt;
  &lt;/div&gt;
  &lt;li&gt;Divide the problem into a number of subproblems that are smaller instances of the same problem.&lt;/li&gt;
  &lt;li&gt;Conquer the subproblems by solving them recursively. If the subproblem sizes are small enough, however, just solve the subproblems in a straightforward manner.&lt;/li&gt;
  &lt;li&gt;Combine the solutions to the subproblems into the solution for the original problem.&lt;/li&gt;
&lt;/ul&gt;

&lt;br /&gt;

&lt;div&gt;The merge sort algorithm closely follows the divide-and-conquer paradigm. Intuitively,&lt;/div&gt;
&lt;div&gt;it operates as follows.&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;ul&gt;
  &lt;li&gt;Divide: Divide the n-element sequence to be sorted into two subsequences of n=2 elements each.&lt;/li&gt;
  &lt;li&gt;Conquer: Sort the two subsequences recursively using merge sort.&lt;/li&gt;
  &lt;li&gt;Combine: Merge the two sorted subsequences to produce the sorted answer.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
  &lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;here is a basic code in python&lt;/p&gt;
&lt;p&gt;
  &lt;br /&gt;
&lt;/p&gt;

&lt;pre&gt;from __future__ import division
import sys
SENTINEL = sys.maxint

def merge(input_array,first,middle,last):
    n1 = middle - first + 1
    n2 = last - middle

    L = [None for t in range(n1+1)]
    R = [None for t in range(n2+1)]

    
    for i in range(n1):
        L[i] = input_array[first + i - 1]
        
    for j in range(n2):
        R[j] =input_array[middle + j]
         

    L[n1] = SENTINEL
     
    R[n2] = SENTINEL
     

    i = 0
    j = 0 
    for k in range(first-1,last): 
        if L[i] &amp;lt;= R[j]:
            input_array[k] = L[i]
            i = i + 1
        else:
            input_array[k] = R[j]
            j = j + 1



def mergeSort(input_array,first,last):
    if first &amp;lt; last:
        middle =  int((first + last)/2) 
        mergeSort(input_array,first,middle)
        mergeSort(input_array,middle + 1,last)
        
        merge(input_array,first,middle,last)


arr = [5,2,4,7,1,3,2,6]
 
mergeSort(arr,1,len(arr))
print arr&lt;/pre&gt;

&lt;p&gt;Hope this helps ;)&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="algorithms" scheme="http://www.varunpant.com/topics/algorithms/1" term="algorithms"></category></entry><entry><title>Using Geotiff as datasource via gdal </title><link href="http://www.varunpant.com/posts/using-geotiff-as-datasource-via-gdal" rel="alternate" /><id>http://www.varunpant.com/posts/using-geotiff-as-datasource-via-gdal</id><published>2016-12-21T00:00:00z</published><updated>2016-12-21T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;&lt;img src=&#34;/media/image_377996742841482328085822.png&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Recently, I have been working on algorithms which needs elevation data as well as Land Cover data, with world coverage. Google has an excellent elevation API however free usage comes with a limit. &lt;/p&gt;
&lt;p&gt;While searching, I came across a dataset in &lt;a href=&#34;https://en.wikipedia.org/wiki/GeoTIFF&#34;&gt;geotiff&lt;/a&gt; format for &lt;a href=&#34;http://landcover.usgs.gov/global_climatology.php&#34;&gt;landcover&lt;/a&gt; as well as a &lt;a href=&#34;http://www.cgiar-csi.org/data/srtm-90m-digital-elevation-database-v4-1&#34;&gt;processed version&lt;/a&gt; of &lt;a href=&#34;https://drive.google.com/drive/folders/0B_J08t5spvd8VWJPbTB3anNHamc&#34;&gt;world elevation&lt;/a&gt;. &amp;nbsp;Elevation data comes in various resolution (250m,500m,1km), landcover is 500m .&lt;/p&gt;
&lt;p&gt;So how do we read it ? In python its quite easy to use&lt;a href=&#34;https://pypi.python.org/pypi/GDAL/&#34;&gt; osgo/gdal&lt;/a&gt; library and read all bands. Geotiff is a rster file and values can be packed in every band (which is basically a 2d array).&lt;/p&gt;
&lt;pre&gt;landUsageLookup = [
    &#34;Water&#34;,  # 1
    &#34;Evergreen Needle leaf Forest&#34;,  # 2
    &#34;Evergreen Broadleaf Forest&#34;,  # 3
    &#34;Deciduous Needle leaf Forest&#34;,  # 4
    &#34;Deciduous Broadleaf Forest&#34;,  # 5
    &#34;Mixed Forests&#34;,  # 6
    &#34;Closed Shrublands&#34;,  # 7
    &#34;Open Shrublands&#34;,  # 8
    &#34;Woody Savannas&#34;,  # 9
    &#34;Savannas&#34;,  # 10
    &#34;Grasslands&#34;,  # 11
    &#34;Permanent Wetland&#34;,  # 12
    &#34;Croplands&#34;,  # 13
    &#34;Urban and Built-Up&#34;,  # 14
    &#34;Cropland/Natural Vegetation Mosaic&#34;,  # 15
    &#34;Snow and Ice&#34;,  # 16
    &#34;Barren or Sparsely Vegetated&#34;  # 17
]

def getLandUsage(latitude, longitude):
    ds = gdal.Open(&#34;data/LCType.tif&#34;) 
    gt = ds.GetGeoTransform()
     
    band = ds.GetRasterBand(1)
    px = int((longitude - gt[0]) / gt[1])  # x pixel
    py = int((latitude - gt[3]) / gt[5])  # y pixel
    structval = band.ReadRaster(px, py, 1, 1, buf_type=gdal.GDT_UInt16)
    lc = struct.unpack(&#39;h&#39;, structval)[0]
    return lc, landUsageLookup[lc]

&lt;/pre&gt;

&lt;p&gt;The code sample above takes in Lat/Lng in wgs84 &amp;nbsp;and convert them into 2d index.&lt;/p&gt;
&lt;p&gt;Hope this helps :)&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="gdal" scheme="http://www.varunpant.com/topics/gdal/1" term="gdal"></category><category label="osgeo" scheme="http://www.varunpant.com/topics/osgeo/1" term="osgeo"></category><category label="geotiff" scheme="http://www.varunpant.com/topics/geotiff/1" term="geotiff"></category></entry><entry><title>How to create fishnets or geospatial grids</title><link href="http://www.varunpant.com/posts/how-to-create-fishnets-or-geospatial-grids" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-create-fishnets-or-geospatial-grids</id><published>2016-12-11T00:00:00z</published><updated>2016-12-11T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;There are many use cases in GIS world, where the information has to be aggregated, an easy way to achieve this is via gridding or binning, where the area of interest is divided into small sections called grids or bins. &lt;/p&gt;
&lt;p&gt;These sections are mostly of rectangular form (which can be easily converted into geotiffs), but in some cases even circles or hexagons are also used.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/media/image_963791002841481453621913.png&#34; /&gt;
  &lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;You can read a good tutorial from &lt;a href=&#34;https://www.mapbox.com/&#34;&gt;mapbox&lt;/a&gt; using &lt;a href=&#34;http://www.qgis.org/en/site/&#34;&gt;Qgis&lt;/a&gt; with a &lt;a href=&#34;http://michaelminn.com/linux/mmqgis/&#34;&gt;mmqgis&lt;/a&gt;&amp;nbsp;plugin &lt;a href=&#34;https://www.mapbox.com/blog/binning-alternative-point-maps/&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;While MMQGIS is a good enough for most use cases, I was looking for &amp;nbsp;a way to create fishnets or grids by giving the bbox of the region and width/height in meters, which would then make it easy to script the process for any dynamic use.&lt;/p&gt;
&lt;p&gt;Luckily there is a &#34;recipe&#34; available which takes input in &lt;a href=&#34;EPSG:3857&#34;&gt;EPSG:3857&lt;/a&gt;&amp;nbsp;projections and hence takes the width/height of grid cell in meter, &lt;a href=&#34;https://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html#create&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The code is pretty easy to comprehend and creates simple polygons for each computed cell in the layer.&lt;/p&gt;
&lt;pre&gt;import os, sys
import ogr
from math import ceil


def main(outputGridfn,xmin,xmax,ymin,ymax,gridHeight,gridWidth):

    # convert sys.argv to float
    xmin = float(xmin)
    xmax = float(xmax)
    ymin = float(ymin)
    ymax = float(ymax)
    gridWidth = float(gridWidth)
    gridHeight = float(gridHeight)

    # get rows
    rows = ceil((ymax-ymin)/gridHeight)
    # get columns
    cols = ceil((xmax-xmin)/gridWidth)

    # start grid cell envelope
    ringXleftOrigin = xmin
    ringXrightOrigin = xmin + gridWidth
    ringYtopOrigin = ymax
    ringYbottomOrigin = ymax-gridHeight

    # create output file
    outDriver = ogr.GetDriverByName(&#39;ESRI Shapefile&#39;)
    if os.path.exists(outputGridfn):
        os.remove(outputGridfn)
    outDataSource = outDriver.CreateDataSource(outputGridfn)
    outLayer = outDataSource.CreateLayer(outputGridfn,geom_type=ogr.wkbPolygon )
    featureDefn = outLayer.GetLayerDefn()

    # create grid cells
    countcols = 0
    while countcols &amp;lt; cols:
        countcols += 1

        # reset envelope for rows
        ringYtop = ringYtopOrigin
        ringYbottom =ringYbottomOrigin
        countrows = 0

        while countrows &amp;lt; rows:
            countrows += 1
            ring = ogr.Geometry(ogr.wkbLinearRing)
            ring.AddPoint(ringXleftOrigin, ringYtop)
            ring.AddPoint(ringXrightOrigin, ringYtop)
            ring.AddPoint(ringXrightOrigin, ringYbottom)
            ring.AddPoint(ringXleftOrigin, ringYbottom)
            ring.AddPoint(ringXleftOrigin, ringYtop)
            poly = ogr.Geometry(ogr.wkbPolygon)
            poly.AddGeometry(ring)

            # add new geom to layer
            outFeature = ogr.Feature(featureDefn)
            outFeature.SetGeometry(poly)
            outLayer.CreateFeature(outFeature)
            outFeature.Destroy

            # new envelope for next poly
            ringYtop = ringYtop - gridHeight
            ringYbottom = ringYbottom - gridHeight

        # new envelope for next poly
        ringXleftOrigin = ringXleftOrigin + gridWidth
        ringXrightOrigin = ringXrightOrigin + gridWidth

    # Close DataSources
    outDataSource.Destroy()


if __name__ == &#34;__main__&#34;:

    #
    # example run : $ python grid.py &amp;lt;full-path&amp;gt;&amp;lt;output-shapefile-name&amp;gt;.shp xmin xmax ymin ymax gridHeight gridWidth
    #

    if len( sys.argv ) != 8:
        print &#34;[ ERROR ] you must supply seven arguments: output-shapefile-name.shp xmin xmax ymin ymax gridHeight gridWidth&#34;
        sys.exit( 1 )

    main( sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7] )&lt;/pre&gt;
&lt;p&gt;Here is an example usage:&amp;nbsp;&lt;code&gt;python grid.py grid.shp 992325.66 1484723.41 494849.32 781786.14 10000 10000&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Here is an example of a 10km/10 km grid&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/media/image_1504214621671481454352189.png&#34; /&gt;&lt;/p&gt;
&lt;p&gt;
  Python scripts are generally usable in most use cases, how ever incase one needs a Postgis alternative, i.e a function which runs in Postgis database and creates a fishnet in a table, then It might be useful to use a query which I found &lt;a href=&#34;http://gis.stackexchange.com/questions/16374/how-to-create-a-regular-polygon-grid-in-postgis&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;pre&gt;CREATE OR REPLACE FUNCTION public.makegrid_2d (
  bound_polygon public.geometry,
  grid_step integer,
  metric_srid integer = 3857 --metric SRID  
)
RETURNS public.geometry AS
$body$
DECLARE
  BoundM public.geometry; --Bound polygon transformed to the metric projection (with metric_srid SRID)
  Xmin DOUBLE PRECISION;
  Xmax DOUBLE PRECISION;
  Ymax DOUBLE PRECISION;
  X DOUBLE PRECISION;
  Y DOUBLE PRECISION;
  sectors public.geometry[];
  i INTEGER;
BEGIN
  BoundM := ST_Transform($1, $3); --From WGS84 (SRID 4326) to the metric projection, to operate with step in meters
  Xmin := ST_XMin(BoundM);
  Xmax := ST_XMax(BoundM);
  Ymax := ST_YMax(BoundM);

  Y := ST_YMin(BoundM); --current sector&#39;s corner coordinate
  i := -1;
  &amp;lt;&lt;yloop&gt;&amp;gt;
  LOOP
    IF (Y &amp;gt; Ymax) THEN  --Better if generating polygons exceeds the bound for one step. You always can crop the result. But if not you may get not quite correct data for outbound polygons (e.g. if you calculate frequency per sector)
        EXIT;
    END IF;

    X := Xmin;
    &amp;lt;&lt;xloop&gt;&amp;gt;
    LOOP
      IF (X &amp;gt; Xmax) THEN
          EXIT;
      END IF;

      i := i + 1;
      sectors[i] := ST_GeomFromText(&#39;POLYGON((&#39;||X||&#39; &#39;||Y||&#39;, &#39;||(X+$2)||&#39; &#39;||Y||&#39;, &#39;||(X+$2)||&#39; &#39;||(Y+$2)||&#39;, &#39;||X||&#39; &#39;||(Y+$2)||&#39;, &#39;||X||&#39; &#39;||Y||&#39;))&#39;, $3);

      X := X + $2;
    END LOOP xloop;
    Y := Y + $2;
  END LOOP yloop;

  RETURN ST_Transform(ST_Collect(sectors), ST_SRID($1));
END;
$body$
LANGUAGE &#39;plpgsql&#39;;
&lt;/xloop&gt;&lt;/yloop&gt;&lt;/pre&gt;
&lt;p&gt;I hope this helps.&lt;/p&gt;</content><category label="gis" scheme="http://www.varunpant.com/topics/gis/1" term="gis"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="osgeo" scheme="http://www.varunpant.com/topics/osgeo/1" term="osgeo"></category><category label="gdal" scheme="http://www.varunpant.com/topics/gdal/1" term="gdal"></category></entry><entry><title>How to transform projections between Spherical Mercator and EPSG 4326</title><link href="http://www.varunpant.com/posts/how-to-transform-projections-between-spherical-mercator-and-epsg-4326" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-transform-projections-between-spherical-mercator-and-epsg-4326</id><published>2016-12-10T00:00:00z</published><updated>2016-12-10T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;div&gt;
  &lt;p&gt;Projections in GIS are commonly referred to by their “EPSG” codes, these are identifiers managed by the European Petroleum Survey Group. &lt;/p&gt;
  &lt;p&gt;One common identifier is “&lt;a href=&#34;EPSG:4326&#34;&gt;EPSG:4326&lt;/a&gt;”, which describes maps where latitude and longitude are treated as X/Y values. &lt;/p&gt;
  &lt;p&gt;Spherical Mercator has an official designation of &lt;a href=&#34;EPSG:3857.&#34;&gt;EPSG:3857.&lt;/a&gt; However, before this was established, a large amount of software used the identifier &lt;a href=&#34;EPSG:900913.&#34;&gt;EPSG:900913.&lt;/a&gt; This is an unofficial code, but is still the commonly usedin many GIS systems.&lt;/p&gt;
  &lt;p&gt; Any time you see the string “&lt;a href=&#34;EPSG:4326&#34;&gt;EPSG:4326&lt;/a&gt;”, you can assume it describes latitude/longitude coordinates.&lt;/p&gt;
  &lt;p&gt; Any time you see the string “&lt;a href=&#34;EPSG:900913&#34;&gt;EPSG:900913&lt;/a&gt;”, it will be describing coordinates in meters in x/y.&lt;/p&gt;
  &lt;p&gt;In python its quite easy to transform coordinates using &lt;a href=&#34;http://gdal.org/1.11/ogr/&#34;&gt;OGR&lt;/a&gt; and OSR tools with their python wrapper.&lt;/p&gt;&lt;pre&gt;def transform(pointX, pointY):&lt;br /&gt;    # Spatial Reference System&lt;br /&gt;    inputEPSG = 4326&lt;br /&gt;    outputEPSG = 3857&lt;br /&gt;&lt;br /&gt;    # create a geometry from coordinates&lt;br /&gt;    point = ogr.Geometry(ogr.wkbPoint)&lt;br /&gt;    point.AddPoint(pointX, pointY)&lt;br /&gt;&lt;br /&gt;    # create coordinate transformation&lt;br /&gt;    inSpatialRef = osr.SpatialReference()&lt;br /&gt;    inSpatialRef.ImportFromEPSG(inputEPSG)&lt;br /&gt;&lt;br /&gt;    outSpatialRef = osr.SpatialReference()&lt;br /&gt;    outSpatialRef.ImportFromEPSG(outputEPSG)&lt;br /&gt;&lt;br /&gt;    coordTransform = osr.CoordinateTransformation(inSpatialRef, outSpatialRef)&lt;br /&gt;&lt;br /&gt;    # transform point&lt;br /&gt;    point.Transform(coordTransform)&lt;br /&gt;&lt;br /&gt;    # return point in EPSG 3857&lt;br /&gt;    return point.GetX(), point.GetY()&lt;br /&gt;&lt;/pre&gt;
  &lt;p&gt;
    &lt;br /&gt;
  &lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;Basically you can use&amp;nbsp;coordTransform to transform any geometry (point,polygon,line e.t.c) between any osr supported projections.&lt;/p&gt;
&lt;p&gt;Hope this helps&lt;/p&gt;</content><category label="gis" scheme="http://www.varunpant.com/topics/gis/1" term="gis"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="osgeo" scheme="http://www.varunpant.com/topics/osgeo/1" term="osgeo"></category><category label="gdal" scheme="http://www.varunpant.com/topics/gdal/1" term="gdal"></category></entry><entry><title>How to Query a Shape file for Point inside a polygon using ogr python</title><link href="http://www.varunpant.com/posts/how-to-query-a-shape-file-for-point-inside-a-polygon-using-ogr-python" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-query-a-shape-file-for-point-inside-a-polygon-using-ogr-python</id><published>2016-09-01T00:00:00z</published><updated>2016-09-01T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Recently I was trying to build a quick geo lookup service in python, which could be used like an &#34;info tool&#34; in QGIS. This task is trivial in almost all geospatial databases, however I wasn&#39;t able to find much online around querying a shape file.&lt;/p&gt;
&lt;p&gt;In this post I will demonstrate a simple python code to query a shape file which contains world countries. The file can be downloaded from &lt;a href=&#34;https://github.com/RandomEtc/shapefile-js/tree/master/thematicmapping&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/media/image_367885381841472742976614.png&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Here is the code&lt;/p&gt;
&lt;p&gt;
  You will need python-gdal bindings.
  &lt;code&gt;sudo apt-get install python-gdal&lt;/code&gt;
&lt;/p&gt;&lt;pre&gt;from osgeo import ogr
ogr.UseExceptions()
from pprint import pprint

 

path = &#34;TM_WORLD_BORDERS_SIMPL-0.3.shp&#34;
drv = ogr.GetDriverByName(&#34;ESRI Shapefile&#34;)
ds = drv.Open(path, 0) 

 

result = ds.ExecuteSQL(&#34;select name from &#39;TM_WORLD_BORDERS_SIMPL-0.3&#39; where ST_Intersects(&#39;TM_WORLD_BORDERS_SIMPL-0.3&#39;.geometry,makePoint(-0.2225382,51.5253007) )&#34;,dialect=&#34;SQLITE&#34;)

c = result.GetFeatureCount()
for i in range(c):
    print result.GetFeature(i).GetField(0)
 

ds.ReleaseResultSet(result)

&lt;/pre&gt;
&lt;p&gt;
  Hope this helps.
&lt;/p&gt;</content><category label="gdal" scheme="http://www.varunpant.com/topics/gdal/1" term="gdal"></category><category label="ogr" scheme="http://www.varunpant.com/topics/ogr/1" term="ogr"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="gis" scheme="http://www.varunpant.com/topics/gis/1" term="gis"></category></entry><entry><title>How to read a csv file in go</title><link href="http://www.varunpant.com/posts/how-to-read-a-csv-file-in-go" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-read-a-csv-file-in-go</id><published>2016-08-30T00:00:00z</published><updated>2016-08-30T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;One of the most common task for a programmer is either to read or write a csv file &lt;/p&gt;

&lt;p&gt;
  &lt;h3&gt;Read a csv file&lt;/h3&gt;
  &lt;pre&gt;
package main

import (
    &#34;bufio&#34;
    &#34;encoding/csv&#34;
    &#34;os&#34;
    &#34;fmt&#34;
    &#34;io&#34;
)

func main() {
    // Load a csv file.
    f, _ := os.Open(&#34;/path/to/my/csv/file.csv&#34;)

    // Create a new reader.
    r := csv.NewReader(bufio.NewReader(f))
    //define seperator
    r.Comma = &#39;,&#39;
    for {
        record, err := r.Read()
        // Stop at EOF.
        if err == io.EOF {
            break
        }
        // Display record.
        fmt.Println(record)
        // ... Display record length.
        fmt.Println(len(record))
        // ... Display all individual elements of the slice.
        for value := range record {
            fmt.Printf(&#34;  %v\n&#34;, record[value])
        }
    }
}
&lt;/pre&gt;
&lt;/p&gt;</content><category label="golang" scheme="http://www.varunpant.com/topics/golang/1" term="golang"></category></entry><entry><title>How to integrate Google container engine with Stackdriver with kubernaties</title><link href="http://www.varunpant.com/posts/how-to-integrate-google-container-engine-with-stackdriver-with-kubernaties" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-integrate-google-container-engine-with-stackdriver-with-kubernaties</id><published>2016-08-04T00:00:00z</published><updated>2016-08-04T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Most folks have been using &lt;a href=&#34;http://grafana.org/&#34;&gt;Grafana&lt;/a&gt; or something &lt;a href=&#34;http://kubernetes.io/docs/user-guide/monitoring/&#34;&gt;similar&lt;/a&gt; to monitor &lt;a href=&#34;http://kubernetes.io/&#34;&gt;Kubernaties&lt;/a&gt; cluster.&lt;/p&gt;
&lt;p&gt;If you are using &lt;a href=&#34;https://cloud.google.com/container-engine/&#34;&gt;Google cloud container engine&lt;/a&gt;&amp;nbsp;, then the standard unified place to monitor all your application and services is &lt;a href=&#34;https://cloud.google.com/monitoring/&#34;&gt;Slackdriver&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;According to googles documentation, when you create a new container cluster using GUI or &amp;nbsp;gcloud, &lt;a href=&#34;https://app.google.stackdriver.com/&#34;&gt;Slackdriver&lt;/a&gt; is automatically configured with a sink, however It did not work out of the box for me hence this post :)&lt;/p&gt;
&lt;p&gt;Well, the easiest way to check if &lt;a href=&#34;https://app.google.stackdriver.com/&#34;&gt;Slackdriver&lt;/a&gt; is configured is to issue a command&lt;/p&gt;





&lt;code&gt;gcloud container clusters describe&amp;nbsp;&amp;lt;cluster-name&amp;gt;&lt;/code&gt;

&lt;p&gt;If the response contains something like &lt;code&gt;monitoringService: monitoring.googleapis.com &lt;/code&gt; then yer all good and you can simply go and visit &lt;a href=&#34;https://app.google.stackdriver.com/gke&#34;&gt;https://app.google.stackdriver.com/gke&lt;/a&gt;&amp;nbsp;link which should point you to you cluster.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/media/image_6619659342091470328330123.png&#34; /&gt;
  &lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;other wise issue this command to register sinks with monitoring.googleapis.com&lt;/p&gt;


&lt;p&gt;&lt;code&gt;gcloud alpha container clusters update &amp;lt;clustername&amp;gt; --monitoring-service=monitoring.googleapis.com&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Hope this helps&lt;/p&gt;</content><category label="google container engine" scheme="http://www.varunpant.com/topics/google-container-engine/1" term="google container engine"></category><category label="kubernaties" scheme="http://www.varunpant.com/topics/kubernaties/1" term="kubernaties"></category><category label="cloud" scheme="http://www.varunpant.com/topics/cloud/1" term="cloud"></category><category label="google" scheme="http://www.varunpant.com/topics/google/1" term="google"></category></entry><entry><title>Binary Search Tree in python</title><link href="http://www.varunpant.com/posts/binary-search-tree-in-python" rel="alternate" /><id>http://www.varunpant.com/posts/binary-search-tree-in-python</id><published>2016-08-01T00:00:00z</published><updated>2016-08-01T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;BST data structure supports many dynamic-set operations including&lt;/p&gt;
&lt;ol&gt;
  &lt;li&gt;Search&lt;/li&gt;
  &lt;li&gt;Minimum&lt;/li&gt;
  &lt;li&gt;Maximum&lt;/li&gt;
  &lt;li&gt;Predecessor&lt;/li&gt;
  &lt;li&gt;Successor&lt;/li&gt;
  &lt;li&gt;Insert&lt;/li&gt;
  &lt;li&gt;Delete&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;These basic operations allow us to treat this data structure both as a dictionary and as a priority queue.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Basic operations on a binary tree takes time proportional to the height of the tree, O(lg n) [worst case] and even O(n) if the tree is a linear chain.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;If you want to learn more about practical application of these trees check &lt;a href=&#34;https://stackoverflow.com/questions/2130416/what-are-the-applications-of-binary-trees&#34;&gt;this&lt;/a&gt; post out.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Here I present a very basic version of binary tree written in python&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;class Node:
    def __init__(self,left=None,right=None,parent=None,key=None):
        self.left = left
        self.right = right
        self.parent = parent
        self.key = key
    
class BinaryTree:
    
    def __init__(self): 
        self.root = None

    def inorderWalk(self,node):
        if node is not None:
            self.inorderWalk(node.left)
            print node.key
            self.inorderWalk(node.right)

    def treeSearch(self,node,key):
        if node is None or key == node.key:
            return node
        if key &amp;lt; node.key:
            return self.treeSearch(node.left,key)
        else:
            return self.treeSearch(node.right,key)

    def iterativeTreeSearch(self,node,key):
        while node is not None and key != node.key:
            if key &amp;lt; node.key:
                node = node.left
            else:
                node = node.right

        return node

    def treeMinimum(self,node):
        while node.left is not None:
            node = node.left

        return node

    def treeMaximum(self,node):
        while node.right is not None:
            node = node.right

        return node

    def treeSuccessor(self,node):
        if node.right is not None:
            return self.treeMinimum(node.right)
        y = node.parent
        while y is not None and node == y.right:
            node = y
            y = y.parent
        return y

    def treePredecessor(self,node):
        if node.left is not None:
            return self.treeMaximum(node.left)
        y = node.parent
        while y is not None and node == y.left:
            node = y
            y = y.parent
        return y

    def insert(self,node):
        y = None
        x = self.root
        while x is not None:
            y = x
            if node.key &amp;lt; x.key:
                x = x.left
            else:
                x = x.right
        node.parent = y
        if y == None:
            self.root = node #Tree was empty
        elif node.key &amp;lt; y.key:
            y.left = node
        else:
            y.right = node

    def transplant(self,u,v):
        if u.parent is None:
            self.root = v
        elif u == u.parent.left:
            u.parent.left = v
        else:
            u.parent.right = v
        if v is not None:
            v.parent = u.parent

    def delete(self,node):
        if node.left is None:
            self.transplant(node,node.right)
        elif node.right is None:
            self.transplant(node,node.left)
        else:
            y = self.treeMinimum(node.right)
            if y.parent is not node:
                self.transplant(y,y.right)
                y.right = node.right
                y.right.parent = y
            self.transplant(node,y)
            y.left = node.left
            y.left.parent = y



A = [12,5,2,9,18,15,19,13,17]

T = BinaryTree()

for _key in A:
    N = Node(key = _key)
    T.insert(N)

T.inorderWalk(T.root)

print &#34;Max: &#34; + str(T.treeMaximum(T.root).key)
print &#34;Min: &#34; + str(T.treeMinimum(T.root).key)

sn = T.treeSearch(T.root,17)

print T.treeSuccessor(sn).key
print T.treePredecessor(sn).key

# for k in A:
#     print &#34;-&#34;*10
#     f = T.treeSearch(T.root,k)
#     print &#34;deleting&#34;, f.key
#     T.delete(f) 
#     T.inorderWalk(T.root)

&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="algorithms" scheme="http://www.varunpant.com/topics/algorithms/1" term="algorithms"></category></entry><entry><title>Heap Sort in python</title><link href="http://www.varunpant.com/posts/heap-sort" rel="alternate" /><id>http://www.varunpant.com/posts/heap-sort</id><published>2016-07-25T00:00:00z</published><updated>2016-07-25T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;div&gt;The (binary) heap data structure is an array object that we can view as a nearly complete binary tree.&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;div&gt;Each node of the tree corresponds to an element of the array.&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;div&gt;The tree is completely filled on all levels except possibly the lowest, which is filled from the left up to a point.&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;div&gt;An array A that represents a heap is an object with two attributes:&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
  &lt;ul&gt;
    &lt;li&gt;length, which (as usual) gives the number of elements in the array.&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;
&lt;div&gt;
  &lt;ul&gt;
    &lt;li&gt;heap-size, which represents how many elements in the heap are stored within array A.&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;

&lt;p&gt;Here is the implementation in python.&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;//not used
def parent(i):
    return int(i/2)

def left(i):
    return 2 * i

def right(i):
    return left(i) + 1

def maxHeapify(A,i,sz):
    l = left(i)
    r = right(i)
    largest = None
    if l &amp;lt;= sz and A[l] &amp;gt; A[i]:
        largest = l
    else:
        largest = i

    if r &amp;lt;= sz and A[r] &amp;gt; A[largest]:
        largest = r

    if largest != i:
        temp = A[i]
        A[i] = A[largest]
        A[largest] = temp 
        maxHeapify(A,largest,sz)

def heapsort(A):
    heap_size = len(A)
    middle = int(heap_size/2)
    for i in xrange(middle,0,-1):
        maxHeapify(A,i,heap_size - 1)

    m = heap_size - 1
    for i in xrange(m,-1,-1): 
        temp = A[0]
        A[0] = A[i]
        A[i] = temp 
        m = m-1 
        maxHeapify(A,0,m)




A = [16,4,10,14,8,7,9,3,2,4,1]

print &#34;Unsorted: &#34;, A 
heapsort(A)
print &#34;Heap Sorted: &#34;, A
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="algorithms" scheme="http://www.varunpant.com/topics/algorithms/1" term="algorithms"></category></entry><entry><title>Insertion sort in python</title><link href="http://www.varunpant.com/posts/insertion-sort-in-python" rel="alternate" /><id>http://www.varunpant.com/posts/insertion-sort-in-python</id><published>2016-07-22T00:00:00z</published><updated>2016-07-22T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Insertion sort, is an efficient algorithm for sorting a small number of elements.&lt;/p&gt;
&lt;p&gt; Insertion sort works the way many people sort a hand of playing cards. We start with an empty left hand and the cards face down on the table. We then remove one card at a time from the table and insert it into the correct position in the left hand.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/media/Insertion-Sort.jpg&#34; /&gt;&lt;/p&gt;
&lt;p&gt; To find the correct position for a card, we compare it with each of the cards already in the hand, from right to left.&lt;/p&gt;
&lt;p&gt;Here is the&amp;nbsp;pseudocode for it.&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;/media/insertion sort.png&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Here is the python version of it&lt;/p&gt;
&lt;div&gt;
  &lt;img src=&#34;https://upload.wikimedia.org/wikipedia/commons/9/9c/Insertion-sort-example.gif&#34; /&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;pre&gt;def insertionSort(a):
    for j in range(1, len(a)):  
        key = a[j]
        i = j - 1
        while (i &amp;gt; -1 and a[i] &amp;gt; key): 
            a[i + 1] = a[i]
            i = i - 1
        a[i + 1] = key
       

    return a


a = [6, 5, 3, 1, 8, 7, 2, 4] 
print insertionSort(a)&lt;/pre&gt;
&lt;p&gt;Hope this helps :)&lt;/p&gt;
&lt;p&gt;
  &lt;br /&gt;
&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="algorithms" scheme="http://www.varunpant.com/topics/algorithms/1" term="algorithms"></category></entry><entry><title>How to install  Ubuntu bash on windows</title><link href="http://www.varunpant.com/posts/how-to-install-ubuntu-bash-on-windows" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-install-ubuntu-bash-on-windows</id><published>2016-04-07T00:00:00z</published><updated>2016-04-07T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;&lt;img src=&#34;http://www.varunpant.com/static/resources/uow/uow.jpg&#34; width=&#34;100%&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Microsoft announced at Build 2016 , about the new feature to  run native Bash and GNU/Linux command-line tools&lt;/p&gt;
&lt;p&gt;Gabriel Aul has just &lt;a href=&#34;https://twitter.com/GabeAul/status/717759462258249728&#34;&gt;announced the release&lt;/a&gt; of the Windows 10 build #14316 to the Windows Insiders Fast-Ring&lt;/p&gt;
&lt;p&gt;This build contains the first public release of Bash on Ubuntu on Windows and the underlying Windows Subsystem for Linux.&lt;/p&gt;
&lt;p&gt;
&lt;ol&gt;
   &lt;li&gt;Turn on Developer Mode: Settings | Update &amp;amp; Security | For Developers | Check the Developer Mode radio button:&lt;br&gt;

&lt;img  src=&#34;http://www.varunpant.com/static/resources/uow/screen1.png&#34; width=&#34;100%&#34; &gt;


   &lt;/li&gt;
   &lt;li&gt;From the start menu, open “Turn Windows Features on or off”:&lt;br&gt;
     &lt;img  src=&#34;http://www.varunpant.com/static/resources/uow/screen2.png&#34; width=&#34;100%&#34; &gt;

   &lt;/li&gt;
   &lt;li&gt;Scroll down and check the “Windows Subsystem for Linux (Beta)” feature:&lt;br&gt;
      &lt;img  src=&#34;http://www.varunpant.com/static/resources/uow/screen3.png&#34; width=&#34;100%&#34; &gt;

   &lt;/li&gt;
   &lt;li&gt;Hit okay and reboot (required step)&lt;/li&gt;
   &lt;li&gt;Once rebooted, open a PowerShell/command prompt and run “Bash” and follow the simple prompts to accept Canonical’s license and kick-off the download of the Ubuntu image:&lt;br&gt;
     &lt;img  src=&#34;http://www.varunpant.com/static/resources/uow/screen4.png&#34; width=&#34;100%&#34; &gt;

   &lt;/li&gt;
   &lt;li&gt;
      After download has completed, you’ll be able to start “Bash on Ubuntu on Windows” from the Start menu:&lt;br&gt;
   &lt;img  src=&#34;http://www.varunpant.com/static/resources/uow/screen5.png&#34; width=&#34;100%&#34; &gt;

      &lt;p&gt;&lt;img  src=&#34;http://www.varunpant.com/static/resources/uow/screen6.png&#34; width=&#34;100%&#34; &gt;
&lt;/p&gt;
   &lt;/li&gt;
&lt;/ol&gt;
&lt;/p&gt;</content><category label="unix" scheme="http://www.varunpant.com/topics/unix/1" term="unix"></category><category label="windows" scheme="http://www.varunpant.com/topics/windows/1" term="windows"></category></entry><entry><title>How to use Google Appengine Remote API for Java</title><link href="http://www.varunpant.com/posts/how-to-use-google-appengine-remote-api-for-java" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-use-google-appengine-remote-api-for-java</id><published>2016-03-22T00:00:00z</published><updated>2016-03-22T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;Google App Engine Remote API enables programmers to access Google DataStore remotely from any python script or a Java Program.&lt;/p&gt;
&lt;p&gt;Remote api essentially is a generic web service, which allows datastore to be accessed from outside the app engine&#39;s environment therefore using this mechanism, users can either bulk insert data or modify existing data from their servers.&lt;/p&gt;
&lt;p&gt;With the help of remote api, data from one datastore can be copied to data on another app engine instance as well.&lt;/p&gt;
&lt;h3&gt;Configuring Remote api on server - Java&lt;/h3&gt;
&lt;p&gt;Configuring remote api on an app engine - java web application simply requires addition of a servlet in the web.xml.&lt;/p&gt;
&lt;p&gt;To install the Remote API servlet, add the following to your &lt;b&gt;web.xml&lt;/b&gt;&lt;/p&gt;
&lt;pre&gt;&amp;lt;servlet&amp;gt;
&amp;lt;display-name&amp;gt;Remote API Servlet&amp;lt;/display-name&amp;gt;
&amp;lt;servlet-name&amp;gt;RemoteApiServlet&amp;lt;/servlet-name&amp;gt;
&amp;lt;servlet-class&amp;gt;com.google.apphosting.utils.remoteapi.RemoteApiServlet&amp;lt;/servlet-class&amp;gt;
&amp;lt;load-on-startup&amp;gt;1&amp;lt;/load-on-startup&amp;gt;
&amp;lt;/servlet&amp;gt;
&amp;lt;servlet-mapping&amp;gt;
&amp;lt;servlet-name&amp;gt;RemoteApiServlet&amp;lt;/servlet-name&amp;gt;
&amp;lt;url-pattern&amp;gt;/remote_api&amp;lt;/url-pattern&amp;gt;
&amp;lt;/servlet-mapping&amp;gt;&lt;br /&gt;
&lt;/pre&gt;
&lt;p&gt;Class &lt;code&gt;com.google.apphosting.utils.remoteapi.RemoteApiServlet&lt;/code&gt; is already bundled with the GAE SDK so thats all which needs to be done to get it up and running, also the security is already handled and only the user with admin privilege can access this handler .&lt;/p&gt;
&lt;p&gt;For you client Java Program (which is not you regular app engine project), you would need to include these two dependencies in your pom.xml&lt;/p&gt;
&lt;pre&gt;&amp;lt;dependency&amp;gt;
&amp;lt;groupId&amp;gt;com.google.appengine.tools&amp;lt;/groupId&amp;gt;
&amp;lt;artifactId&amp;gt;appengine-gcs-client&amp;lt;/artifactId&amp;gt;
&amp;lt;version&amp;gt;0.5&amp;lt;/version&amp;gt;
&amp;lt;/dependency&amp;gt;&lt;br /&gt;&amp;lt;dependency&amp;gt;&lt;br /&gt;&amp;lt;groupId&amp;gt;com.google.appengine&amp;lt;/groupId&amp;gt;&lt;br /&gt;&amp;lt;artifactId&amp;gt;appengine-remote-api&amp;lt;/artifactId&amp;gt;&lt;br /&gt;&amp;lt;version&amp;gt;1.9.32&amp;lt;/version&amp;gt;&lt;br /&gt;&amp;lt;/dependency&amp;gt;&lt;br /&gt;&lt;br /&gt;
&lt;/pre&gt;
&lt;p&gt;Then install remote api in your standalone(non appengine) project&lt;/p&gt;
&lt;pre&gt;RemoteApiOptions options_local = new RemoteApiOptions()
.server(&#34;localhost&#34;, 8080)
.useDevelopmentServerCredential();
or&lt;br /&gt;RemoteApiOptions options_remote = new RemoteApiOptions()&lt;br /&gt;.server(&#34;your_app_id.appspot.com&#34;, 443)&lt;br /&gt;.useApplicationDefaultCredential();RemoteApiInstaller installer = new RemoteApiInstaller();
installer.install(options_local);
&lt;/pre&gt;
&lt;p&gt;The Remote API client will rely on Application Default Credentials that use OAuth 2.0.&lt;/p&gt;
&lt;p&gt;Finally create an instance of datastore factory after installing the API&lt;/p&gt;&lt;code&gt;final DatastoreService ds = DatastoreServiceFactory.getDatastoreService();&lt;/code&gt;
&lt;p&gt;For example if one needs to delete all entities in the local or remote datastore via code, then&lt;/p&gt;
&lt;pre&gt;String[] entities = &#34;Entity1,Entity2,Entity&#34;.split(&#34;,&#34;);
for (String _e : entities) {
Query query = new Query(_e);
for (Entity entity : ds.prepare(query).asIterable()) {
ds.delete(entity.getKey());
}
}
&lt;/pre&gt;
&lt;p&gt;Or here is another example where we create some entity on a remote server&lt;/p&gt;
&lt;pre&gt;Entity e = new Entity(&#34;SomeEntity&#34;);
e.setProperty(&#34;prop1&#34;,&#34;blah&#34;);
e.setProperty(&#34;prop2&#34;,&#34;blah blah ?&#34;);
e.setProperty(&#34;prop3&#34;,&#34;blah blah blah ??&#34;);
&lt;/pre&gt;
&lt;p&gt;Basically , as it should&#39;d have been clear by now,after the step involving installation of Remote API, all datastore operations occur in the remote server.&lt;/p&gt;
&lt;p&gt;Finally , while performing operations on remote server via remote api, always prefer to do operations on batch, read more &lt;a href=&#34;https://cloud.google.com/appengine/docs/java/datastore/entities#Java_Batch_operations&#34;&gt;here &lt;/a&gt; about Java DataStore API Batch Operations.&lt;/p&gt;
&lt;p&gt;Hope this helps.&lt;/p&gt;</content><category label="appengine" scheme="http://www.varunpant.com/topics/appengine/1" term="appengine"></category></entry><entry><title>Read GAE Admin Backups fromLevelDB format and export GAE Entities using bulkloader</title><link href="http://www.varunpant.com/posts/read-gae-admin-backups-fromleveldb-format-and-export-gae-entities-using-bulkloader" rel="alternate" /><id>http://www.varunpant.com/posts/read-gae-admin-backups-fromleveldb-format-and-export-gae-entities-using-bulkloader</id><published>2016-01-11T00:00:00z</published><updated>2016-01-11T00:00:00z</updated><author><name>admin</name></author><content type="html">Google datastore is pretty awesome when one needs a quick no-sql data storage. However recently I have experienced a problem in exporting my GAE Datastore as csv and in certain cases as a line delimited Json file.

Its not very hard to do so and perhaps the easiest way to handle such thing is to write an export handler in you web app, however, there are alternative ways which I have highlighted below.
&lt;ol&gt;
	&lt;li&gt;One of the easiest alternative is by using &lt;a href=&#34;https://console.cloud.google.com/project/_/datastore/settings?_ga=1.52544424.12031260.1450181862&#34;&gt; Datastore Admin .&lt;/a&gt;
This tool will easily let you backup you GAE DataStore Entities to google cloud storage in the same project which can later be downloaded locally, by using cloud console or gsutil like this &lt;code&gt;gsutil cp -R /gs/your_bucket_name/your_path /local_target&lt;/code&gt;&lt;/li&gt;
	&lt;li&gt;Then there is &lt;a href=&#34;https://cloud.google.com/appengine/docs/python/tools/remoteapi&#34;&gt;Remote API for python and Java&lt;/a&gt;, which perhaps was created to modify the datastore directly via code from your local machine&lt;/li&gt;
	&lt;li&gt;Finally there is a python utility called &lt;code&gt;bulkloader.py&lt;/code&gt; which is coupled with &lt;b&gt;remote_api&lt;/b&gt;i , this utility does require python sdk to be installed and added to your system path.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Using the Bulk Loader Tool&lt;/h3&gt;
To quickly verify if &lt;strong&gt;bulkloader&lt;/strong&gt; is correctly installed simply type &lt;code&gt;bulkloader.py&lt;/code&gt;
&lt;blockquote&gt;If you have a Python application, you can use the appcfg.py upload_data and appcfg.py download_data commands to do data uploads and downloads. These are equivalent to bulkloader.py, but can also derive the application ID and the remote API URL from your app.yaml file. (Future releases may make more bulkloader features available via appcfg.py; check the App Engine website for the latest.)&lt;/blockquote&gt;
f you have a Java application, you just run the bulkloader.py tool, specifying the application ID and remote API URL as command-line arguments: &lt;code&gt;bulkloader.py --app&lt;em&gt;id=app-id --url=http://app-id.appspot.com/remote&lt;/em&gt;api&lt;/code&gt;

The loader tool keeps track of its progress during an upload or download in a data file and can begin from where it last left incase the process is interrupted, this feature requires sqlite3 installed though which can be verified by typing squlite3 in the shell.

One of the easiest features of the bulk loader to use is the backup and restore feature. The bulk loader can download every entity of a given kind to a data file, and can upload that data file back to the app to restore those entities.
&lt;h4&gt;To Download all entities&lt;/h4&gt;
&lt;code&gt;
bulkloader.py --dump
--app&lt;em&gt;id=app-id
--url=http://app-id.appspot.com/remote&lt;/em&gt;api
--kind=kind
--filename=backup.dat&lt;/code&gt;
&lt;h4&gt;To Upload all entitites&lt;/h4&gt;
&lt;code&gt;
bulkloader.py --restore
--app&lt;em&gt;id=app-id
--url=http://app-id.appspot.com/remote&lt;/em&gt;api
--kind=kind
--filename=backup.dat
&lt;/code&gt;
&lt;blockquote&gt;When using --dump and --restore, entities are not validated using the app’s model classes. They are dumped and restored directly as they appear in the datastore.&lt;/blockquote&gt;
Entity keys are preserved, including system-assigned numeric IDs. Properties with key values will remain valid as long as the entities they are referring to are in the app, or are part of the dump being restored. Restoring an entity with the same key as an existing entity will replace the existing entity.

There are clever ways to read csv and upload data into appengine datastore using bulkloader which I will explain in another post, however for those who have been taking dumps using the admin tool, here is quick python code to read entities from the backup files which are in Googles &lt;a href=&#34;https://github.com/google/leveldb&#34;&gt;level DB format&lt;/a&gt;
&lt;pre&gt;
import sys,datetime
sys.path.append(&#39;/usr/local/google_appengine/&#39;)
sys.path.append(&#39;/usr/local/google_appengine/lib/yaml/lib/&#39;)
if &#39;google&#39; in sys.modules:
    del sys.modules[&#39;google&#39;]

from google.appengine.api.files import records
from google.appengine.datastore import entity_pb
from google.appengine.api import datastore
import unicodecsv as csv
from pprint import pprint

toCSV = []

def getKeyName(r):
    entity_proto = entity_pb.EntityProto(contents=r)
    for element in entity_proto.key().path().element_list():
        if element.has_name():
            return element.name()

def getProto(r):
    entity_proto = entity_pb.EntityProto(contents=r)
    return datastore.Entity.FromPb(entity_proto)

fls = [&#39;output-0&#39;,&#39;output-1&#39;,&#39;output-2&#39;,&#39;output-3&#39;,&#39;output-4&#39;]
for f in fls:
    raw = open(f, &#39;r&#39;)
    reader = records.RecordsReader(raw)

    for record in reader:
            entity = getProto(record)
            entity[u&#34;name&#34;] = getKeyName(record)
            # pprint(entity)

            toCSV.append(entity)
            print &#34;-&#34;*50

            # pprint(entity)

            # for key in entity.keys():
            #     print key + &#34; - &#34; + str(type(entity[key]))

keys = toCSV[0].keys()
with open(&#39;settings.csv&#39;, &#39;wb&#39;) as output_file:
    dict_writer = csv.DictWriter(output_file, keys,encoding=&#39;utf-8&#39;)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)
&lt;/pre&gt;</content><category label="gae" scheme="http://www.varunpant.com/topics/gae/1" term="gae"></category><category label="appengine" scheme="http://www.varunpant.com/topics/appengine/1" term="appengine"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category></entry><entry><title>Serving raster layers on Google Cloud Platform</title><link href="http://www.varunpant.com/posts/serving-raster-layers-on-google-cloud-platform" rel="alternate" /><id>http://www.varunpant.com/posts/serving-raster-layers-on-google-cloud-platform</id><published>2015-09-21T00:00:00z</published><updated>2015-09-21T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;In this blog post, I will write about using &lt;a href=&#34;https://cloud.google.com/storage/&#34;&gt;Google cloud storage&lt;/a&gt; as a Raster Tile Server for static imagery.&lt;/p&gt;  &lt;p&gt;In the GIS domain, various techniques are used to add custom raster overlay on top of a base maps, or to even use custom imagery, as a base map itself.&lt;/p&gt;  &lt;p&gt;This approach is also useful if you have a large quantity of satellite or aerial imagery, that you need to serve at scale onto a Google map or any other GIS tool.&lt;/p&gt;  &lt;p&gt;There are various clients out there for web as well as android or IOS, which provide an ability to add overlays while pointing to an external service for the image source.&lt;/p&gt;  &lt;p&gt;&lt;a href=&#34;https://cloud.google.com/storage/&#34;&gt;Google Cloud Storage&lt;/a&gt; serves as a perfect online, static imagery severing service.&lt;/p&gt;  &lt;p&gt;The general idea is to save map tiles, which are usually 256 x 256&amp;#160; sized images in the cloud and then point the client to the base url .&lt;/p&gt;  &lt;h2&gt;Map tiles&lt;/h2&gt;  &lt;p&gt;Map tiles can have various naming standards and can vary based on map projection. &lt;/p&gt;  &lt;p&gt;This article focuses on map tiles in a &lt;strong&gt;z/x/y.png&lt;/strong&gt; naming standard, where &lt;strong&gt;Z&lt;/strong&gt; is the current zoom level, and &lt;strong&gt;X&lt;/strong&gt; is the &lt;strong&gt;X coordinate&lt;/strong&gt; and &lt;strong&gt;Y&lt;/strong&gt; is the &lt;strong&gt;Y coordinate&lt;/strong&gt;, measured from the top left of the map for each zoom level.&lt;/p&gt;  &lt;p&gt;Google Maps, ESRI, Bing, Open Street Map, and others use this top left “standard.”&amp;#160; However, the OGC standard, called TMS, starts from the bottom left.&lt;/p&gt;  &lt;p&gt;You can see the differences in the two examples below, which show a typical tiles file structure (&lt;strong&gt;Z/X/Y.png&lt;/strong&gt;), where, in the 4th X column of zoom level 4, there are two images for the Y coordinates. &lt;/p&gt;  &lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_2.png&#34;&gt;&lt;img title=&#34;image&#34; style=&#34;width: 50%&#34; alt=&#34;image&#34; src=&#34;http://varunpant.com/static/resources/image_thumb.png&#34; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Note that their names are different based on whether counting began at the &lt;strong&gt;top left&lt;/strong&gt; or &lt;strong&gt;bottom left&lt;/strong&gt;.&lt;/p&gt;  &lt;p&gt;The file structure in which your software exported the tiles will determine the logic you need to use in your application when you want to load a specific tile. &lt;/p&gt;  &lt;p&gt;However, the file structure doesn’t impact the actual upload process.&lt;/p&gt;  &lt;h2&gt;Generating Map Tiles&lt;/h2&gt;  &lt;p&gt;There are various open source tools , which can directly generate map tiles from a vector or raster data source. There is a great example &lt;a href=&#34;http://blog.cartodb.com/tiles-on-gcs/&#34;&gt;here&lt;/a&gt; from CartoDB, which shows how to&amp;#160; generate raster tiles from geotiff or&amp;#160; shape files (Any OGC data Source supported by GDAL tools)&lt;/p&gt;  &lt;p&gt;In this article , I will present an alternative way to do so, by using a python library called &lt;a href=&#34;http://tilestache.org/&#34;&gt;Tilestache&lt;/a&gt; .&lt;/p&gt;  &lt;p&gt;Tilestache is a map tiles server which seamlessly integrates with Google maps tiling scheme. It also provides a&amp;#160; &lt;a href=&#34;https://github.com/TileStache/TileStache/blob/master/scripts/tilestache-seed.py&#34;&gt;seeding script&lt;/a&gt; which can generate tiles on the disk and has plugins to directly add those tiles in the google cloud. &lt;/p&gt;  &lt;p&gt;I prefer &lt;a href=&#34;http://tilestache.org/&#34;&gt;Tilestache&lt;/a&gt; for various reasons, but most importantly because it is based on &lt;a href=&#34;http://mapnik.org/&#34;&gt;Mapnik&lt;/a&gt;, therefore, one can use open source tools like &lt;a href=&#34;https://www.mapbox.com/tilemill/&#34;&gt;Tilemill&lt;/a&gt; by &lt;a href=&#34;https://www.mapbox.com/&#34;&gt;mapbox&lt;/a&gt; to style the maps and later export the &lt;a href=&#34;https://www.mapbox.com/tilemill/docs/manual/exporting/&#34;&gt;mapnik xml&lt;/a&gt; directly, which in-turn, can later be configured in &lt;a href=&#34;http://tilestache.org/&#34;&gt;Tilestache&lt;/a&gt; for generating highly styled images.&lt;/p&gt;  &lt;p&gt;Here is a quick example of styling states of America, the style used in TileMill is below&lt;/p&gt;  &lt;pre&gt;#ne110madmin1statespr {
  line-color:#fff;
  line-width:1;
  polygon-opacity:0.5;
  text-name: &amp;quot;[name]&amp;quot;;
  text-face-name: &amp;quot;Arial Bold&amp;quot;;
}
#ne110madmin1statespr { polygon-fill: #FFFFCC; }
#ne110madmin1statespr[name_len &amp;gt;= 4 ] { polygon-fill: #D9F0A3; }
#ne110madmin1statespr[name_len &amp;gt;= 7] { polygon-fill: #ADDD8E; }
#ne110madmin1statespr[name_len &amp;gt;= 10] { polygon-fill: #78C679; }
#ne110madmin1statespr[name_len &amp;gt;= 13] { polygon-fill: #41AB5D; }
#ne110madmin1statespr[name_len &amp;gt;= 15] { polygon-fill: #238443; }
#ne110madmin1statespr[name_len &amp;gt;= 20] { polygon-fill: #005A32; }&lt;/pre&gt;

&lt;p&gt;Here is how it looks. &lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_4.png&#34;&gt;&lt;img title=&#34;image&#34; style=&#34;width: 100%&#34; alt=&#34;image&#34; src=&#34;http://varunpant.com/static/resources/image_thumb_1.png&#34; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we can easily extract the mapnik xml from the tilemill. &lt;/p&gt;

&lt;p&gt;Next step is to configure a tilestache config file which is essentially a json document which is used by rendering engine to draw tiles. Here is a sample configuration&lt;/p&gt;

&lt;pre&gt;{
  &amp;quot;cache&amp;quot;:
  {
    &amp;quot;name&amp;quot;: &amp;quot;Disk&amp;quot;,
    &amp;quot;path&amp;quot;: &amp;quot;tiles&amp;quot;,
    &amp;quot;dirs&amp;quot;: &amp;quot;portable&amp;quot;,
    &amp;quot;umask&amp;quot;: &amp;quot;0000&amp;quot;
  },
  &amp;quot;layers&amp;quot;:
  {
    &amp;quot;NE&amp;quot;:
    {
        &amp;quot;provider&amp;quot;: {&amp;quot;name&amp;quot;: &amp;quot;mapnik&amp;quot;, &amp;quot;mapfile&amp;quot;: &amp;quot;C:\\Users\\Varun Pant\\Desktop\\NE\\NE.xml&amp;quot;},
        &amp;quot;projection&amp;quot;: &amp;quot;spherical mercator&amp;quot;
    }
  }
}&lt;/pre&gt;

&lt;p&gt;Few things to note in the above configuration is the attribute &lt;strong&gt;cache &lt;/strong&gt;and attribute &lt;strong&gt;layers&lt;/strong&gt;. &lt;a href=&#34;http://tilestache.org/doc/TileStache.Caches.html&#34;&gt;Cache&lt;/a&gt; instructs the library to save the files onto the disk, the &lt;strong&gt;dirs&lt;/strong&gt; attribute instructs the file structure to be of portable type which essentially means to save is &lt;strong&gt;X/Y/Z.png&lt;/strong&gt; format on the disk.&lt;/p&gt;

&lt;p&gt;Now to start the webserver, one can simply type in &lt;code&gt;tilestache-server.py -c ne.cfg &lt;/code&gt;&lt;/p&gt;

&lt;p&gt;I have also added a quick javascript below, which shows ,how to add a custom overlay on google maps and point it to our raster service.&lt;/p&gt;

&lt;pre&gt;function CustomOverlay(tileSize) {
    this.tileSize = tileSize;
}
CustomOverlay.prototype.getTile = function(coord, zoom, ownerDocument) {
    var img = ownerDocument.createElement(&#39;img&#39;);
    img.src = &amp;quot;http://localhost:8080/NE/&amp;quot; + zoom + &amp;quot;/&amp;quot; + coord.x + &amp;quot;/&amp;quot; + coord.y + &amp;quot;.png&amp;quot;;
    img.style.width = this.tileSize.width + &#39;px&#39;;
    img.style.height = this.tileSize.height + &#39;px&#39;;
    return img;
};

var map;

function initialize() {
    map = new google.maps.Map(
        document.getElementById(&amp;quot;map-canvas&amp;quot;), {
            center: new google.maps.LatLng(42.660851192127, -96.5624457296875),
            zoom: 4
        });

    map.overlayMapTypes.insertAt(0, new CustomOverlay(new google.maps.Size(256, 256)));
}

google.maps.event.addDomListener(window, &#39;load&#39;, initialize);&lt;/pre&gt;

&lt;p&gt;If all goes well, then this is how the end result will look like.&lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_6.png&#34;&gt;&lt;img title=&#34;image&#34; style=&#34;width: 100%&#34; alt=&#34;image&#34; src=&#34;http://varunpant.com/static/resources/image_thumb_2.png&#34; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is a &lt;a href=&#34;https://gist.github.com/varunpant/aad7e87ea1c8af8a673a&#34;&gt;gist&lt;/a&gt; with complete html mark-up.&lt;/p&gt;

&lt;p&gt;As stated above, tilestache also allows to just create static images on the disk instead of serving them, which is very usefull if one wants to serve these tiles fronted by a proxy or load it to cloud like Google or amazon data storage.&lt;/p&gt;

&lt;p&gt;The Command to do so is &lt;code&gt;tilestache-seed.py –&lt;strong&gt;c&lt;/strong&gt; &amp;lt;config name&amp;gt;.cfg –&lt;strong&gt;l&lt;/strong&gt; &amp;lt;layername&amp;gt; –&lt;strong&gt;b&lt;/strong&gt;&amp;#160; &amp;lt;bounding box&amp;gt; &lt;strong&gt;-e&lt;/strong&gt; png &amp;lt;list of zoom levels to render&amp;gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;In my case,I will use the bounding box of my shapefile and the command goes like this &lt;code&gt;tilestache-seed.py -c ne.cfg -l NE -b&amp;#160; 18.9161900000001420 -171.7911106028911700 71.3577635769417500 -66.9646599999999810&amp;#160; -e png 1 2 3 4 5 6 7 8 &lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This is how the folders are created in my &lt;strong&gt;cache directory&lt;/strong&gt;, which is configured in the &lt;strong&gt;ne.cfg&lt;/strong&gt; shown above.&lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_8.png&#34;&gt;&lt;img title=&#34;image&#34; style=&#34;width: 100%&#34; alt=&#34;image&#34; src=&#34;http://varunpant.com/static/resources/image_thumb_3.png&#34; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Uploading data to the cloud&lt;/h2&gt;

&lt;p&gt;So now that we have our tiles generated, the next task is to upload them to the cloud.&lt;/p&gt;

&lt;p&gt;1. Sign in to the &lt;a href=&#34;https://console.developers.google.com/&#34;&gt;Google Developers Console&lt;/a&gt; and click Create Project. &lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_10.png&#34;&gt;&lt;img title=&#34;image&#34; style=&#34;width: 100%&#34; alt=&#34;image&#34; src=&#34;http://varunpant.com/static/resources/image_thumb_4.png&#34; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;2.Enable billing. &lt;/p&gt;

&lt;p&gt;3. Create a Google Cloud storage bucket, choose the appropriate location and storage class.&lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_12.png&#34;&gt;&lt;img title=&#34;image&#34; style=&#34;width: 100%&#34; alt=&#34;image&#34; src=&#34;http://varunpant.com/static/resources/image_thumb_5.png&#34; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And that&#39;s it you are all set. Finally click the bucket name and you will have the following options &lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_14.png&#34;&gt;&lt;img title=&#34;image&#34; style=&#34;width: 100%&#34; alt=&#34;image&#34; src=&#34;http://varunpant.com/static/resources/image_thumb_6.png&#34; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The easiest way to upload folders and tiles here is to click upload folder button and point to the folders on the disk. This is by far the easiest method, however in our case we have only generated tiles for first 8 zoom levels, so they are not much in number and using a web UI upload mechanism will work.&lt;/p&gt;

&lt;p&gt;If we choose to generate large number of tiles and cover more than few countries we are possibly looking at millions to tiles specially around the street level (zoom 19 to 22), to cover such a scenario, I will recommend using another option in tilestache ,which directly allows saving the tiles in Google cloud storage. Tilestache, has a &lt;a href=&#34;http://tilestache.org/doc/TileStache.Goodies.Caches.GoogleCloud.html&#34;&gt;plugin&lt;/a&gt; which can be used instead of a disk based cache.&amp;#160; here is how to configure it&lt;/p&gt;

&lt;pre&gt;{
  &amp;quot;cache&amp;quot;:
  {
    &amp;quot;class&amp;quot;: &amp;quot;TileStache.Goodies.Caches.GoogleCloud:Cache&amp;quot;,
    &amp;quot;kwargs&amp;quot;: {
      &amp;quot;bucket&amp;quot;:  &amp;quot;daa-transfers-static&amp;quot;,
      &amp;quot;access&amp;quot;: &amp;quot;accesstoken&amp;quot;,
      &amp;quot;secret&amp;quot;: &amp;quot;clientsecret&amp;quot;&amp;quot;
    }
  },
  &amp;quot;layers&amp;quot;:
  {
    &amp;quot;NE&amp;quot;:
    {
        &amp;quot;provider&amp;quot;: {&amp;quot;name&amp;quot;: &amp;quot;mapnik&amp;quot;, &amp;quot;mapfile&amp;quot;: &amp;quot;C:\\Users\\Varun Pant\\Desktop\\NE\\NE.xml&amp;quot;},
        &amp;quot;projection&amp;quot;: &amp;quot;spherical mercator&amp;quot;
    }
  }
}&lt;/pre&gt;

&lt;p&gt;You will notice that to work with this&amp;#160; plugin,one needs to have &lt;strong&gt;access token&lt;/strong&gt; and&lt;strong&gt; client secret&lt;/strong&gt;. This can be easily generated using the &lt;a href=&#34;https://console.developers.google.com/&#34;&gt;developer console&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;To setup, follow these steps&lt;/p&gt;

&lt;p&gt;GS Security Credentials:&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Select the project for Google cloud storage [Google APIs Console] &lt;/li&gt;

  &lt;li&gt;Select Google Cloud Storage &lt;/li&gt;

  &lt;li&gt;Select Make this my default project for interoperable storage access. &lt;/li&gt;

  &lt;li&gt;Select Interoperable Access. &lt;/li&gt;

  &lt;li&gt;You can find &lt;strong&gt;gs_access_key_id&lt;/strong&gt; ,&lt;strong&gt;gs_secret_access_key&lt;/strong&gt; for your project. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_16.png&#34;&gt;&lt;img title=&#34;image&#34; style=&#34;width: 100%&#34; alt=&#34;image&#34; src=&#34;http://varunpant.com/static/resources/image_thumb_7.png&#34; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Once configured run the tile seed command again and now, the tiles would be directly stored in the bucket, to access them use the following format &lt;a href=&#34;http://storage.googleapis.com/&#34;&gt;http://storage.googleapis.com/&lt;/a&gt;&amp;lt;bucket_name&amp;gt;/&amp;lt;path&amp;gt;/&amp;lt;tile.png&amp;gt;.&lt;/p&gt;

&lt;p&gt;In our case we can access the tiles like this.&lt;/p&gt;

&lt;p&gt;&lt;a title=&#34;http://storage.googleapis.com/states-demo/NE/8/68/103.png&#34; href=&#34;http://storage.googleapis.com/states-demo/NE/8/68/103.png&#34;&gt;http://storage.googleapis.com/states-demo/NE/8/68/103.png&lt;/a&gt; , in the Html code given above, one can easily change the url from img.src = &amp;quot;http://localhost:8080/NE/&amp;quot; + zoom + &amp;quot;/&amp;quot; + coord.x + &amp;quot;/&amp;quot; + coord.y + &amp;quot;.png&amp;quot;;&amp;#160; to img.src = &amp;quot;&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&lt;a href=&#34;http://storage.googleapis.com/states-demo/NE/&#34;&gt;http://storage.googleapis.com/states-demo&lt;/code&gt;/NE/&lt;/a&gt;&amp;quot; + zoom + &amp;quot;/&amp;quot; + coord.x + &amp;quot;/&amp;quot; + coord.y + &amp;quot;.png&amp;quot;; &lt;/pre&gt;

&lt;h2&gt;Security and ACL&lt;/h2&gt;

&lt;p&gt;Google cloud also allows you to configure the permissions by setting up ACL against your bucket. It is possible to make the bucket and all its content public, or authenticate them via domain ,SSO, user groups and many more ways.&amp;#160; &lt;a href=&#34;https://cloud.google.com/storage/docs/cloud-console?hl=en&#34;&gt;Read this article&lt;/a&gt; to know more.&lt;/p&gt;

&lt;h2&gt;GSUtil&lt;/h2&gt;

&lt;p&gt;Finally there is another way to upload your cache by using &lt;a href=&#34;https://cloud.google.com/storage/docs/gsutil?hl=en&#34;&gt;GSUtil&lt;/a&gt;.&lt;/p&gt;

&lt;pre&gt;gsutil cp -a public-read -r C:\tiles\NE gs://states-demo&lt;/pre&gt;

&lt;p&gt;I have hosted a link &lt;a href=&#34;http://www.varunpant.com/static/resources/gcedemo/index.html&#34;&gt;here&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;Hope this helps.&lt;/p&gt;</content><category label="google" scheme="http://www.varunpant.com/topics/google/1" term="google"></category><category label="gis" scheme="http://www.varunpant.com/topics/gis/1" term="gis"></category><category label="google cloud storage" scheme="http://www.varunpant.com/topics/google-cloud-storage/1" term="google cloud storage"></category></entry><entry><title>Install all Go project dependencies in one command</title><link href="http://www.varunpant.com/posts/install-all-go-project-dependencies-in-one-command" rel="alternate" /><id>http://www.varunpant.com/posts/install-all-go-project-dependencies-in-one-command</id><published>2015-08-25T00:00:00z</published><updated>2015-08-25T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;So if you are looking to compile you go project on your server, you would probably need to worry about any third party dependencies.&lt;/p&gt;
&lt;p&gt;Here is quick recursive way to do that&lt;/p&gt;
&lt;p&gt;&lt;code&gt;go get ./...&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Hope this helps&lt;/p&gt;</content><category label="golang" scheme="http://www.varunpant.com/topics/golang/1" term="golang"></category></entry><entry><title>Bubble-sort in python</title><link href="http://www.varunpant.com/posts/bubble-sort-in-python" rel="alternate" /><id>http://www.varunpant.com/posts/bubble-sort-in-python</id><published>2015-07-23T00:00:00z</published><updated>2015-07-23T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Bubble sort is a sorting algo that repeatedly steps through the list to be sorted, compares each pair of adjacent items and&amp;nbsp;&lt;a href=&#34;https://en.wikipedia.org/wiki/Swap_(computer_science)&#34; title=&#34;Swap (computer science)&#34;&gt;swaps&lt;/a&gt;&amp;nbsp;them if they are in the wrong order.&amp;nbsp;&lt;/p&gt;
&lt;p&gt;It&amp;nbsp;is a popular, but inefficient sorting algo, it has worst-case and average complexity both&amp;nbsp;&lt;em&gt;&lt;a href=&#34;https://en.wikipedia.org/wiki/Big_o_notation&#34; title=&#34;Big o notation&#34;&gt;О&lt;/a&gt;&lt;/em&gt;(&lt;em&gt;n&lt;/em&gt;&lt;sup&gt;2&lt;/sup&gt;), where&amp;nbsp;&lt;em&gt;n&lt;/em&gt;&amp;nbsp;is the number of items being sorted.&lt;/p&gt;
&lt;p&gt;Here is an implementation in python&lt;/p&gt;
&lt;p&gt;&lt;img src=&#34;https://upload.wikimedia.org/wikipedia/commons/0/06/Bubble-sort.gif&#34; /&gt;
  &lt;br /&gt;
&lt;/p&gt;
&lt;pre&gt;def bubbleSort(B):
    count = len(B)
    for i in xrange(count): 
        for j in xrange(count-1,i,-1): 
            #print &#34;compairing %i with %i&#34;%(B[j],B[j-1])
            if B[j] &lt; B[j - 1]:
                temp = B[j]
                B[j] = B[j - 1]
                B[j - 1] = temp
                #print &#34;Swapping  %i with %i&#34;%(B[j],B[j-1])
        #print &#34;Transformed Array: &#34; , B
            

B = [6,5,3,1,8,7,2,4]
print &#34;Unsorted: &#34;, B 
bubbleSort(B)
print &#34;Bubble Sorted: &#34;, B 
 

&lt;/pre&gt;
&lt;p&gt;Hope this helps&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="algorithms" scheme="http://www.varunpant.com/topics/algorithms/1" term="algorithms"></category></entry><entry><title>ultimate developer and power users tool list for mac and linux</title><link href="http://www.varunpant.com/posts/ultimate-developer-and-power-users-tool-list-for-mac-and-linux" rel="alternate" /><id>http://www.varunpant.com/posts/ultimate-developer-and-power-users-tool-list-for-mac-and-linux</id><published>2015-02-07T00:00:00z</published><updated>2015-02-07T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;This is a collection of tools and utilities which I have found indispensable as an engineer.&amp;nbsp;Each has a distinct purpose, and I probably touch each at least a few times a week.&amp;nbsp; These tools save me time and I hope that you will find some of them useful as well.&lt;/p&gt;
&lt;h3&gt;Productivity&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&#34;https://amanusk.github.io/s-tui/&#34;&gt;s-tui&lt;/a&gt;&amp;nbsp;s-tui is a terminal UI for monitoring your computer. s-tui allows to monitor CPU temperature, frequency, power and utilization in a graphical way from the terminal.&lt;/li&gt;
  &lt;li&gt;&lt;span aria-hidden=&#34;true&#34; role=&#34;presentation&#34;&gt;&lt;a href=&#34;http://cockpit-project.org/running.html#ubuntu&#34;&gt;Cockpit&lt;/a&gt;&lt;/span&gt;&amp;nbsp;is a server manager that makes it easy to administer your GNU/Linux servers via a web browser.
    &lt;br /&gt;
  &lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Security&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&#34;https://www.tinc-vpn.org/&#34;&gt;https://www.tinc-vpn.org/&lt;/a&gt;&amp;nbsp;&amp;nbsp;Virtual Private Network (VPN) daemon that uses tunnelling and encryption to create a secure private network between hosts on the Internet.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Fun&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&#34;https://github.com/abishekvashok/cmatrix&#34;&gt;https://github.com/abishekvashok/cmatrix&lt;/a&gt;&amp;nbsp;Matrix digital rain with CMatrix on a Linux or Unix terminal .
  &lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;    Automation&lt;/h3&gt;
&lt;ul&gt;
  &lt;li&gt;&lt;a href=&#34;https://members.funnelscripts.com/amazing-headline-scripts/&#34;&gt;FunnelScripts&lt;/a&gt;&amp;nbsp;Facebook Adverts.&lt;/li&gt;
&lt;/ul&gt;</content><category label="tools" scheme="http://www.varunpant.com/topics/tools/1" term="tools"></category></entry><entry><title>Creating Isochrones and Isodistances using Googles Direction Search API</title><link href="http://www.varunpant.com/posts/creating-isochrones-and-isodistances-using-googles-direction-search-api" rel="alternate" /><id>http://www.varunpant.com/posts/creating-isochrones-and-isodistances-using-googles-direction-search-api</id><published>2014-12-29T00:00:00z</published><updated>2014-12-29T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;h3&gt;Introduction&lt;/h3&gt;
&lt;p&gt;
&lt;img style=&#34;width:100%&#34; alt=&#34;Isochrone&#34; src=&#34;https://raw.githubusercontent.com/varunpant/Google_Isochrone/master/ScreenShot.png&#34; /&gt;
&lt;a href=&#34;http://en.wikipedia.org/wiki/Isochrone_map&#34;&gt;Isochrones&lt;/a&gt; are curves of equal travel time from a certain point of origin, another way of saying this would be that an Isochrone is an isoline for travel time, if the weighting factor is changed form time to distance, then the resulting curve us called an Isodistance.
&lt;/p&gt;
&lt;p&gt;
In this post I will present a rough way to create an Isochrone and an Isodistance using &lt;a href=&#34;https://developers.google.com/maps/documentation/directions/&#34;&gt;google&#39;s directions API.&lt;/a&gt;
&lt;/p&gt;

&lt;h3&gt;Algorithm&lt;/h3&gt;
&lt;p&gt;The actual algorithm to calculate Isocrone or Isodistance is perhpas a bit complicated than the simplistic approach being described here, if you are intrested in having a deeper look then I would recommend visiting this &lt;a href=&#34;http://en.wikipedia.org/wiki/Isochrone_map&#34;&gt; link &lt;/a&gt; by OpenStreetMap folks.

Here is a &lt;a href=&#34;https://github.com/varunpant/Google_Isochrone&#34;&gt;link&lt;/a&gt; to my version on github. Open Isochrone.html to take a look at the functionality or visit this hosted &lt;a href=&#34;http://www.varunpant.com/static/resources/google/Isochrone/isochrone.html&#34;&gt;link&lt;/a&gt;.

&lt;/p&gt;

&lt;h3&gt; Details &lt;/h3&gt;
&lt;p&gt;
Since we do not have direct access to road network (to crawl minimum spanning tree), we fist start the process by drawing a circle of x meters for Isodistance or make a fair assumption for Isochrones.

Following code describes the process.
&lt;pre&gt;
function getCirclePoints(center, radius) {

	var circlePoints = [];
	var searchPoints = [];
	with(Math) {
		var rLat = (radius / 6378.135) * (180 / PI);
		var rLng = rLat / cos(center.lat() * (PI / 180));
		for (var a = 0; a &lt; 361; a++) {
			var aRad = a * (PI / 180);
			var x = center.lng() + (rLng * cos(aRad));
			var y = center.lat() + (rLat * sin(aRad));
			var point = new google.maps.LatLng(parseFloat(y), parseFloat(x));
			circlePoints.push(point);
			if (a % pointInterval == 0) {
				searchPoints.push(point)
			}
		}
	}
	searchPolygon = new google.maps.Polygon({
		paths: circlePoints,
		strokeColor: &#39;#000000&#39;,
		strokeOpacity: 1,
		strokeWeight: 1,
		fillColor: &#39;#ffffff&#39;,
		geodesic: true,
		fillOpacity: 0.5,
		clickable: false
	});
	searchPolygon.setMap(map);
	map.fitBounds(searchPolygon.getBounds());
	return searchPoints
}
&lt;/pre&gt;

&lt;/p&gt;
&lt;p&gt;
&lt;code&gt;getCirclePoints&lt;/code&gt; method uses a point interval of 5 and returns around 72 points (360/5), all around the circumference of the circle.

Next, we use the center of the circle as our starting point, and call direction services for each of the point in the circumference.
&lt;pre&gt;
    var from = startpoint.lat() + &#39; &#39; + startpoint.lng();
	var to = searchPoints[0].lat() + &#39; &#39; + searchPoints[0].lng();

	//Removed processed Point.
	searchPoints.shift()

	var request = {
		origin: from,
		destination: to,
		travelMode: google.maps.TravelMode[selectedMode],
		avoidHighways: false
	};

	directionsService.route(request, directionsearch)
&lt;/pre&gt;

&lt;/p&gt;
&lt;h3&gt;Steps&lt;/h3&gt;
&lt;p&gt;
For each of the requested responses, code traverse through the steps in the legs, then depending on the weighing factor we compute the desired distance or time as shown below

&lt;pre&gt;
for (var n = 0; n &lt; steps.length; n++) {

		if(ISOCHRONE)
			unit += steps[n].duration.value;
		else
			unit += steps[n].distance.value;

		if (unit &lt; comparator) {
			temp_Points.push(steps[n].end_location)
		}
		 else {
			break;
		}
	}
&lt;/pre&gt;


The whole process can be observed by directions debug lines.

&lt;img src=&#34;http://varunpant.com/static/resources/isochrone.gif&#34; alt=&#34;Isochrone&#34; style=&#34;width:100%&#34; /&gt;

&lt;/p&gt;





</content><category label="isochrone" scheme="http://www.varunpant.com/topics/isochrone/1" term="isochrone"></category><category label="javascript" scheme="http://www.varunpant.com/topics/javascript/1" term="javascript"></category><category label="google" scheme="http://www.varunpant.com/topics/google/1" term="google"></category></entry><entry><title>Tilestache on google maps</title><link href="http://www.varunpant.com/posts/tilestache-on-google-maps" rel="alternate" /><id>http://www.varunpant.com/posts/tilestache-on-google-maps</id><published>2014-12-26T00:00:00z</published><updated>2014-12-26T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;h3&gt;Introduction&lt;/h3&gt;
&lt;p&gt;
In this post I will demonstrate how to add custom TileStache map tiles on google maps, using google maps JavaScript API V3.
TileStache has emerged as one of the easiest way to render your own map .There are many examples out there on creating basic tiles and then adding them on top of Leaftlet or Openlayers. In this post I will add them as an overlay on Google Maps.
&lt;/p&gt;

&lt;h3&gt;Overlays&lt;/h3&gt;
&lt;p&gt;
In Google’s terminology, adding a map layer basically means adding an overlay.
Here is an example on adding a &lt;a class=&#34;c4&#34; href=&#34;https://developers.google.com/maps/documentation/javascript/examples/groundoverlay-simple&#34;&gt;Ground Overlay.&lt;/a&gt;
Here is another one called &lt;a class=&#34;c4&#34; href=&#34;https://developers.google.com/maps/documentation/javascript/examples/overlay-simple&#34;&gt;Custom overlay.&lt;/a&gt;
Basically there is a concept of map types and is documented &lt;a class=&#34;c4&#34; href=&#34;https://developers.google.com/maps/documentation/javascript/maptypes&#34;&gt;here&lt;/a&gt; in great detail, just skip past the Standard map types and scroll to Custom Map Types.
This example, of a &lt;a class=&#34;c4&#34; href=&#34;https://developers.google.com/maps/documentation/javascript/examples/maptype-base&#34;&gt;Basic Map Type&lt;/a&gt; proved to be most helpful.
In case you are after adding your own Base Map, instead of an Overlay, then take a look at this &lt;a class=&#34;c4&#34; href=&#34;https://developers.google.com/maps/documentation/javascript/examples/maptype-image&#34;&gt;example&lt;/a&gt;.
&lt;/p&gt;

&lt;h3&gt;TileMill and TileStache&lt;/h3&gt;
&lt;p&gt;
Ok, so now lets quickly create a map server side.
In my Map I have a Uk District polygon layer which have been computed to get a count score with UK Crime DataSet November 2014, I simply used Point inside a polygon feature in Qgis to get a score.
Then I styled the data using Carto Css in TileMill to a get a Heat Map Like effect.

&lt;img style=&#34;width:100%&#34; src=&#34;http://www.varunpant.com/static/resources/tilestachedemo/image00.png&#34; alt=&#34;&#34; /&gt;

&lt;/p&gt;

&lt;p&gt;Here is the Carto Css if you are wondering.&lt;/p&gt;

&lt;p&gt;
&lt;pre&gt;
/* Color variables */
@r1:#28ee00;
@r2:#4fee00;
@r3:#77ee00;
@r4:#9fee00;
@r5:#c6ee00;
@r6:#eec600;
@r7:#ee9f00;
@r8:#ee7700;
@r9:#ee4f00;
@r10:#ee2800;
/* Layers */
#sectors {
  [zoom&lt;8]
  {
    line-width:0.2;
    polygon-opacity:0.9;
  }
  [zoom&gt;=8]
  {
  line-width:0.8;
   polygon-opacity:0.7;
  }

  [zoom&gt;=12]
  {
  line-width:1;
   polygon-opacity:0.6;
  }
  [zoom&gt;20]
  {
    line-width:1.2;
    polygon-opacity:0.4;
  }

  line-opacity: 1;
  [PNTCNT=0]{polygon-opacity:0;line-opacity:0;}
  [PNTCNT &gt; 0][PNTCNT &lt;= 24]{polygon-fill:@r1;line-color:#FFF;}
  [PNTCNT &gt; 24][PNTCNT &lt;= 48]{polygon-fill:@r2;line-color:#FFF;}
  [PNTCNT &gt; 48][PNTCNT &lt;= 72]{polygon-fill:@r3;line-color:#FFF;}
  [PNTCNT &gt; 72][PNTCNT &lt;= 96]{polygon-fill:@r4;line-color:#FFF;}
  [PNTCNT &gt; 96][PNTCNT &lt;= 120]{polygon-fill:@r5;line-color:#FFF;}
  [PNTCNT &gt; 120][PNTCNT &lt;= 144]{polygon-fill:@r6;line-color:#FFF;}
  [PNTCNT &gt; 144][PNTCNT &lt;= 168]{polygon-fill:@r7;line-color:#FFF;}
  [PNTCNT &gt; 168][PNTCNT &lt;= 192]{polygon-fill:@r8;line-color:#FFF;}
  [PNTCNT &gt; 192][PNTCNT &lt;= 216]{polygon-fill:@r9;line-color:#FFF;}
  [PNTCNT &gt; 216]{polygon-fill:@r10;line-color:#FFF;}
}

&lt;/pre&gt;
&lt;/p&gt;
&lt;p&gt;
Its very easy to export Mapnik Configuration xml of your TileMill Project.
&lt;img style=&#34;width:100%&#34; src=&#34;http://www.varunpant.com/static/resources/tilestachedemo/image02.png&#34; alt=&#34;&#34; /&gt;

&lt;/p&gt;
&lt;p&gt;
This is my Map configuration for TileStache.
&lt;pre&gt;
{
  &#34;cache&#34;:
  {
    &#34;name&#34;: &#34;Test&#34;,
    &#34;path&#34;: &#34;/tmp/stache&#34;,
    &#34;umask&#34;: &#34;0000&#34;
  },
  &#34;layers&#34;:
  {
     &#34;sectors&#34;:
     {
         &#34;provider&#34;: {&#34;name&#34;: &#34;mapnik&#34;, &#34;mapfile&#34;: &#34;crime.xml&#34;},
         &#34;projection&#34;: &#34;spherical mercator&#34;
     }
  }
}

&lt;/pre&gt;
&lt;/p&gt;
&lt;p&gt;
Finally start the server .
&lt;code&gt;TileStache-master/scripts/tilestache-server.py -c /path/to/my/configuration/tiles.cfg&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;h3&gt;Creating a Custom Overlay for Google Maps&lt;/h3&gt;

Its quite easy to add a TileStache Overlay on top of google maps.
TileStache URLs are already based on a Google Maps-like scheme:
&lt;code&gt;/{layer name}/{zoom}/{column}/{row}.{extension}&lt;/code&gt;
So we create a CoordMapType overlay.
&lt;pre&gt;
 /** @constructor */
  function CoordMapType(tileSize) {
    this.tileSize = tileSize;
  }
  CoordMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
    var img = ownerDocument.createElement(&#39;img&#39;);
    img.src=&#34;http://localhost:8080/sectors/&#34;+ zoom+&#34;/&#34;+coord.x+&#34;/&#34;+ coord.y+&#34;.png&#34;;
    img.style.width = this.tileSize.width + &#39;px&#39;;
    img.style.height = this.tileSize.height + &#39;px&#39;;
    return img;
  };
&lt;/pre&gt;

and then we simply add this overlay to map to overlayMapTypes .

&lt;pre&gt;
map = new google.maps.Map(document.getElementById(&#39;map-canvas&#39;),
      mapOptions);
    map.overlayMapTypes.insertAt(
      0, new CoordMapType(new google.maps.Size(256, 256)));
&lt;/pre&gt;

and thats it, we are done. Here is a screenshot of how the map looks.

&lt;/p&gt;
&lt;p&gt;

&lt;img style=&#34;width:100%&#34; src=&#34;http://www.varunpant.com/static/resources/tilestachedemo/image01.png&#34; alt=&#34;&#34; /&gt;

&lt;/p&gt;

&lt;p&gt;
I have added a working sample &lt;a href=&#34;http://www.varunpant.com/static/resources/tilestachedemo/distribution.zip&#34;&gt;here &lt;/a&gt;, incase you wanna check out the full source code.

Hope this helps.


&lt;/p&gt;



</content><category label="tilestache" scheme="http://www.varunpant.com/topics/tilestache/1" term="tilestache"></category></entry><entry><title>Merge multiple Shapefiles using OGR2OGR in windows Linux or OSX</title><link href="http://www.varunpant.com/posts/merge-multiple-shapefiles-using-ogr2ogr-in-windows-linux-or-osx" rel="alternate" /><id>http://www.varunpant.com/posts/merge-multiple-shapefiles-using-ogr2ogr-in-windows-linux-or-osx</id><published>2014-12-22T00:00:00z</published><updated>2014-12-22T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;h3 id=&#34;introduction&#34;&gt;Introduction&lt;/h3&gt;
&lt;p&gt;This post is aimed at providing assistance to folks who are trying to merge many shapefiles into one single file in either windows or linux environment.
Stuff like this may seem obvious to power users of GDAL/OGR, but not to those that are just new to using these great free tools.&lt;/p&gt;
&lt;h3 id=&#34;merging-shape-shp-files-on-windows&#34;&gt;Merging Shape (*.shp) Files on Windows&lt;/h3&gt;
&lt;p&gt;Essentially, these  commands will grab every shapefile in a directory, and merge them into a single file called “merged.shp”.&lt;/p&gt;
&lt;pre&gt;for %f in (*.shp) do (
if not exist merged.shp (
ogr2ogr -f “esri shapefile” merged.shp %f) else (
ogr2ogr -f “esri shapefile” -update -append merged.shp %f -nln Merged )
)
&lt;/pre&gt;&lt;h3 id=&#34;merging-shape-shp-files-on-osx-or-linux&#34;&gt;Merging Shape (*.shp) Files on OSX or Linux&lt;/h3&gt;
&lt;p&gt;In Linux like environment it&amp;#39;s even easier than one would imagine. Infact I am quite sure it should be a one liner for windows enviroment as well, will have to try one day :)&lt;/p&gt;
&lt;pre&gt;for f in *.shp; do ogr2ogr -update -append merged.shp $f -f &amp;quot;ESRI Shapefile&amp;quot;; done;
&lt;/pre&gt;&lt;h3 id=&#34;merging-shape-shp-files-using-qgis&#34;&gt;Merging Shape (*.shp) Files using QGIS&lt;/h3&gt;
&lt;p&gt;Quite frankley I found this method to be the most slow of all, however this has  GUI and should be fine for moderate size files.&lt;/p&gt;
&lt;p&gt;Open Qgis and click &lt;b&gt;Vector&lt;/b&gt; on menu bar, then click on &lt;b&gt;Data Management Tools&lt;/b&gt; and finally on &lt;b&gt;Merge shapefiles to one&lt;/b&gt;&lt;/p&gt;
&lt;p&gt;&lt;img style=&#34;width:100%&#34; src=&#34;http://www.varunpant.com/static/resources/QgisMerge.png&#34; alt=&#34;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;This will open a dialog, which will ask for the input source folder and the destination file name , and thats it, click &lt;b&gt;OK&lt;/b&gt;to begin the process.&lt;/p&gt;
&lt;p&gt;&lt;img style=&#34;width:100%&#34; src=&#34;http://www.varunpant.com/static/resources/qgismergeD.png&#34; alt=&#34;&#34; /&gt;&lt;/p&gt;
&lt;h3&gt;Creating Index using shapeindex &lt;/h3&gt;
&lt;p&gt;
After merging shapefiles , its most likely that one would like to create a spatial index.
Here is how to do it.
Migrate to the folder and execute &lt;code&gt;shapeindex myShapeFileName.shp&lt;/code&gt;
&lt;/p&gt;
&lt;h3&gt;Copying Ordinance Survey Vector Map shape files into singular folders&lt;/h3&gt;
&lt;p&gt;Incase you are looking at a help full script to copy all similar named shape files from grid folders into dedicated layer named folders using python then I have a goodie for you
&lt;pre&gt;
import fnmatch
import os
import shutil
import glob
from collections import defaultdict

groups = defaultdict(list)

basedir =&#39;/Users/varunpant/Desktop/O vectormap&#39;
mergeddir = os.path.join(basedir, &#39;merged&#39;)

def copyFiles(src,desti):

    files = glob.glob(src.replace(&#39;shp&#39;,&#39;*&#39;))
    for f in files:
        shutil.copy(f, desti)


for root, dirnames, filenames in os.walk(basedir):
  for filename in fnmatch.filter(filenames, &#39;*.shp&#39;):
      basename, extension = os.path.splitext(filename)
      name = basename.split(&#39;_&#39;)[1]
      groups[name].append(os.path.join(root, filename))

for group in groups:
    g = groups[group]

    directory = os.path.join(mergeddir, group)
    if not os.path.exists(directory):
       os.makedirs(directory)

    for n in g:
        copyFiles(n,directory)
        #print n

&lt;/pre&gt;
&lt;/p&gt;
</content><category label="gdal" scheme="http://www.varunpant.com/topics/gdal/1" term="gdal"></category><category label="qgis" scheme="http://www.varunpant.com/topics/qgis/1" term="qgis"></category></entry><entry><title>HTML Geolocation and Altitude</title><link href="http://www.varunpant.com/posts/html-geolocation-and-altitude" rel="alternate" /><id>http://www.varunpant.com/posts/html-geolocation-and-altitude</id><published>2014-12-21T00:00:00z</published><updated>2014-12-21T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;HTML5 Geolocation is a feature which allows the browser on a computer or a mobile phone, to acquire the position from the wifi,2g/3g/4g network or GPS.&lt;/p&gt;

&lt;p&gt;The HTML Geolocation API is used to get the geographical position of a user.

Since this can compromise user privacy, the position is not available unless the user approves it.

The simplest way to use it through &lt;code&gt;navigator.geolocation&lt;/code&gt; object

&lt;pre&gt;
if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);

function showPosition(position) {
    alert(position.coords.latitude +  &#34; , &#34;  + position.coords.longitude);
}
&lt;/pre&gt;

&lt;/p&gt;
&lt;p&gt;
The latitude and longitude are available to JavaScript on the page, which in turn can send it back to the remote web server and do fancy location-aware things like finding local businesses or showing your location on a map, geofencing and a lot more.
&lt;/p&gt;&lt;p&gt;
The &lt;code&gt;position&lt;/code&gt; object contains few more intresting parameters, but are generally available only when in use in smart phones as those devices are equipped with supporting hardware.

Here is a  table with detailed information.

&lt;table class=&#34;st&#34;&gt;
&lt;caption&gt;Position Object&lt;/caption&gt;
&lt;tbody&gt;&lt;tr class=&#34;ho&#34;&gt;&lt;th&gt;Property&lt;/th&gt;&lt;th&gt;Type&lt;/th&gt;&lt;th&gt;Notes
&lt;/th&gt;&lt;/tr&gt;&lt;tr class=&#34;zebra&#34;&gt;&lt;th&gt;&lt;code&gt;coords.latitude&lt;/code&gt;&lt;/th&gt;&lt;td&gt;double&lt;/td&gt;&lt;td&gt;decimal degrees
&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;th&gt;&lt;code&gt;coords.longitude&lt;/code&gt;&lt;/th&gt;&lt;td&gt;double&lt;/td&gt;&lt;td&gt;decimal degrees
&lt;/td&gt;&lt;/tr&gt;&lt;tr class=&#34;zebra&#34;&gt;&lt;th&gt;&lt;code&gt;coords.altitude&lt;/code&gt;&lt;/th&gt;&lt;td&gt;double or &lt;code&gt;null&lt;/code&gt;&lt;/td&gt;&lt;td&gt;meters above the &lt;a href=&#34;http://en.wikipedia.org/wiki/Reference_ellipsoid&#34;&gt;reference ellipsoid&lt;/a&gt;
&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;th&gt;&lt;code&gt;coords.accuracy&lt;/code&gt;&lt;/th&gt;&lt;td&gt;double&lt;/td&gt;&lt;td&gt;meters
&lt;/td&gt;&lt;/tr&gt;&lt;tr class=&#34;zebra&#34;&gt;&lt;th&gt;&lt;code&gt;coords.altitudeAccuracy&lt;/code&gt;&lt;/th&gt;&lt;td&gt;double or &lt;code&gt;null&lt;/code&gt;&lt;/td&gt;&lt;td&gt;meters
&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;th&gt;&lt;code&gt;coords.heading&lt;/code&gt;&lt;/th&gt;&lt;td&gt;double or &lt;code&gt;null&lt;/code&gt;&lt;/td&gt;&lt;td&gt;degrees clockwise from &lt;a href=&#34;http://en.wikipedia.org/wiki/True_north&#34;&gt;true north&lt;/a&gt;
&lt;/td&gt;&lt;/tr&gt;&lt;tr class=&#34;zebra&#34;&gt;&lt;th&gt;&lt;code&gt;coords.speed&lt;/code&gt;&lt;/th&gt;&lt;td&gt;double or &lt;code&gt;null&lt;/code&gt;&lt;/td&gt;&lt;td&gt;meters/second
&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;th&gt;&lt;code&gt;timestamp&lt;/code&gt;&lt;/th&gt;&lt;td&gt;DOMTimeStamp&lt;/td&gt;&lt;td&gt;like a &lt;code&gt;Date()&lt;/code&gt; object
&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;
&lt;/p&gt;

&lt;h3&gt;Handling Errors and Rejections&lt;/h3&gt;

&lt;p&gt;

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to get the user&#39;s location.

&lt;pre&gt;
function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            x.innerHTML = &#34;User denied the request for Geolocation.&#34;
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML = &#34;Location information is unavailable.&#34;
            break;
        case error.TIMEOUT:
            x.innerHTML = &#34;The request to get user location timed out.&#34;
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML = &#34;An unknown error occurred.&#34;
            break;
    }
}
&lt;/pre&gt;

&lt;/p&gt;
&lt;p&gt;
Some popular mobile devices — like the iPhone and Android phones — support two methods of figuring out where you are. The first method triangulates your position based on your relative proximity to different cellular towers operated by your phone carrier. This method is fast and doesn’t require any dedicated GPS hardware, but it only gives you a rough idea of where you are. Depending on how many cell towers are in your area, “a rough idea” could be as little as one city block or as much as a kilometer in every direction.&lt;p&gt;&lt;p&gt;
The second method actually uses dedicated GPS hardware on your device to talk to dedicated GPS positioning satellites that are orbiting the Earth. GPS can usually pinpoint your location within a few meters. The downside is that the dedicated GPS chip on your device draws a lot of power, so phones and other general purpose mobile devices usually turn off the chip until it’s needed. That means there will be a startup delay while the chip is initializing its connection with the GPS satellites in the sky. If you’ve ever used Google Maps on an iPhone or other smartphone, you’ve seen both methods in action. First you see a large circle that approximates your position (finding the nearest cell tower), then a smaller circle (triangulating with other cell towers), then a single dot with an exaction position (given by GPS satellites).
&lt;/p&gt;

&lt;p&gt;
The getCurrentPosition() function has an optional third argument, a PositionOptions object. There are three properties you can set in a PositionOptions object. All the properties are optional. You can set any or all or none of them.

&lt;pre&gt;

	navigator.geolocation.getCurrentPosition(showPosition,{enableHighAccuracy:true, maximumAge:30000, timeout:27000});

&lt;/pre&gt;

&lt;/p&gt;

&lt;p&gt;
Generally one would constantly need to acquire the current position of the device, for such a usecase there is another built in method called &lt;code&gt;watchPosition&lt;/code&gt;
The sinature will remind you of &lt;code&gt;setTimeout&lt;/code&gt; and &lt;code&gt;clearTimeout&lt;/code&gt; built in methods.

&lt;pre&gt;
		//This will start calling showPosition in a timedout manner where variable wpid acts as a reference.
		var wpid=navigator.geolocation.watchPosition(showPosition, geo_error, {enableHighAccuracy:true, maximumAge:30000, timeout:27000});

		//If you wanna stop the loop.
		//navigator.geolocation.clearWatch(wpid);
	    // wpid=false;
&lt;/pre&gt;

Finally there is a full working example &lt;a href=&#34;http://www.varunpant.com/static/resources/google/geolocation.html&#34;&gt;here&lt;/a&gt;.

&lt;/p&gt;
</content><category label="html5" scheme="http://www.varunpant.com/topics/html5/1" term="html5"></category><category label="maps" scheme="http://www.varunpant.com/topics/maps/1" term="maps"></category><category label="javascript" scheme="http://www.varunpant.com/topics/javascript/1" term="javascript"></category></entry><entry><title>Classes and Inheritance in EcmaScript 6 (ES6 Harmony)</title><link href="http://www.varunpant.com/posts/classes-and-inheritance-in-ecmascript-6-es6-harmony" rel="alternate" /><id>http://www.varunpant.com/posts/classes-and-inheritance-in-ecmascript-6-es6-harmony</id><published>2014-11-30T00:00:00z</published><updated>2014-11-30T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;
So if you are a JavaScript geek and haven&#39;t yet heard,(if every one is listening to ECMA announcements, who&#39;s gonna drink beer :) ) ECMA 6 feature set has been drafted,its &lt;a href=&#34;http://wiki.ecmascript.org/doku.php?id=harmony:specification_drafts&#34;&gt;feature set &lt;/a&gt; is frozen, it is mostly being refined now. You can already program in it and compile it to current JavaScript . The JavaScript frameworks &lt;a href=&#34;&#34;&gt;AngularJS&lt;/a&gt; and &lt;a href=&#34;&#34;&gt;Ember.js&lt;/a&gt; will be based on it (with ways to opt out). Again, via cross-compilation.&lt;/p&gt;

&lt;p&gt; As you may already know JavaScript is being used both client side i.e. in the browser and also on server side eg:Node.js.
To check which features are currently supported in your browser visit &lt;a href=&#34;http://kangax.github.io/compat-table/es6/&#34;&gt;here &lt;/a&gt;
&lt;/p&gt;

&lt;p&gt;
For me , the most exciting feature has been Classes. We all know that JavaScript needs this soo badly, even though JavaScript, has always been referred to as an OOP language, and arguments have been made by many  that as long as you can implement a class like encapsulation and inheritance like functionality, the language must be regarded as an OOP language(I know, there is much more to this as well), now I being, a humble developer, in most cases just agreed to all that mumbo-jumbo, but there has always been a secret fire burning all along. The desire to actually have a &lt;b&gt;Class&lt;/b&gt; keyword and &lt;b&gt;extend&lt;/b&gt; keyword, so that my brain finds symmetry in the world&lt;/p&gt;

&lt;p&gt; Well somebody must have been listening up there, I mean in the ECMA world, and eventually these babies are here, hence this amazing posts to share the joy :).
&lt;/p&gt;

&lt;p&gt;So before these keywords were present, a class like construct was generally created like the snippet below
&lt;h3&gt;Class&lt;/h3&gt;
&lt;pre&gt;
function Employee( name,age, salary ) { //approximate a class/constructor
   this.name = name;
   this.age= age;
   this.salary = salary;

   this.printEmployeeDetails = function(){ //expose a function
          console.log(this.name + &#39; is &#39; + this.age + &#39; years old, and earns &#39; + this.salary);
    }
}

// Instantiate a new Employee
var smith = new Employee( &#34;Smith&#34;,35,100000);
smith.printEmployeeDetails(); //Smith is 35 years old, and earns 100000
&lt;/pre&gt;

In ECMA6 this can be done as follows
&lt;pre&gt;
class Employee {
    constructor(name,age, salary ) { //constructors!
      this.name = name;
      this.age= age;
      this.salary = salary;
    }

    printEmployeeDetails(){
          console.log(this.name + &#39; is &#39; + this.age + &#39; years old, and earns &#39; + this.salary);
    }
}
&lt;/pre&gt;
&lt;h3&gt;Inheritance&lt;/h3&gt;
&lt;p&gt;
In current JavaScript, Inheritance is  prototypical, which to laymen is a keyword and also lets you override the constructer.
Inheritance can be defined like this &lt;code&gt;ChildClassName.prototype = new ParentClass();&lt;/code&gt;

To Illustrate, consider this example
&lt;pre&gt;

function Janitor(name) {
 this.name = name;

//These values are not passed in by constructor and are local to class Janitor
 this.age = 66;
 this.salary = 5000;
 }
Janitor.prototype = new Employee();// Here&#39;s where the inheritance occurs
Janitor.prototype.constructor=Janitor;// Override the Employee (super) constructor, real confusing, I know

//Define new Janitor Instance
var bob = new Janitor(&#39;Bob&#39;);

//note: bob has printEmployeeDetails method inherited from Employee class
bob.printEmployeeDetails() // Bob is 66 years old, and earns 5000

&lt;/pre&gt;
&lt;/p&gt;

&lt;p&gt;
In ECMA6 this can be done as follows
&lt;pre&gt;
class Janitor extends Employee { //inheritance
    constructor(name) {
        super(name); //call the parent constructor with super
        this.age = 66;
        this.salary = 5000;
    }
}

let bob = new Janitor(&#39;Bob&#39;);
bob.printEmployeeDetails() // Bob is 66 years old, and earns 5000

&lt;/pre&gt;

&lt;p&gt;Unfortunately Chrome, which is my browser of choice does not support classes, so you can&#39;t run this code in console, but I am sure, I will strike out this line soon :)
&lt;/p&gt;

&lt;p&gt;B.T.W check these projects out too &lt;a href=&#34;http://www.typescriptlang.org/&#34;&gt;Microsoft’s TypeScript&lt;/a&gt;,&lt;a href=&#34;http://flowtype.org/&#34;&gt; Facebook’s Flow&lt;/a&gt; and  &lt;a href=&#34;https://docs.google.com/document/d/11YUzC-1d0V1-Q3V0fQ7KSit97HnZoKVygDxpWzEYW0U/edit?pli=1&#34;&gt;Google’s AtScript.&lt;/a&gt;&lt;/p&gt;

&lt;/p&gt;

</content><category label="javascript" scheme="http://www.varunpant.com/topics/javascript/1" term="javascript"></category></entry><entry><title>longest palindrome in a string</title><link href="http://www.varunpant.com/posts/longest-palindrome-in-a-string" rel="alternate" /><id>http://www.varunpant.com/posts/longest-palindrome-in-a-string</id><published>2014-10-15T00:00:00z</published><updated>2014-10-15T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;  def isPailenDrome(s):
        if len(s)==1:
                return False
        L = len(s)
        for i in range(L):
            if s[i] != s[L-1-i]:
                return False
        return True
                

def longestPalindrome(s):
        L = len(s)
        if len(s)&amp;lt;=1:
                return s
        if  isPailenDrome(s):
                return s
        p = {}
        for u in range(L):
                for v in range(u+1,L+1):  
                        k = s[u:v]
                        # print k,isPailenDrome(k)
                        if isPailenDrome(k):
                                p[len(k)] = k
        
        if len(p) &amp;gt; 0:
                return p[sorted(p,reverse = True)[0]]
        return s[0]
  &lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="algorithms" scheme="http://www.varunpant.com/topics/algorithms/1" term="algorithms"></category></entry><entry><title>print two-dimensional array in spiral order</title><link href="http://www.varunpant.com/posts/print-two-dimensional-array-in-spiral-order" rel="alternate" /><id>http://www.varunpant.com/posts/print-two-dimensional-array-in-spiral-order</id><published>2014-10-15T00:00:00z</published><updated>2014-10-15T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;So I saw this problem in a book today about printing a 2d matrix in spiral order&lt;/p&gt;
&lt;p&gt;Here are two solutions to it&lt;/p&gt;
&lt;h3&gt;Solution one.&lt;/h3&gt;
&lt;div&gt;def printSpiralTL(m,x1,y1,x2,y2):&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; for i in range(x1,x2):&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; print m[y1][i]&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; for j in range(y1+1,y2+1):&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; print m[j][x2-1]&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; if x2-x1 &amp;gt; 0:&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; printSpiralBL(m, x1, y1 + 1, x2-1, y2)&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;
&lt;div&gt;
  &lt;br /&gt;
&lt;/div&gt;
&lt;div&gt;def printSpiralBL(m,x1,y1,x2,y2):&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; for i in range(x2-1,x1-1,-1):&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; print m[y2][i]&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; for j in range(y2-1,y1-1,-1):&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; print m[j][x1]&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; if x2-x1 &amp;gt; 0:&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; printSpiralTL(m, x1+1, y1, x2, y2-1)&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;
&lt;div&gt;m = [&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; [1, 2, 3, 4],&amp;nbsp;&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; [5, 6, 7, 8],&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; [9, 0, 1, 2],&amp;nbsp; &amp;nbsp;&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; [3, 4, 5, 6],&amp;nbsp;&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; [7, 8, 9, 1]&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;/div&gt;
&lt;div&gt;&amp;nbsp; &amp;nbsp; ]&lt;/div&gt;
&lt;p&gt;
  &lt;code&gt;printSpiralTL(m,0,0,4,4) &lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;Output:&lt;/p&gt;
&lt;pre&gt;1
2
3
4
8
2
6
1
9
8
7
3
9
5
6
7
1
5
4
0
&lt;/pre&gt;
&lt;p&gt;Here is another way&lt;/p&gt;
&lt;h3&gt;Solution two (print - pop -Transpose).&lt;/h3&gt;
&lt;pre&gt;m = [
    
    [1, 2, 3, 4], 
    [5, 6, 7, 8],
    [9, 0, 1, 2],   
    [3, 4, 5, 6], 
    [7, 8, 9, 1]
        
    ]

def spiral(arr):
    while arr:
        for a in arr[0]:
            print a
        arr = list(reversed(zip(*arr[1:])))

spiral(m)
&lt;/pre&gt;
&lt;p&gt;Hope this helps.&lt;/p&gt;</content><category label="algorithm" scheme="http://www.varunpant.com/topics/algorithm/1" term="algorithm"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category></entry><entry><title>merge two sorted arrays in python</title><link href="http://www.varunpant.com/posts/merge-two-sorted-arrays-in-python" rel="alternate" /><id>http://www.varunpant.com/posts/merge-two-sorted-arrays-in-python</id><published>2014-10-11T00:00:00z</published><updated>2014-10-11T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Here is a quick code snippet to merge two sorted arrays in python&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt;def merge(a,b):
        merged = []
        l = 0
        r = 0
        for i in range(len(a)+len(b) ):
                lval = None
                rval = None

                if l &amp;lt; len(a):
                        lval = a[l]
                if r &amp;lt; len(b):
                        rval = b[r]
                
                if (lval &amp;lt; rval and rval and lval)  or rval == None:
                        merged.append(lval)
                        l+=1
                elif (lval &amp;gt;= rval and rval and lval)or lval == None:
                        merged.append(rval)
                        r+=1

        return merged

&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;print merge([3,5],[2,4])&lt;/code&gt;&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="algorithm" scheme="http://www.varunpant.com/topics/algorithm/1" term="algorithm"></category></entry><entry><title>Update the locate DB on OS X</title><link href="http://www.varunpant.com/posts/update-the-locate-db-on-os-x" rel="alternate" /><id>http://www.varunpant.com/posts/update-the-locate-db-on-os-x</id><published>2014-09-10T00:00:00z</published><updated>2014-09-10T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Apparently out OS X does not have an&amp;nbsp;&lt;code&gt;updatedb&lt;/code&gt;&amp;nbsp;command like linux has, so I was stumped on how to update the locate database.&lt;/p&gt;
&lt;p&gt;I have quickly added this command here, incase I need to use it again.&lt;/p&gt;
&lt;p&gt;
  &lt;code&gt;sudo /usr/libexec/locate.updatedb&lt;/code&gt;
&lt;/p&gt;</content></entry><entry><title>How to print the Fibonacci Sequence in Python</title><link href="http://www.varunpant.com/posts/how-to-print-the-fibonacci-sequence-in-python" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-print-the-fibonacci-sequence-in-python</id><published>2014-08-09T00:00:00z</published><updated>2014-08-09T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;The Fibonacci numbers are the sequence of numbers&amp;nbsp;&lt;img src=&#34;http://mathworld.wolfram.com/images/equations/FibonacciNumber/Inline1.gif&#34; width=&#34;44&#34; height=&#34;16&#34; border=&#34;0&#34; alt=&#34;{F_n}_(n=1)^infty&#34; style=&#34;border-width: 0px; border-image-width: initial;&#34; /&gt;&amp;nbsp;defined by the&amp;nbsp;&lt;a href=&#34;http://mathworld.wolfram.com/LinearRecurrenceEquation.html&#34;&gt;linear recurrence equation&lt;/a&gt;&lt;/p&gt;
&lt;div&gt;
  &lt;table summary=&#34;&#34; width=&#34;100%&#34; align=&#34;center&#34; cellspacing=&#34;0&#34; cellpadding=&#34;0&#34;&gt;
    &lt;tbody&gt;
      &lt;tr&gt;
        &lt;td align=&#34;left&#34;&gt;&lt;img src=&#34;http://mathworld.wolfram.com/images/equations/FibonacciNumber/NumberedEquation1.gif&#34; width=&#34;99&#34; height=&#34;14&#34; border=&#34;0&#34; alt=&#34; F_n=F_(n-1)+F_(n-2) &#34; style=&#34;border-width: 0px; border-image-width: initial;&#34; /&gt;&lt;/td&gt;

      &lt;/tr&gt;
    &lt;/tbody&gt;
  &lt;/table&gt;
&lt;/div&gt;
&lt;p&gt;with&amp;nbsp;&lt;img src=&#34;http://mathworld.wolfram.com/images/equations/FibonacciNumber/Inline2.gif&#34; width=&#34;71&#34; height=&#34;14&#34; border=&#34;0&#34; alt=&#34;F_1=F_2=1&#34; style=&#34;border-width: 0px; border-image-width: initial;&#34; /&gt;&amp;nbsp;and&amp;nbsp;&lt;img src=&#34;http://mathworld.wolfram.com/images/equations/FibonacciNumber/Inline3.gif&#34; width=&#34;39&#34; height=&#34;14&#34; border=&#34;0&#34; alt=&#34;F_0=0&#34; style=&#34;border-width: 0px; border-image-width: initial;&#34; /&gt;&lt;/p&gt;
&lt;p&gt;So in simple terms a method to compute fibonacci number for nth place looks like this&lt;/p&gt;
&lt;p&gt;
&lt;/p&gt;&lt;pre&gt; def fibonacci(n):  
     if n == 0 or n ==1:
         return n
     else:
        return fibonacci(n-1)+fibonacci(n-2) 
&lt;/pre&gt;
&lt;p&gt;&lt;/p&gt;
&lt;p&gt; here is quick test
&lt;/p&gt;&lt;pre&gt;for i in range(10):
    print i,&#34; : &#34;,fibonacci(i)


#This will print
0  :  0
1  :  1
2  :  1
3  :  2
4  :  3
5  :  5
6  :  8
7  :  13
8  :  21
9  :  34
&lt;/pre&gt;
&lt;p&gt;or an inline method like this &lt;code&gt;   print [fibonacci(i) for i in range(11)]&lt;/code&gt; will result&lt;/p&gt;
&lt;pre&gt;[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]&lt;/pre&gt;Running time of fibonacci series is quite interesting. The first version using recursion has a very bad polynomial time (one can try seeing the performance degrade by passing in larger numbers like 30) so
&lt;pre&gt;def fab(n):  
    if n == 0 or n ==1:
        return n
    else:
        return fab(n-1)+fab(n-2)

#This would take polynomial time, (3.4)seconds on my macbook.
fab(35)

&lt;/pre&gt;
&lt;p&gt;There is a better way of doing this in linear time&lt;/p&gt;
&lt;pre&gt;def fab2(n):
    if n == 0:
     return 0
    f = [0 for j in range(n+1)]
    f[0] = 0
    f[1] = 1
    for i in range(2,n+1):
        f[i] = f[i-1]+f[i-2]
    return f

#this will print the sequence in linear time less than 0.1 seconds
fab2(35)
&lt;/pre&gt;


&lt;p&gt;Few days ago I found another interesting way to code this using &lt;code&gt;enumerate&lt;/code&gt; and &lt;code&gt;yield&lt;/code&gt; in python&lt;/p&gt;
&lt;pre&gt;def fib():
    a, b = 0, 1
    while True:            # First iteration:
        yield a            # yield 0 to start with and then
        a, b = b, a + b    # a will now be 1, and b will also be 1, (0 + 1)
&lt;/pre&gt;
&lt;p&gt;and usage&lt;/p&gt;

&lt;pre&gt;for index, fibonacci_number in enumerate(fib()):
     print(&#39;{i:3}: {f:3}&#39;.format(i=index, f=fibonacci_number))
     if index == 10:
         break

&lt;/pre&gt;
&lt;p&gt;prints&lt;/p&gt;

&lt;pre&gt;  0:   0
  1:   1
  2:   1
  3:   2
  4:   3
  5:   5
  6:   8
  7:  13
  8:  21
  9:  34
 10:  55
&lt;/pre&gt;&lt;a href=&#34;https://learnodo-newtonic.com/fibonacci-facts&#34;&gt;

Here&lt;/a&gt; are some interesting facts about the Leonardo Fibonacii.</content></entry><entry><title>Using ElasticSearch for Spatial Search tutorial</title><link href="http://www.varunpant.com/posts/using-elasticsearch-for-spatial-search-tutorial" rel="alternate" /><id>http://www.varunpant.com/posts/using-elasticsearch-for-spatial-search-tutorial</id><published>2014-07-20T00:00:00z</published><updated>2014-07-20T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;In this post I will demonstrate using &lt;a href=&#34;http://www.elasticsearch.org/&#34;&gt;ElasticSearch&lt;/a&gt; to spatially query records and &amp;nbsp;filter them by attributes.&lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;http://www.elasticsearch.org/&#34;&gt;ElasticSearch&lt;/a&gt; is built on top of &lt;a href=&#34;http://lucene.apache.org/&#34;&gt;Lucence&lt;/a&gt; which in version 4.0 supports Spatial query features, for those interested here is an &lt;a href=&#34;http://svn.apache.org/viewvc/lucene/dev/branches/branch_4x/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialExample.java?view=markup&#34;&gt;example&lt;/a&gt; and &lt;a href=&#34;http://lucene.apache.org/core/4_0_0/spatial/index.html&#34;&gt;link&lt;/a&gt; to javadocs.&lt;/p&gt;

&lt;p&gt;You will need to install &lt;a href=&#34;http://www.elasticsearch.org/&#34;&gt;ElasticSearch&lt;/a&gt;, read about installing it &lt;a href=&#34;http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/_installing_elasticsearch.html&#34;&gt;here&lt;/a&gt;, also install &lt;a href=&#34;http://www.elasticsearch.org/guide/en/marvel/current/&#34;&gt;marvel&lt;/a&gt; plugin for configuration and testing.&lt;/p&gt;

&lt;p&gt;For this demonstration I have used data from&amp;nbsp;&lt;a href=&#34;http://download.geofabrik.de/&#34;&gt;Geofabrik&lt;/a&gt;. I have used &lt;strong&gt;point.shp&lt;/strong&gt; file from &lt;a href=&#34;http://download.geofabrik.de/europe/great-britain.html&#34;&gt;Great Britan&lt;/a&gt; but you can use data from any other country as well.&lt;/p&gt;

&lt;p&gt;To extract the data,I wrote a quick python script using &lt;a href=&#34;https://code.google.com/p/pyshp/&#34;&gt;pyshp&lt;/a&gt;&amp;nbsp;library&lt;/p&gt;

&lt;p&gt;One can easily install it by typing &lt;code&gt;sudo easy_install pyshp&lt;/code&gt; in shell&lt;/p&gt;

&lt;h3&gt;Mapping type setup&lt;/h3&gt;

&lt;p&gt;Before uploading the records we need to create an Index in elasticsearch and apply schema mapping where we will instruct elasticsearch to create a geo index on location attribute.&lt;/p&gt;

&lt;p&gt;We can do this easily by issuing a curl request&lt;/p&gt;


&lt;pre&gt;
curl -XPUT http://localhost:9200/places -d &amp;#39;
{
    &amp;quot;mappings&amp;quot;: {
        &amp;quot;place&amp;quot;: {
            &amp;quot;properties&amp;quot;: {
                &amp;quot;id&amp;quot;: {&amp;quot;type&amp;quot;: &amp;quot;double&amp;quot;},
                &amp;quot;name&amp;quot;: {&amp;quot;type&amp;quot;: &amp;quot;string&amp;quot;},
                &amp;quot;type&amp;quot;: {&amp;quot;type&amp;quot;: &amp;quot;string&amp;quot;},
                &amp;quot;location&amp;quot;: {&amp;quot;type&amp;quot;: &amp;quot;geo_point&amp;quot;}
            }
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;Once the schema for index places has been set up, its now time to add records to the index.&lt;/p&gt;

&lt;p&gt;In the python script below modify the name of the shape file path and execute.&lt;/p&gt;



&lt;pre&gt;
import shapefile
import urllib2
import json
sf = shapefile.Reader(&amp;quot;points&amp;quot;)
sr = sf.shapeRecords()

for r in sr:
    try :
        if r.record[2].strip() and r.record[3].strip():
            req = urllib2.Request(&amp;#39;http://localhost:9200/places/place/&amp;#39;)
            req.add_header(&amp;#39;Content-Type&amp;#39;, &amp;#39;application/json&amp;#39;)
            data = {&amp;#39;id&amp;#39;: r.record[0].strip(),&amp;#39;name&amp;#39;:r.record[2].strip(),&amp;#39;type&amp;#39;:r.record[3].strip(),&amp;#39;location&amp;#39;:{&amp;#39;lat&amp;#39;:r.shape.points[0][1],&amp;#39;lon&amp;#39;:r.shape.points[0][0]}}
            response = urllib2.urlopen(req, json.dumps(data))
            print r.record[2]
    except Exception,e:
        print e
        #print &amp;quot;ERROR &amp;quot;,r.record[0],r.record[2],r.record[3] , r.shape.points[0][0], r.shape.points[0][1]
        pass
&lt;/pre&gt;

&lt;p&gt;The script inserts all records which have a valid &lt;b&gt;name&lt;/b&gt; and &lt;b&gt;type&lt;/b&gt; column into index.&lt;/p&gt;



&lt;h3&gt;Verify&lt;/h3&gt;

&lt;p&gt;Once complete we can quickly verify the number of records in the index by issuing.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;GET places/_count&lt;/code&gt; from &lt;b&gt;marvel&lt;/b&gt; or from a browser &lt;code&gt;http://localhost:9200/places/_count&lt;/code&gt;&lt;/p&gt;



&lt;h3&gt;Spatial Search&lt;/h3&gt;

&lt;p&gt;In &lt;strong&gt;Marvel/Sense&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;
GET places/_search
{
  &amp;quot;sort&amp;quot; : [
      {
          &amp;quot;_geo_distance&amp;quot; : {
              &amp;quot;location&amp;quot; : {
                    &amp;quot;lat&amp;quot;: 51.5286416,
                &amp;quot;lon&amp;quot;: -0.10159870000006777
              },
              &amp;quot;order&amp;quot; : &amp;quot;asc&amp;quot;,
              &amp;quot;unit&amp;quot; : &amp;quot;km&amp;quot;
          }
      }
  ],
  &amp;quot;query&amp;quot;: {
    &amp;quot;filtered&amp;quot; : {
        &amp;quot;query&amp;quot; : {
            &amp;quot;match_all&amp;quot; : {}
        },
        &amp;quot;filter&amp;quot; : {
            &amp;quot;geo_distance&amp;quot; : {
                &amp;quot;distance&amp;quot; : &amp;quot;20km&amp;quot;,
                &amp;quot;location&amp;quot; : {
                   &amp;quot;lat&amp;quot;: 51.5286416,
                   &amp;quot;lon&amp;quot;: -0.10159870000006777
                }
            }
        }
    }
  }
}
&lt;/pre&gt;

&lt;p&gt;or by &lt;strong&gt;curl&lt;/strong&gt;&lt;/p&gt;

&lt;pre&gt;
curl -XGET &amp;#39;http://localhost:9200/places/place/_search?pretty=true&amp;#39; -d &amp;#39;
{
  &amp;quot;sort&amp;quot; : [
      {
          &amp;quot;_geo_distance&amp;quot; : {
              &amp;quot;location&amp;quot; : {
                    &amp;quot;lat&amp;quot;: 51.5286416,
                   &amp;quot;lon&amp;quot;: -0.10159870000006777
              },
              &amp;quot;order&amp;quot; : &amp;quot;asc&amp;quot;,
              &amp;quot;unit&amp;quot; : &amp;quot;km&amp;quot;
          }
      }
  ],
  &amp;quot;query&amp;quot;: {
    &amp;quot;filtered&amp;quot; : {
        &amp;quot;query&amp;quot; : {
            &amp;quot;match_all&amp;quot; : {}
        },
        &amp;quot;filter&amp;quot; : {
            &amp;quot;geo_distance&amp;quot; : {
                &amp;quot;distance&amp;quot; : &amp;quot;20km&amp;quot;,
                &amp;quot;location&amp;quot; : {
                    &amp;quot;lat&amp;quot;: 51.5286416,
                   &amp;quot;lon&amp;quot;: -0.10159870000006777
                }
            }
        }
    }
  }
}&amp;#39;
&lt;/pre&gt;

&lt;p&gt;To search by &lt;strong&gt;Geodistance&lt;/strong&gt; as well as a &lt;strong&gt;term filter&lt;/strong&gt;, modify the query to.&lt;/p&gt;



&lt;pre&gt;
GET places / _search ? size = 100 &amp;amp; from = 0 {
    &amp;quot;sort&amp;quot;: [{
        &amp;quot;_geo_distance&amp;quot;: {
            &amp;quot;location&amp;quot;: {
                &amp;quot;lat&amp;quot;: 51.5286416,
                &amp;quot;lon&amp;quot;: -0.10159870000006777
            },
            &amp;quot;order&amp;quot;: &amp;quot;asc&amp;quot;,
            &amp;quot;unit&amp;quot;: &amp;quot;km&amp;quot;
        }
    }],
    &amp;quot;query&amp;quot;: {
        &amp;quot;filtered&amp;quot;: {
            &amp;quot;query&amp;quot;: {
                &amp;quot;bool&amp;quot;: {
                    &amp;quot;should&amp;quot;: [{
                        &amp;quot;term&amp;quot;: {
                            &amp;quot;type&amp;quot;: &amp;quot;pub&amp;quot;
                        }
                    }]
                }
            },
            &amp;quot;filter&amp;quot;: {
                &amp;quot;geo_distance&amp;quot;: {
                    &amp;quot;distance&amp;quot;: &amp;quot;1km&amp;quot;,
                    &amp;quot;location&amp;quot;: {
                        &amp;quot;lat&amp;quot;: 51.5286416,
                        &amp;quot;lon&amp;quot;: -0.10159870000006777
                    }
                }
            }
        }

    }
}
&lt;/pre&gt;

&lt;p&gt;For better visualisation I have created a nice webapp &lt;a href=&#34;https://github.com/varunpant/AroundMe&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;img style=&#34;width:100%&#34; alt=&#34;Web App&#34; src=&#34;https://raw.githubusercontent.com/varunpant/AroundMe/master/screenshot.png&#34; /&gt;&lt;/p&gt;
&lt;p&gt;Hope this helps&lt;/p&gt;
</content><category label="elasticsearch" scheme="http://www.varunpant.com/topics/elasticsearch/1" term="elasticsearch"></category><category label="geo_point" scheme="http://www.varunpant.com/topics/geo_point/1" term="geo_point"></category><category label="geo_distance" scheme="http://www.varunpant.com/topics/geo_distance/1" term="geo_distance"></category><category label="search" scheme="http://www.varunpant.com/topics/search/1" term="search"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category></entry><entry><title>CCS3 only Loading Icon</title><link href="http://www.varunpant.com/posts/ccs3-only-loading-icon" rel="alternate" /><id>http://www.varunpant.com/posts/ccs3-only-loading-icon</id><published>2014-07-13T00:00:00z</published><updated>2014-07-13T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;I generally have been using loading gifs in my work most of the time to inform the user that the resources are being fetched asynchronously from the server.&lt;/p&gt;

&lt;p&gt; &lt;a href=&#34;http://www.ajaxload.info/&#34;&gt;Ajaxload&lt;/a&gt; website is perhaps one of the most used site to download a suitable gif.&lt;/p&gt;

&lt;p&gt;In this post I will demonstrate a css3 only way to create a nice loading simulation &lt;/p&gt;
&lt;h3&gt;Basic Code&lt;/h3&gt;
&lt;p&gt;We will use nested divs to create the loading animation control

&lt;pre&gt;
&amp;lt;div class=&amp;quot;wrap&amp;quot;&amp;gt;
   &amp;lt;div class=&amp;#39;circle&amp;#39;&amp;gt;
      &amp;lt;div class=&amp;quot;clockNeedle&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/pre&gt;

&lt;br/&gt;
and css looks like this

&lt;pre&gt;
body{
  background-color: #fff;
  text-align: center;
  height: 100%;
}

html {
  height: 100%;
  overflow: hidden;
}

.wrap{
 position: absolute;
  top:0; left:0; bottom:0; right:0;
  margin: auto;
  width: 150px;
  height: 150px;
  border: 1px solid transparent;
}

.circle{
  width: 80%;
  height: 80%;
  border: 5px solid black;
  border-radius: 50%;
  position: absolute;
  bottom:0;
  margin-left: auto; margin-right: auto; left:0; right:0;
}


.clockNeedle{
  width: 50px;
  height: 5px;
  background: black;
  position: absolute;
  top: 50%;
  left: 10px;
  transform-origin:100% 50%;
  -webkit-transform-origin:100% 50%;
  -webkit-animation: needleAnimation 3s linear 0s infinite;
  animation: needleAnimation 3s linear 0s infinite;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes needleAnimation {
    from {   }
    to {
    	-ms-transform:rotate(360deg);
    	-moz-transform:rotate(360deg);
    	-webkit-transform:rotate(360deg);
	}
}

@keyframes needleAnimation {
   from { }
    to {
    	-ms-transform:rotate(360deg);
    	-moz-transform:rotate(360deg);
    	-webkit-transform:rotate(360deg);
	}
}
&lt;/pre&gt;
&lt;/p&gt;

&lt;h3&gt;Explanation&lt;/h3&gt;
&lt;p&gt;Basically to form the outer circle we simply use a div and make it circular by applying &lt;b&gt;border-radius &lt;/b&gt;property to &lt;b&gt;50%&lt;/b&gt;  &lt;code&gt; border-radius: 50%;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Needle div is styled to have the same background as the wrap, then the width is made 50% and height is 5 px so it looks like a line.  Later the a transform origin is applied to make it look like a clock needle and position it adjacent to the circle centre.&lt;/p&gt;
&lt;p&gt;
Css line &lt;code&gt; animation: needleAnimation 3s linear 0s infinite;&lt;/code&gt;  makes it rotate for infinite time.(it takes 3s for the animation to finish and repeat it self)
&lt;/p&gt;

&lt;p&gt;Hope you find this useful.&lt;/p&gt;
&lt;h3&gt;Live&lt;/h3&gt;
&lt;p data-height=&#34;268&#34; data-theme-id=&#34;0&#34; data-slug-hash=&#34;bwnaL&#34; data-default-tab=&#34;result&#34; class=&#39;codepen&#39;&gt;See the Pen &lt;a href=&#39;http://codepen.io/varunpant/pen/bwnaL/&#39;&gt;bwnaL&lt;/a&gt; by Varun (&lt;a href=&#39;http://codepen.io/varunpant&#39;&gt;@varunpant&lt;/a&gt;) on &lt;a href=&#39;http://codepen.io&#39;&gt;CodePen&lt;/a&gt;.&lt;/p&gt;
&lt;script async src=&#34;//codepen.io/assets/embed/ei.js&#34;&gt;&lt;/script&gt;

&lt;p&gt;&lt;a href=&#34;http://codepen.io/varunpant/pen/bwnaL?editors=110&#34;&gt;Here&lt;/a&gt; is a link to the actual demonstration&lt;/p&gt;

&lt;h3&gt;Edit&lt;/h3&gt;
&lt;p&gt;I also found another traditonal icon done in css3 &lt;a href=&#34;http://codepen.io/emgerold/pen/EwCxi&#34;&gt;here&lt;/a&gt; &lt;/p&gt;

&lt;p data-height=&#34;268&#34; data-theme-id=&#34;0&#34; data-slug-hash=&#34;EwCxi&#34; data-default-tab=&#34;result&#34; class=&#39;codepen&#39;&gt;See the Pen &lt;a href=&#39;http://codepen.io/emgerold/pen/EwCxi/&#39;&gt;Clean simple Ajax Spinner&lt;/a&gt; by emgerold (&lt;a href=&#39;http://codepen.io/emgerold&#39;&gt;@emgerold&lt;/a&gt;) on &lt;a href=&#39;http://codepen.io&#39;&gt;CodePen&lt;/a&gt;.&lt;/p&gt;
&lt;script async src=&#34;//codepen.io/assets/embed/ei.js&#34;&gt;&lt;/script&gt;</content><category label="css" scheme="http://www.varunpant.com/topics/css/1" term="css"></category><category label="html5" scheme="http://www.varunpant.com/topics/html5/1" term="html5"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category></entry><entry><title>How to install and configure grunt on mac Osx</title><link href="http://www.varunpant.com/posts/how-to-install-and-configure-grunt-on-mac-osx" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-install-and-configure-grunt-on-mac-osx</id><published>2014-07-12T00:00:00z</published><updated>2014-07-12T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;This post is intended to assist folks who are trying to install and work with grunt on mac osx&lt;/p&gt;

&lt;h3&gt;Install &lt;code&gt;Node.js&lt;/code&gt; and &lt;/code&gt;npm&lt;/code&gt; with Homebrew&lt;/h3&gt;
&lt;p&gt;First, install Homebrew by typing in the following command&lt;/code&gt;
&lt;code&gt;ruby -e &#34;$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)&#34;&lt;/code&gt;
&lt;p&gt;Then, type in  brew update to ensure your &lt;em&gt;Homebrew&lt;/em&gt; is up to date.&lt;/p&gt;
&lt;code&gt;brew update&lt;/code&gt;

&lt;p&gt;Run &lt;code&gt;brew doctor&lt;/code&gt; to make sure your system is all good. &lt;/p&gt;
&lt;p&gt;Follow any other recommendations from brew doctor.&lt;/p&gt;

&lt;p&gt;Next, add the Homebrew location to your &lt;code&gt;$PATH&lt;/code&gt; and source your bash profile &lt;/p&gt;
&lt;p&gt;&lt;code&gt;
export PATH=&#34;/usr/local/bin:$PATH&#34;
&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;install Node with NPM&lt;/h3&gt;
&lt;p&gt;&lt;code&gt;brew install node&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;To test out your Node and npm install, try installing Grunt (you might be asked to run with sudo)&lt;/p&gt;

&lt;p&gt;&lt;code&gt;sudo npm install -g grunt-cli&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;
Add the path from the grunt installer to your bash profile by typing in
&lt;code&gt;export PATH=/usr/local/lib/node_modules/grunt/bin:$PATH&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;Made the profile an executable &lt;code&gt;source ~/.bash_profile&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;this should do the trick&lt;/p&gt;
</content><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category></entry><entry><title>Normalizing Ranges of Numbers</title><link href="http://www.varunpant.com/posts/normalizing-ranges-of-numbers" rel="alternate" /><id>http://www.varunpant.com/posts/normalizing-ranges-of-numbers</id><published>2014-07-09T00:00:00z</published><updated>2014-07-09T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;Range Normalization is a &lt;a href=&#34;http://www.heatonresearch.com/wiki/Normalization&#34;&gt;normalization&lt;/a&gt; technique that allows you to map a number to a specific range.&lt;/p&gt;  &lt;p&gt;Lets say that we have a data set where the values are in a range of 1 to 10, however we wish to normalise it to a range between 0 and 5&lt;/p&gt;  &lt;p&gt;Mathematically speaking the equation comes down to&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/eq1_2.png&#34;&gt;&lt;img title=&#34;eq1&#34; style=&#34;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&#34; border=&#34;0&#34; alt=&#34;eq1&#34; src=&#34;http://varunpant.com/static/resources/eq1_thumb.png&#34; width=&#34;229&#34; height=&#34;31&#34; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/eq2_2.png&#34;&gt;&lt;img title=&#34;eq2&#34; style=&#34;border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px&#34; border=&#34;0&#34; alt=&#34;eq2&#34; src=&#34;http://varunpant.com/static/resources/eq2_thumb.png&#34; width=&#34;228&#34; height=&#34;30&#34; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;translated to Python &lt;/p&gt;

&lt;pre&gt;from __future__ import division
class Normaliser:

    def __init__(self,dH,dL,nH,nL):
        self.dH = dH
        self.dL = dL
        self.nH = nH
        self.nL = nL

    def normalize(self,x):
        return ((x - self.dL) / (self.dH - self.dL))  * (self.nH - self.nL) + self.nL

    def denormalize(self,x):
        return ((self.dL - self.dH) * x - self.nH * self.dL + self.dH * self.nL) / (self.nL - self.nH)

if __name__ == &amp;quot;__main__&amp;quot;:
    norm = Normaliser(10,1,5,0);

    for a in range(1,11):
        x = norm.normalize(a);
        y = norm.denormalize(x);
        print str(a) + &amp;quot; : &amp;quot; + str(x) + &amp;quot; : &amp;quot; + str(y)&lt;/pre&gt;

&lt;p&gt;The results&lt;/p&gt;

&lt;pre&gt;1 : 0.0 : 1.0
2 : 0.555555555556 : 2.0
3 : 1.11111111111 : 3.0
4 : 1.66666666667 : 4.0
5 : 2.22222222222 : 5.0
6 : 2.77777777778 : 6.0
7 : 3.33333333333 : 7.0
8 : 3.88888888889 : 8.0
9 : 4.44444444444 : 9.0
10 : 5.0 : 10.0&lt;/pre&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;Hope this helps.&lt;/p&gt;</content><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category></entry><entry><title>Install tile-stache on OsX Mavericks</title><link href="http://www.varunpant.com/posts/install-tile-stache-on-osx-mavericks" rel="alternate" /><id>http://www.varunpant.com/posts/install-tile-stache-on-osx-mavericks</id><published>2014-07-08T00:00:00z</published><updated>2014-07-08T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;This is quick tutorial about installing &lt;a href=&#34;http://tilestache.org/&#34;&gt;Tilestache&lt;/a&gt; library in OSX Mavericks.&lt;/p&gt;
&lt;h3 id=&#34;step-1&#34;&gt;Step 1&lt;/h3&gt;
&lt;p&gt;Make sure Developer tools are installed
&lt;code&gt;xcode-select --install&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Then add these flags to tell xcode to use python like rest of the world does&lt;/p&gt;
&lt;p&gt; &lt;code&gt;export CFLAGS=-Qunused-arguments&lt;/code&gt;&lt;/p&gt;
&lt;p&gt; &lt;code&gt;export CPPFLAGS=-Qunused-arguments&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Finally type in  &lt;code&gt;sudo easy_install tilestache&lt;/code&gt;&lt;/p&gt;
&lt;p&gt;Thats it all done, you might see some warnings but thats fine ignore them .&lt;/p&gt;
&lt;p&gt;Read the introduction &lt;a href=&#34;http://mike.teczno.com/notes/tilestache.html&#34;&gt;here&lt;/a&gt; to get started&lt;/p&gt;
&lt;p&gt;Hope it helps.&lt;/p&gt;
</content><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category></entry><entry><title>how to make a web crawler in python</title><link href="http://www.varunpant.com/posts/how-to-make-a-web-crawler-in-python" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-make-a-web-crawler-in-python</id><published>2014-02-01T00:00:00z</published><updated>2014-02-01T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;Here is a very simple web crawler in python&lt;/p&gt;
&lt;p&gt;
  &lt;pre&gt;
import sys, thread, Queue, re, urllib, urlparse, time, os, sys
dupcheck = set()  
q = Queue.Queue(100) 
q.put(&#34;http://www.varunpant.com&#34;) 
def queueURLs(html, origLink): 
    for url in re.findall(&#39;&#39;&#39;&lt;a[^&gt;]+href=[&#34;&#39;](.[^&#34;&#39;]+)[&#34;&#39;]&#39;&#39;&#39;, html, re.I): 
        link = url.split(&#34;#&#34;, 1)[0] if url.startswith(&#34;http&#34;) else &#39;{uri.scheme}://{uri.netloc}&#39;.format(uri=urlparse.urlparse(origLink)) + url.split(&#34;#&#34;, 1)[0] 
        if link in dupcheck:
            continue
        dupcheck.add(link)
        if len(dupcheck) &gt; 99999: 
            dupcheck.clear()
        q.put(link) 
def getHTML(link): 
    try:
        html = urllib.urlopen(link).read() 
        print link
        # open(str(time.time()) + &#34;.html&#34;, &#34;w&#34;).write(&#34;&#34; % link  + &#34;\n&#34; + html) 
        queueURLs(html, link) 
    except (KeyboardInterrupt, SystemExit): 
        raise
    except Exception:
        pass
while True:
    thread.start_new_thread( getHTML, (q.get(),)) 
    time.sleep(0.5)
&lt;/pre&gt;
&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category></entry><entry><title>Ternary search tree</title><link href="http://www.varunpant.com/posts/ternary-search-tree" rel="alternate" /><id>http://www.varunpant.com/posts/ternary-search-tree</id><published>2014-01-26T00:00:00z</published><updated>2014-01-26T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;In &lt;a href=&#34;http://en.wikipedia.org/wiki/Computer_science&#34;&gt;computer science&lt;/a&gt;, a &lt;b&gt;ternary search tree&lt;/b&gt; is a type of &lt;a href=&#34;http://en.wikipedia.org/wiki/Trie&#34;&gt;prefix tree&lt;/a&gt; where nodes are arranged as a &lt;a href=&#34;http://en.wikipedia.org/wiki/Binary_search_tree&#34;&gt;binary search tree&lt;/a&gt;. Like other prefix trees, a ternary search tree can be used as an &lt;a href=&#34;http://en.wikipedia.org/wiki/Associative_map&#34;&gt;associative map&lt;/a&gt; structure with the ability for incremental &lt;a href=&#34;http://en.wikipedia.org/wiki/String_search&#34;&gt;string search&lt;/a&gt;. However, ternary search trees are more space efficient compared to standard prefix trees, at the cost of speed. Common applications for ternary search trees include &lt;a href=&#34;http://en.wikipedia.org/wiki/Spell-check&#34;&gt;spell-checking&lt;/a&gt; and &lt;a href=&#34;http://en.wikipedia.org/wiki/Auto-completion&#34;&gt;auto-completion&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;As with other trie data structures, each node in a ternary search tree represents a prefix of the stored strings. All strings in the middle subtree of a node start with that prefix.&lt;/p&gt;  &lt;p&gt;In this blog post I present a c# version of Ternary Search Tree.&lt;/p&gt;  &lt;h3&gt;The interface&lt;/h3&gt;  &lt;pre class=&#34;csharpcode&#34;&gt;&lt;span class=&#34;kwrd&#34;&gt;interface&lt;/span&gt; ITernaryTree&amp;lt;T&amp;gt;
    {
        &lt;span class=&#34;kwrd&#34;&gt;void&lt;/span&gt; Add(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; key, T &lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt;);
        &lt;span class=&#34;kwrd&#34;&gt;bool&lt;/span&gt; Contains(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; key);
        System.Collections.Generic.IEnumerable&amp;lt;&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;&amp;gt; Keys { get; }
        &lt;span class=&#34;kwrd&#34;&gt;int&lt;/span&gt; Length { get; }
        System.Collections.Generic.IEnumerable&amp;lt;T&amp;gt; NearSearch(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; query, &lt;span class=&#34;kwrd&#34;&gt;int&lt;/span&gt; distance);
        System.Collections.Generic.IEnumerable&amp;lt;&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;&amp;gt; PrefixMatch(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; prefix);
        System.Collections.Generic.IEnumerable&amp;lt;T&amp;gt; Search(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; prefix);
        T &lt;span class=&#34;kwrd&#34;&gt;this&lt;/span&gt;[&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; key] { get; }
        System.Collections.Generic.IEnumerable&amp;lt;&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;&amp;gt; WildcardMatch(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; pat);
    }&lt;/pre&gt;

&lt;p&gt;The interface above defines the API for the data structure. Lets take a deeper look.&lt;/p&gt;

&lt;table class=&#34;gridtable&#34;&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;void&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Add(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; key, T &lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt;)&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Add a key value pair in the tree.&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;bool&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Contains(string key)&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Check whether a key is in tree.&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;IEnumerable&amp;lt;&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;&amp;gt;&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;&amp;lt;&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;&amp;gt; Keys &lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Return all keys in the tree.&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;int&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Length&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Returns the length of the tree.&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;NearSearch(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; query, &lt;span class=&#34;kwrd&#34;&gt;int&lt;/span&gt; distance)&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Returns all values for keys in the dictionary that are within a given Hamming distance of a query.&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;IEnumerable&amp;lt;&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;&amp;gt;&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;PrefixMatch(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; prefix)&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Returns all keys starting with a given prefix.&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Search(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; prefix)&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Searches all values of keys starting with given prefix.&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;T &lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;&lt;span class=&#34;kwrd&#34;&gt;this&lt;/span&gt;[&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; key]&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Gets the node value with the specified key&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;IEnumerable&amp;lt;&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;&amp;gt;&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;WildcardMatch(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; pat)&lt;/td&gt;

      &lt;td valign=&#34;top&#34; width=&#34;133&#34;&gt;Returns all keys matching given wilcard pattern.&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;h3&gt;The Trie Node&lt;/h3&gt;

&lt;pre class=&#34;csharpcode&#34;&gt;&lt;span class=&#34;kwrd&#34;&gt;class&lt;/span&gt; Node
        {
            &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
            &lt;span class=&#34;rem&#34;&gt;/// character&lt;/span&gt;
            &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
            &lt;span class=&#34;kwrd&#34;&gt;internal&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;char&lt;/span&gt; c;

            &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
            &lt;span class=&#34;rem&#34;&gt;/// The  left, middle, and right subtries.&lt;/span&gt;
            &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
            &lt;span class=&#34;kwrd&#34;&gt;internal&lt;/span&gt; Node left, mid, right;

            &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
            &lt;span class=&#34;rem&#34;&gt;/// The value associated .&lt;/span&gt;
            &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
            &lt;span class=&#34;kwrd&#34;&gt;internal&lt;/span&gt; T &lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt;;
        }&lt;/pre&gt;

&lt;p&gt;The Class is mostly self explanatory, but the key points to note is that it contains three internal node(sub-tries) unlike a traditional trie node. &lt;/p&gt;

&lt;p&gt;Adding node in the data structure&lt;/p&gt;

&lt;pre class=&#34;csharpcode&#34;&gt;        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// Adds the specified key.&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;param name=&amp;quot;key&amp;quot;&amp;gt;The key.&amp;lt;/param&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;param name=&amp;quot;value&amp;quot;&amp;gt;The value.&amp;lt;/param&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;kwrd&#34;&gt;public&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;void&lt;/span&gt; Add(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; key, T &lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt;)
        {
            &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;.IsNullOrEmpty(key)) { &lt;span class=&#34;kwrd&#34;&gt;throw&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;new&lt;/span&gt; InvalidOperationException(&lt;span class=&#34;str&#34;&gt;&amp;quot;Keys cannot be null or empty.&amp;quot;&lt;/span&gt;); }
            &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (!Contains(key)) N++;
            root = Add(root, key, &lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt;, 0);
        }

        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// Adds the specified node in the tree.&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;param name=&amp;quot;node&amp;quot;&amp;gt;The Node.&amp;lt;/param&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;param name=&amp;quot;key&amp;quot;&amp;gt;The key.&amp;lt;/param&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;param name=&amp;quot;value&amp;quot;&amp;gt;The val.&amp;lt;/param&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;param name=&amp;quot;charIndex&amp;quot;&amp;gt;The d.&amp;lt;/param&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;&lt;/span&gt;
        Node Add(Node node, &lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; key, T &lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt;, &lt;span class=&#34;kwrd&#34;&gt;int&lt;/span&gt; charIndex)
        {
            &lt;span class=&#34;kwrd&#34;&gt;char&lt;/span&gt; charAtIndex = key[charIndex];
            &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (node == &lt;span class=&#34;kwrd&#34;&gt;null&lt;/span&gt;) { node = &lt;span class=&#34;kwrd&#34;&gt;new&lt;/span&gt; Node(); node.c = charAtIndex; }
            &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (charAtIndex &amp;lt; node.c) node.left = Add(node.left, key, &lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt;, charIndex);
            &lt;span class=&#34;kwrd&#34;&gt;else&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (charAtIndex &amp;gt; node.c) node.right = Add(node.right, key, &lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt;, charIndex);
            &lt;span class=&#34;kwrd&#34;&gt;else&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (charIndex &amp;lt; key.Length - 1)
                node.mid = Add(node.mid, key, &lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt;, charIndex + 1);
            &lt;span class=&#34;kwrd&#34;&gt;else&lt;/span&gt; node.&lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt; = &lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt;;
            &lt;span class=&#34;kwrd&#34;&gt;return&lt;/span&gt; node;
        }&lt;/pre&gt;

&lt;h3&gt;Get&lt;/h3&gt;

&lt;pre class=&#34;csharpcode&#34;&gt;&lt;span class=&#34;rem&#34;&gt;        /// &amp;lt;summary&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// Gets the specified x.&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;param name=&amp;quot;node&amp;quot;&amp;gt;The x.&amp;lt;/param&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;param name=&amp;quot;key&amp;quot;&amp;gt;The key.&amp;lt;/param&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;param name=&amp;quot;charIndex&amp;quot;&amp;gt;The d.&amp;lt;/param&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;&lt;/span&gt;
        Node Get(Node node, &lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; key, &lt;span class=&#34;kwrd&#34;&gt;int&lt;/span&gt; charIndex)
        {
            &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (node == &lt;span class=&#34;kwrd&#34;&gt;null&lt;/span&gt;) &lt;span class=&#34;kwrd&#34;&gt;return&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;null&lt;/span&gt;;
            &lt;span class=&#34;kwrd&#34;&gt;char&lt;/span&gt; c = key[charIndex];
            &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (c &amp;lt; node.c) &lt;span class=&#34;kwrd&#34;&gt;return&lt;/span&gt; Get(node.left, key, charIndex);
            &lt;span class=&#34;kwrd&#34;&gt;else&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (c &amp;gt; node.c) &lt;span class=&#34;kwrd&#34;&gt;return&lt;/span&gt; Get(node.right, key, charIndex);
            &lt;span class=&#34;kwrd&#34;&gt;else&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (charIndex &amp;lt; key.Length - 1)
                &lt;span class=&#34;kwrd&#34;&gt;return&lt;/span&gt; Get(node.mid, key, charIndex + 1);
            &lt;span class=&#34;kwrd&#34;&gt;else&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;return&lt;/span&gt; node;
        }&lt;/pre&gt;

&lt;p&gt;and finally&lt;/p&gt;

&lt;h3&gt;PrefixMatch&lt;/h3&gt;

&lt;pre class=&#34;csharpcode&#34;&gt;        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;summary&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// Returns all keys starting with a given prefix.&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;/summary&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;param name=&amp;quot;prefix&amp;quot;&amp;gt;The prefix.&amp;lt;/param&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;rem&#34;&gt;/// &amp;lt;returns&amp;gt;&amp;lt;/returns&amp;gt;&lt;/span&gt;
        &lt;span class=&#34;kwrd&#34;&gt;public&lt;/span&gt; IEnumerable&amp;lt;&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;&amp;gt; PrefixMatch(&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt; prefix)
        {
            Queue&amp;lt;&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;&amp;gt; queue = &lt;span class=&#34;kwrd&#34;&gt;new&lt;/span&gt; Queue&amp;lt;&lt;span class=&#34;kwrd&#34;&gt;string&lt;/span&gt;&amp;gt;();
            Node node = Get(root, prefix, 0);
            &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (node == &lt;span class=&#34;kwrd&#34;&gt;null&lt;/span&gt;) &lt;span class=&#34;kwrd&#34;&gt;return&lt;/span&gt; queue;
            &lt;span class=&#34;kwrd&#34;&gt;if&lt;/span&gt; (node.&lt;span class=&#34;kwrd&#34;&gt;value&lt;/span&gt; != &lt;span class=&#34;kwrd&#34;&gt;null&lt;/span&gt;) queue.Enqueue(prefix);
            Collect(node.mid, prefix, queue);
            &lt;span class=&#34;kwrd&#34;&gt;return&lt;/span&gt; queue;
        }&lt;/pre&gt;

&lt;p&gt;To see a complete working example check out the Github page &lt;a href=&#34;https://github.com/varunpant/TernaryTree/blob/master/TernaryTree/TernarySearchTree/TernaryTree.cs&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Full repo can be found &lt;a href=&#34;https://github.com/varunpant/TernaryTree&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;. There is a test web application demonstrating auto suggest included in the project, I will write more about it in a later post.&lt;/p&gt;</content><category label=".net" scheme="http://www.varunpant.com/topics/net/1" term=".net"></category><category label="datastructure" scheme="http://www.varunpant.com/topics/datastructure/1" term="datastructure"></category></entry><entry><title>Gheat Java – Heat maps</title><link href="http://www.varunpant.com/posts/gheat-java-heat-maps" rel="alternate" /><id>http://www.varunpant.com/posts/gheat-java-heat-maps</id><published>2014-01-24T00:00:00z</published><updated>2014-01-24T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/heat_map_2.jpg&#34;&gt;&lt;img title=&#34;heat_map&#34; alt=&#34;heat_map&#34; src=&#34;http://varunpant.com/static/resources/heat_map_thumb.jpg&#34; width=&#34;95%&#34; /&gt;&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;A &lt;b&gt;heat map&lt;/b&gt; is a graphical representation of data where the individual values contained in a &lt;a href=&#34;http://en.wikipedia.org/wiki/Matrix_(mathematics)&#34;&gt;matrix&lt;/a&gt; are represented as colors.&lt;/p&gt;  &lt;p&gt;This article will attempt to explain the process or creating and using &lt;a href=&#34;https://github.com/varunpant/GHEAT-JAVA&#34; target=&#34;_blank&#34;&gt;GHEAT-JAVA&lt;/a&gt;, which is&amp;#160; a port of famous aspen based &lt;a href=&#34;https://code.google.com/p/gheat/&#34; target=&#34;_blank&#34;&gt;gheat&lt;/a&gt; and took great inspiration from &lt;a href=&#34;http://www.codeproject.com/Articles/88956/GHeat-NET&#34; target=&#34;_blank&#34;&gt;Gheat.net&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Writing a service which would serve heat map tiles is a bit tricky,there are three major components involved&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;The client part i.e. some kind of mapping library which has a concept of layer, I chose Google maps. &lt;/li&gt;    &lt;li&gt;The data source part, i.e. a spatially aware database or an in memory data structure, I have used postgres ,an in memory quad tree and a flat file as data sources. &lt;/li&gt;    &lt;li&gt;The renderer part or basically the code which excepts requests , parses tile bounds, fetches data and then renders gradients on the tile and later colorizes them. &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;h3&gt;The Tiling layer (Client part)&lt;/h3&gt;  &lt;p&gt;Google maps allows developers to add a custom layer , the code looks like this&lt;/p&gt;  &lt;pre class=&#34;csharpcode&#34;&gt;&lt;span class=&#34;kwrd&#34;&gt;function&lt;/span&gt; getHeatMapObject(colorScheme) {
            &lt;span class=&#34;kwrd&#34;&gt;var&lt;/span&gt; heatMapOptions = {
                getTileUrl:&lt;span class=&#34;kwrd&#34;&gt;function&lt;/span&gt; (tile, zoom) {

                    &lt;span class=&#34;kwrd&#34;&gt;return&lt;/span&gt; &lt;span class=&#34;str&#34;&gt;&#39;http://localhost:8080?colorScheme=&#39;&lt;/span&gt; + colorScheme + &lt;span class=&#34;str&#34;&gt;&#39;&amp;amp;zoom=&#39;&lt;/span&gt; +
                            zoom +
                            &lt;span class=&#34;str&#34;&gt;&#39;&amp;amp;x=&#39;&lt;/span&gt; + tile.x +
                            &lt;span class=&#34;str&#34;&gt;&#39;&amp;amp;y=&#39;&lt;/span&gt; + tile.y; &lt;span class=&#34;rem&#34;&gt;//+&lt;/span&gt;
                    &lt;span class=&#34;rem&#34;&gt;//remove this bit if browser caching is desired&lt;/span&gt;
                    &lt;span class=&#34;str&#34;&gt;&#39;&amp;amp;rand=&#39;&lt;/span&gt; + Math.random();
                },
                tileSize:&lt;span class=&#34;kwrd&#34;&gt;new&lt;/span&gt; google.maps.Size(256, 256),
                isPng:&lt;span class=&#34;kwrd&#34;&gt;true&lt;/span&gt;,
                releaseTile:&lt;span class=&#34;kwrd&#34;&gt;function&lt;/span&gt; (tile, zoom) {
                    &lt;span class=&#34;rem&#34;&gt;//Called when a tile is out of view&lt;/span&gt;
                },
                name:colorScheme + &lt;span class=&#34;str&#34;&gt;&amp;quot;Heat Map&amp;quot;&lt;/span&gt;
            };
            &lt;span class=&#34;kwrd&#34;&gt;return&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;new&lt;/span&gt; google.maps.ImageMapType(heatMapOptions);
        }&lt;/pre&gt;

&lt;p&gt;I have left the bit which deals with different color schemes out as its trivial. &lt;/p&gt;

&lt;h3&gt;The Data Source&lt;/h3&gt;

&lt;p&gt;The service can query a spatial database, I have included a data provider for postgres. Here is the sample query which the application executes&lt;/p&gt;

&lt;pre class=&#34;csharpcode&#34;&gt;&lt;span class=&#34;kwrd&#34;&gt;SELECT&lt;/span&gt; ST_X(geom) &lt;span class=&#34;kwrd&#34;&gt;as&lt;/span&gt; longitude,ST_Y(geom) &lt;span class=&#34;kwrd&#34;&gt;as&lt;/span&gt; latitude, weight &lt;span class=&#34;kwrd&#34;&gt;as&lt;/span&gt; weight &lt;span class=&#34;kwrd&#34;&gt;from&lt;/span&gt; mySpatialTable &lt;span class=&#34;kwrd&#34;&gt;where&lt;/span&gt; geom @ ST_MakeEnvelope(?,?,?,?,4326)&amp;quot;&lt;/pre&gt;

&lt;p&gt;As its evident that a table is needed with x, y and weight columns, where x and y are the coordinates of datum in EPSG:4326 projection and weight is an integer between1 and 5&lt;/p&gt;

&lt;p&gt;I have also included an in-memory spatial data structure called &lt;a href=&#34;http://en.wikipedia.org/wiki/Quadtree&#34; target=&#34;_blank&#34;&gt;Quadtree&lt;/a&gt; which is pretty ideal for fast spatial look up, look in App.java to see how to populate this data source.&lt;/p&gt;

&lt;p&gt;Finally there is a file data source which is pretty slow for large data lookup but is included anyways ;/&lt;/p&gt;

&lt;h3&gt;The Renderer&lt;/h3&gt;

&lt;p&gt;The rendering algorithm is as follows&lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Parse the request and get tile bounds. &lt;/li&gt;

  &lt;li&gt;Use the bounds to query data source for points. &lt;/li&gt;

  &lt;li&gt;if the data source returns empty, return empty tile, &lt;/li&gt;

  &lt;li&gt;Otherwise
    &lt;ol&gt;
      &lt;li&gt;Expand the height and width of tile by one dot width.(Apply padding) &lt;/li&gt;

      &lt;li&gt;Generate a blank image of desired dimensions (256 x 256) &lt;/li&gt;

      &lt;li&gt;Add gradient depending on the zoom level and weight for each point on the blank image. &lt;/li&gt;

      &lt;li&gt;To the gray scale gradient map we add color pixel by pixel by mapping them to the color scheme which is 255 pixels high. &lt;/li&gt;

      &lt;li&gt;Finally the tile is trimmed due to it having to be larger to accommodate points on the edges of a tile. &lt;/li&gt;
    &lt;/ol&gt;
  &lt;/li&gt;

  &lt;li&gt;Return heat map tile. &lt;/li&gt;
&lt;/ol&gt;</content><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="gis" scheme="http://www.varunpant.com/topics/gis/1" term="gis"></category><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category><category label="java" scheme="http://www.varunpant.com/topics/java/1" term="java"></category></entry><entry><title>Raphael-js-tutorial-part-II</title><link href="http://www.varunpant.com/posts/raphael-js-tutorial-part-ii" rel="alternate" /><id>http://www.varunpant.com/posts/raphael-js-tutorial-part-ii</id><published>2013-12-25T00:00:00z</published><updated>2013-12-25T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;This is second part of the tutorial about getting started with &lt;a href=&#34;http://raphaeljs.com/&#34; target=&#34;_blank&#34;&gt;Raphael.js&lt;/a&gt;. To see this first part go &lt;a href=&#34;http://www.varunpant.com/posts/raphael-js-tutorial-part-i&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;  &lt;h4&gt;Writing Text with Raphael&lt;/h4&gt;  Some code first ;)  &lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;var canvas = Raphael(0, 0, 250, 250 );

&lt;b&gt;var&lt;/b&gt; t = canvas.text(50, 50, &lt;i&gt;&amp;quot;Some text Goes here&amp;quot;&lt;/i&gt;);

var t2 = canvas.text(60,90,&amp;quot;First line \n Second Line \n Third line&amp;quot;);

var t3 = canvas.text(214, 140, &amp;quot;1079&amp;quot;).attr({&amp;quot;text-anchor&amp;quot;:&amp;quot;middle&amp;quot;,&#39;font-size&#39;:16,&amp;quot;font-family&amp;quot;:&amp;quot;arial&amp;quot;,&amp;quot;fill&amp;quot;:&amp;quot;#fff&amp;quot;});&lt;/pre&gt;
&lt;iframe style=&#34;width: 250px; height: 250px&#34; class=&#34;well&#34; src=&#34;http://www.varunpant.com/static/resources/Raphael.JS%20Tutorial/sample5.html&#34;&gt;&lt;/iframe&gt;

&lt;p&gt;In the above examples canvas.text will create a simple text element at 50,50. Strangely VML /SVG do not have Line breaks therefore the programmer is responsible for creating new lines,in most cases appending&lt;strong&gt; &#39;\n&#39;&lt;/strong&gt; does the trick.&lt;/p&gt;

&lt;p&gt;While styling your text ,attribute text-anchor is quite important, it defaults to &lt;strong&gt;&#39;middle&#39;&lt;/strong&gt; but can be changed to &lt;strong&gt;start&lt;/strong&gt; and end as &lt;strong&gt;well&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;Default Attributes Styling and adding Custom Attributes&lt;/h3&gt;

&lt;p&gt;Raphael honors &lt;a href=&#34;http://www.w3.org/TR/SVG/&#34; target=&#34;_blank&#34;&gt;SVG Attribute&lt;/a&gt; Specification and lets the user customize them by &lt;a href=&#34;http://raphaeljs.com/reference.html#Element.attr&#34; target=&#34;_blank&#34;&gt;attr()&lt;/a&gt; method.&lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;canvas = Raphael(0, 0, 250, 250 );
// Creates circle at x = 125, y = 125, with radius 50
var circle = canvas.circle(125, 125, 50);
// Sets the fill attribute of the circle to red (#f00)
circle.&lt;strong&gt;attr&lt;/strong&gt;(&amp;quot;&lt;strong&gt;fill&lt;/strong&gt;&amp;quot;, &amp;quot;&lt;strong&gt;blue&lt;/strong&gt;&amp;quot;);
// Sets the stroke attribute of the circle to white
circle.&lt;strong&gt;attr&lt;/strong&gt;(&amp;quot;&lt;strong&gt;stroke&lt;/strong&gt;&amp;quot;, &lt;strong&gt;&amp;quot;#fff&lt;/strong&gt;&amp;quot;);&lt;/pre&gt;
&lt;iframe style=&#34;width: 250px; height: 250px&#34; class=&#34;well&#34; src=&#34;http://www.varunpant.com/static/resources/Raphael.JS%20Tutorial/sample6.html&#34;&gt;&lt;/iframe&gt;

&lt;h4&gt;Animation&lt;/h4&gt;

&lt;p&gt;The library comes with an &lt;a href=&#34;http://raphaeljs.com/reference.html#Element.animate&#34; target=&#34;_blank&#34;&gt;animate&lt;/a&gt; function which is perhaps one of my favorite implementation, its simple easy and packs a big punch.&lt;/p&gt;

&lt;p&gt;Animation is a basically a process of fiddling with the attributes of a vector in a timed routine, so lets say that we have a circle i.e&lt;/p&gt;

&lt;p&gt;var circle&amp;#160; =&amp;#160; canvas.circle(125,125,50) &lt;/p&gt;

&lt;p&gt;i.e. a circle with its center at 125,125 and radius 50 , so I want to animate the radius of the circle to say 25, I will simply do this&lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;

&lt;b&gt;var&lt;/b&gt; anim = Raphael.animation({r:25}, 1000);

circle.animate(anim);&lt;/pre&gt;

There are some helper methods built in like

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;circle.animate(anim.delay(500)); // run the given animation after 500 ms&lt;/pre&gt;
&lt;b&gt;or&lt;/b&gt;

circle.animate(anim.repeat(Infinity));&lt;/pre&gt;

One can also pass in a easing functions, like this

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;var anim = Raphael.animation({r:25,fill:&amp;quot;red&amp;quot;}, 1000,&amp;quot;bounce&amp;quot;);&lt;/pre&gt;

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;Check out more easing functions &lt;a href=&#34;http://raphaeljs.com/easing.html&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt; &lt;/pre&gt;
&lt;iframe style=&#34;width: 250px; height: 250px&#34; class=&#34;well&#34; src=&#34;http://www.varunpant.com/static/resources/Raphael.JS%20Tutorial/sample7.html&#34;&gt;&lt;/iframe&gt;

&lt;p&gt;Finally I will add a custom widget which I animated from my last example in the first part.&lt;/p&gt;
&lt;iframe style=&#34;width: 250px; height: 250px&#34; class=&#34;well&#34; src=&#34;http://www.varunpant.com/static/resources/Raphael.JS%20Tutorial/sample8.html&#34;&gt;&lt;/iframe&gt;</content><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="fun" scheme="http://www.varunpant.com/topics/fun/1" term="fun"></category><category label="javascript" scheme="http://www.varunpant.com/topics/javascript/1" term="javascript"></category><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="raphael js" scheme="http://www.varunpant.com/topics/raphael-js/1" term="raphael js"></category></entry><entry><title>Turn Off Autocomplete for Input</title><link href="http://www.varunpant.com/posts/turn-off-autocomplete-for-input" rel="alternate" /><id>http://www.varunpant.com/posts/turn-off-autocomplete-for-input</id><published>2013-12-01T00:00:00z</published><updated>2013-12-01T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;The autocomplete attribute specifies whether or not an input field should have autocomplete enabled.&lt;/p&gt;  &lt;p&gt;Autocomplete allows the browser to predict the value from locally saved history/cache. When a user starts to type in a field, the browser should display options to fill in the field, based on earlier typed values. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; The autocomplete attribute works with the following &amp;lt;input&amp;gt; types: text, search, url, tel, email, password, datepickers, range, and color.&lt;/p&gt;  &lt;p&gt;example usage:&lt;/p&gt;&lt;code&gt; &amp;lt;input name=&amp;quot;q&amp;quot; autocomplete=&amp;quot;off&amp;quot; /&amp;gt;&lt;/code&gt;   </content><category label="snippet" scheme="http://www.varunpant.com/topics/snippet/1" term="snippet"></category></entry><entry><title>Embedding Flash,Quicktime,Windows Media,Silverlight or HTML5 Video</title><link href="http://www.varunpant.com/posts/embedding-flash-quicktime-windows-media-silverlight-or-html5-video" rel="alternate" /><id>http://www.varunpant.com/posts/embedding-flash-quicktime-windows-media-silverlight-or-html5-video</id><published>2013-10-01T00:00:00z</published><updated>2013-10-01T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;h3&gt;Flash Object&lt;/h3&gt;  &lt;p&gt;This is quick Snippet which demonstrate how to embed flash object in a web page.&lt;/p&gt;  &lt;pre class=&#34;csharpcode&#34;&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;object&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;type&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;application/x-shockwave-flash&amp;quot;&lt;/span&gt;
  &lt;span class=&#34;attr&#34;&gt;data&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;path-to-my-flash-file.swf&amp;quot;&lt;/span&gt;
  &lt;span class=&#34;attr&#34;&gt;width&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;0&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;height&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;0&amp;quot;&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;
  &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;movie&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;your-flash-file.swf&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
  &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;quality&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;high&amp;quot;&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
&lt;span class=&#34;kwrd&#34;&gt;&amp;lt;/&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;object&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;h3&gt;Quicktime&lt;/h3&gt;

&lt;p&gt;This is quick Snippet which demonstrate how to embed quicktime object in a web page&lt;/p&gt;

&lt;pre class=&#34;csharpcode&#34;&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;object&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;classid&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B&amp;quot;&lt;/span&gt;
       &lt;span class=&#34;attr&#34;&gt;codebase&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;http://www.apple.com/qtactivex/qtplugin.cab&amp;quot;&lt;/span&gt;
       &lt;span class=&#34;attr&#34;&gt;width&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;200&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;height&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;16&amp;quot;&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;
 &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;src&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;pathToMyMovie.mov&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
 &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;autoplay&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;true&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
 &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;pluginspage&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;http://www.apple.com/quicktime/download/&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
 &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;controller&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;true&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
 &lt;span class=&#34;rem&#34;&gt;&amp;lt;!--[if !IE]&amp;gt; &amp;lt;--&amp;gt;&lt;/span&gt;
   &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;object&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;data&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;movie.mov&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;width&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;200&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;height&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;16&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;type&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;video/quicktime&amp;quot;&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;
     &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;pluginurl&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;http://www.apple.com/quicktime/download/&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
     &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;controller&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;true&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
   &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;/&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;object&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;
 &lt;span class=&#34;rem&#34;&gt;&amp;lt;!--&amp;gt; &amp;lt;![endif]--&amp;gt;&lt;/span&gt;
&lt;span class=&#34;kwrd&#34;&gt;&amp;lt;/&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;object&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;h3&gt;Windows Media&lt;/h3&gt;

&lt;p&gt;This is quick Snippet which demonstrate how to embed Windows Media object in a web page.&lt;/p&gt;

&lt;pre class=&#34;csharpcode&#34;&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;object&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;type&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;video/x-ms-wmv&amp;quot;&lt;/span&gt;
  &lt;span class=&#34;attr&#34;&gt;data&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;pathToMyMovie.wmv&amp;quot;&lt;/span&gt;
  &lt;span class=&#34;attr&#34;&gt;width&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;320&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;height&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;260&amp;quot;&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;
  &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;src&amp;quot;&lt;/span&gt;
    &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;pathToMyMovie.wmv&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
  &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;autostart&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;true&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
  &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;controller&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;true&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
&lt;span class=&#34;kwrd&#34;&gt;&amp;lt;/&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;object&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;h3&gt;Silver Light&lt;/h3&gt;

&lt;p&gt;This is quick Snippet which demonstrate how to embed Silverlight object in a web page.&lt;/p&gt;

&lt;pre class=&#34;csharpcode&#34;&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;object&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;width&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;300&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;height&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;300&amp;quot;&lt;/span&gt;
    &lt;span class=&#34;attr&#34;&gt;data&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;data:application/x-silverlight-2,&amp;quot;&lt;/span&gt;
    &lt;span class=&#34;attr&#34;&gt;type&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;application/x-silverlight-2&amp;quot;&lt;/span&gt; &lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;
    &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;param&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;name&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;source&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;value&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;SilverlightApplication1.xap&amp;quot;&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;/&amp;gt;&lt;/span&gt;
&lt;span class=&#34;kwrd&#34;&gt;&amp;lt;/&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;object&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;h3&gt;HTML5 Video&lt;/h3&gt;

&lt;pre class=&#34;csharpcode&#34;&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;video&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;width&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;300&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;height&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;300&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;controls&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;
  &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;source&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;src&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;pathToMyMovie.mp4&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;type&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;video/mp4&amp;quot;&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;
  &lt;span class=&#34;kwrd&#34;&gt;&amp;lt;&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;source&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;src&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;pathToMyMovie.ogg&amp;quot;&lt;/span&gt; &lt;span class=&#34;attr&#34;&gt;type&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;=&amp;quot;video/ogg&amp;quot;&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;
Your browser does not support the video tag.
&lt;span class=&#34;kwrd&#34;&gt;&amp;lt;/&lt;/span&gt;&lt;span class=&#34;html&#34;&gt;video&lt;/span&gt;&lt;span class=&#34;kwrd&#34;&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;

&lt;p&gt;
&lt;h4&gt;Supported Videoformats&lt;/h4&gt;
&lt;table class=&#34;gridtable&#34;&gt;
&lt;tbody&gt;&lt;tr&gt;
&lt;th style=&#34;width:25%&#34;&gt;Browser&lt;/th&gt;
&lt;th style=&#34;width:25%&#34;&gt;MP4&lt;/th&gt;
&lt;th style=&#34;width:25%&#34;&gt;WebM&lt;/th&gt;
&lt;th style=&#34;width:25%&#34;&gt;Ogg&lt;/th&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Internet Explorer&lt;/td&gt;
&lt;td&gt;YES&lt;/td&gt;
&lt;td&gt;NO&lt;/td&gt;
&lt;td&gt;NO&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Chrome&lt;/td&gt;
&lt;td&gt;YES&lt;/td&gt;
&lt;td&gt;YES&lt;/td&gt;
&lt;td&gt;YES&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Firefox&lt;/td&gt;
&lt;td&gt;YES&lt;/td&gt;
&lt;td&gt;YES&lt;/td&gt;
&lt;td&gt;YES&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Safari&lt;/td&gt;
&lt;td&gt;YES&lt;/td&gt;
&lt;td&gt;NO&lt;/td&gt;
&lt;td&gt;NO&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Opera&lt;/td&gt;
&lt;td&gt;NO&lt;/td&gt;
&lt;td&gt;YES&lt;/td&gt;
&lt;td&gt;YES&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;/p&gt;</content><category label="snippet" scheme="http://www.varunpant.com/topics/snippet/1" term="snippet"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category></entry><entry><title>Mod Proxy equivalent in IIS using ARR and URL Rewrite Module</title><link href="http://www.varunpant.com/posts/mod-proxy-equivalent-in-iis-using-arr-and-url-rewrite-module" rel="alternate" /><id>http://www.varunpant.com/posts/mod-proxy-equivalent-in-iis-using-arr-and-url-rewrite-module</id><published>2013-08-25T00:00:00z</published><updated>2013-08-25T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;IIS7 is quite modular, it is &lt;a href=&#34;http://blogs.iis.net/bills/archive/2008/06/02/how-iis-ships-software.aspx&#34; target=&#34;_blank&#34;&gt;shipped&lt;/a&gt; with lots of goodies as separate modules and together it is now one of the most powerful and flexible web server.&lt;/p&gt;  &lt;p&gt;In this post I intent to cover how we can easily configure &lt;a href=&#34;http://www.iis.net/downloads/microsoft/application-request-routing&#34; target=&#34;_blank&#34;&gt;ARR&lt;/a&gt; and &lt;a href=&#34;http://www.microsoft.com/en-gb/download/details.aspx?id=7435&#34; target=&#34;_blank&#34;&gt;URL Rewrite Module&lt;/a&gt; to get a similar functionality as of &lt;a href=&#34;http://httpd.apache.org/docs/2.2/mod/mod_proxy.html&#34; target=&#34;_blank&#34;&gt;Mod Proxy&lt;/a&gt; in Apache.&lt;/p&gt;  &lt;p&gt;Here I will demonstrate configuration of a reverse proxy which according to the &lt;a href=&#34;http://en.wikipedia.org/wiki/Reverse_proxy&#34; target=&#34;_blank&#34;&gt;definition&lt;/a&gt; is &lt;/p&gt;  &lt;blockquote cite=&#34;http://en.wikipedia.org/wiki/Reverse_proxy&#34;&gt;&lt;strong&gt;Reverse proxy&lt;/strong&gt; is a type of &lt;a href=&#34;http://en.wikipedia.org/wiki/Proxy_server&#34;&gt;proxy server&lt;/a&gt; that retrieves resources on behalf of a &lt;a href=&#34;http://en.wikipedia.org/wiki/Client_(computing)&#34;&gt;client&lt;/a&gt; from one or more &lt;a href=&#34;http://en.wikipedia.org/wiki/Server_(computing)&#34;&gt;servers&lt;/a&gt;. &lt;/blockquote&gt; A general use case to configure such proxies could be to handle cross domain Ajax requests, so basically if I would like to call a service hosted as &lt;code&gt;&lt;a href=&#34;http://anotherdomain.com/service&#34;&gt;http://anotherdomain.com/service&lt;/a&gt; &lt;/code&gt;from &lt;code&gt;&lt;a href=&#34;http://localdomain/service&#34;&gt;http://localdomain/service&lt;/a&gt; &lt;/code&gt;I would need to configure a proxy which will request resources from &lt;code&gt;anotherdomain.com/service&lt;/code&gt; on behalf of &lt;code&gt;localdomain&lt;/code&gt;   &lt;h3&gt;Configuration&lt;/h3&gt;  &lt;p&gt;&lt;b&gt;STEP 1:&lt;/b&gt; To set up a rule click on the web application from the sites tree on the left and then click on the URL Rewrite module, then form the command pallete on the right hand click on Add Rule as shown in image below.     &lt;br /&gt;&lt;a href=&#34;http://varunpant.com/static/resources/add_rule_18.png&#34;&gt;&lt;img title=&#34;add_rule&#34; border=&#34;0&#34; alt=&#34;add_rule&#34; src=&#34;http://varunpant.com/static/resources/add_rule_thumb_8.png&#34; width=&#34;146&#34; height=&#34;244&#34; /&gt;&lt;/a&gt;     &lt;br /&gt;&lt;b&gt;STEP 2:&lt;/b&gt; From the add rule dialog choose reverse proxy template     &lt;br /&gt;&lt;a href=&#34;http://varunpant.com/static/resources/reverse_proxy_template_12.png&#34;&gt;&lt;img title=&#34;reverse_proxy_template&#34;class=&#34;img-polaroid&#34; alt=&#34;reverse_proxy_template&#34; src=&#34;http://varunpant.com/static/resources/reverse_proxy_template_12.png&#34; width=&#34;80%&#34; height=&#34;90%&#34; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Configure Inbound Rules window and provide server name as shown in screen shot below&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_2.png&#34;&gt;&lt;img  class=&#34;img-polaroid&#34;  src=&#34;http://varunpant.com/static/resources/image_configureproxyurl.png&#34; width=&#34;80%&#34; height=&#34;90%&#34; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Finally configure the last form, this is where one can specify cache parameters and override server header variables, such as basic authentication (http_authorisation) etc.&lt;/p&gt;  &lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_4.png&#34;&gt;&lt;img alt=&#34;image&#34; class=&#34;img-polaroid&#34; src=&#34;http://varunpant.com/static/resources/last_page_proxy.png&#34; width=&#34;80%&#34; height=&#34;90%&#34;  /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;In the patterns text box entering something like &lt;code&gt;^/service(.*)&lt;/code&gt; will trap all requests going to &lt;code&gt;&lt;a href=&#34;http://localdomain/service&#34;&gt;http://localdomain/service&lt;/a&gt; &lt;/code&gt;and they will be proxyed as if the requests were made like &lt;code&gt;&lt;a href=&#34;http://anotherdomain.com/service&#34;&gt;http://anotherdomain.com/service&lt;/a&gt; &lt;/code&gt;, The query strings if present are also carried forward, all these settings and modification are preserved in &lt;code&gt;web.config&lt;/code&gt; of the web application, under &lt;code&gt;&lt;system.webserver&gt;tag&lt;/code&gt;. The rules after configuration look like &lt;/p&gt;
&lt;pre&gt;
&amp;lt;rewrite&amp;gt;
    &amp;lt;rules&amp;gt;
        &amp;lt;rule stopprocessing=&amp;quot;true&amp;quot; name=&amp;quot;ReverseProxyInboundRule1&amp;quot;&amp;gt;
            &amp;lt;match url=&amp;quot;^service/(.*)&amp;quot; /&amp;gt;
            &amp;lt;action url=&amp;quot;http://anotherdomain.com/service{R:1}&amp;quot; type=&amp;quot;Rewrite&amp;quot; /&amp;gt;
            &amp;lt;servervariables /&amp;gt;
        &amp;lt;/rule&amp;gt;
    &amp;lt;/rules&amp;gt;
&amp;lt;/rewrite&amp;gt;
&lt;/pre&gt;&lt;/p&gt;
	If desired server variables and cache params can also be included.

	&lt;p&gt;Apart form using the reverse proxy template one can directly use url re-write module and even import settings from apache . Read &lt;a href=&#34;http://www.iis.net/learn/extensions/url-rewrite-module/importing-apache-modrewrite-rules&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt; for more information.&lt;/p&gt;

&lt;p&gt;I hope you will find this post use full. Happy coding ;)&lt;/p&gt;</content><category label=".net" scheme="http://www.varunpant.com/topics/net/1" term=".net"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="iis" scheme="http://www.varunpant.com/topics/iis/1" term="iis"></category></entry><entry><title>Signing android release apk from the command line (via ant)</title><link href="http://www.varunpant.com/posts/signing-android-release-apk-from-the-command-line-via-ant" rel="alternate" /><id>http://www.varunpant.com/posts/signing-android-release-apk-from-the-command-line-via-ant</id><published>2013-08-25T00:00:00z</published><updated>2013-08-25T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;This post is probably out too late ,as almost all IDE&#39;s these days (which support android development) ,probably have an Integrated &lt;strong&gt;release signing&lt;/strong&gt; or &lt;strong&gt;debug signing&lt;/strong&gt; utility/wizard built in, but if somebody is using an old IDE or perhaps want to integrate release in a CI(continues integration) environment , this tutorial might come in handy.&lt;/p&gt;  &lt;p&gt;Basically one has to sign an apk either with a debug key (which is generally present in your .android folder) or a create a fresh application specific keystore , to know more go &lt;a href=&#34;http://developer.android.com/tools/publishing/app-signing.html&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Assuming you have setup android SDK properly in a Windows /Mac or Linux environment and all paths etc. are configured properly, lets begin by opening a command shell and navigating to the root of the android project,If the project is setup properly then a basic build command using ant &lt;code&gt;ant clean debug&lt;/code&gt; should trigger a build&lt;/p&gt;  &lt;p&gt;In order to sign an application we need to make a keystore that we use for the lifetime of this application. It&#39;s important to note that this keystore should be backed up in a secure place, losing it means you cannot install any updates on devices that have this app already installed. We are going to use the &amp;quot;keytool&amp;quot; program to create a keystore.&lt;/p&gt; &lt;code&gt;keytool -genkey -v -keystore release.keystore -alias mykey -keyalg RSA -keysize 2048 -validity 10000&lt;/code&gt;   &lt;p&gt;This command will invoke a console wizard which will eventually create a keystore in the &amp;quot;release.keystore&amp;quot; file in the local directory with a key in it called mykey that will have 2048 size to it as well as be valid for 10,000 days. I generally include this file in my project version control and keep it in the same level as my ant.properties file&lt;/p&gt;  &lt;p&gt;The next step is to modify your ant properties file and add these (I have store and alisa password same) &lt;code&gt;key.store=release.keystore key.alias=mykey key.store.password=secret key.alias.password=secret &lt;/code&gt;and thats it, finall step is to issue a command &lt;code&gt;ant clean release&lt;/code&gt;&lt;/p&gt;    &lt;p&gt;If everything was successful it will say &amp;quot;BUILD SUCCESSFUL&amp;quot; and put an apk named something like &amp;quot;MyProject-release.apk&amp;quot; in the &lt;code&gt;/bin&lt;/code&gt; directory.&lt;/p&gt;</content><category label="android" scheme="http://www.varunpant.com/topics/android/1" term="android"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category></entry><entry><title>Importing CSV File Into SQL SERVER  Database using BULK INSERT</title><link href="http://www.varunpant.com/posts/importing-csv-file-into-sql-server-database-using-bulk-insert" rel="alternate" /><id>http://www.varunpant.com/posts/importing-csv-file-into-sql-server-database-using-bulk-insert</id><published>2013-03-11T00:00:00z</published><updated>2013-03-11T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;
Importing data into a database from a delimited file is perhaps one of the most common tasks that one might have to perform. SQL server gives us an import utility which supports various data sources and has an intutive interface as well,however there is another way which can be utilized to quickly get the job done, its called &lt;a href=&#34;http://msdn.microsoft.com/en-us/library/aa225968(v=sql.80).aspx&#34; &gt;BULK INSERT&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
BULK INSERT is a SQL command which can be  typed in management console,takes various parameters to control the import and is very simple to use.
&lt;/p&gt;

&lt;p&gt;
A typical use would look like this:
&lt;pre class=&#34;prettyprint linunums lang-sql&#34;&gt;
GO
BULK INSERT &lt;myTargetTableName&gt; from &#39;C:\sourceFile.csv&#39; WITH
(
FIELDTERMINATOR =&#39;,&#39;,
ROWTERMINATOR =&#39;\n&#39;
)
&lt;/pre&gt;
and that&#39;s it, the command will automatically read csv file, try to do any default type conversion(determined by the TargetTables colum types) and will fail if there are any errors.
&lt;/p&gt;
&lt;p&gt;
There are many other properties which can be set to make import easy ti handle, the ones I typically use are
&lt;pre class=&#34;prettyprint linunums lang-sql&#34;&gt;
GO
BULK INSERT &lt;myTargetTableName&gt; from &#39;C:\sourceFile.csv&#39; WITH
(
FIELDTERMINATOR =&#39;,&#39;,
ROWTERMINATOR =&#39;\n&#39;,

CODEPAGE=&#39;RAW&#39;,--Helps in Determining the source/destination Encoding (UTF8 etc)
MaxErrors = 999999-- This will allow 999999 errors to be ignored before the whole import fails. This is a workaround as its not possible to tell the importer to ignore errors completely.
)
&lt;/pre&gt;

Here is a full syntax and supported properties, for their explanation, please visit  &lt; href=&#34;http://msdn.microsoft.com/en-us/library/aa225968(v=sql.80).aspx&#34; &gt;this &lt;/a&gt; page.

&lt;pre class=&#34;prettyprint linunums lang-sql&#34;&gt;

BULK INSERT [ [ &#39;database_name&#39;.] [ &#39;owner&#39; ].] { &#39;table_name&#39; FROM &#39;data_file&#39; }
    [ WITH
        (
            [ BATCHSIZE [ = batch_size ] ]
            [ [ , ] CHECK_CONSTRAINTS ]
            [ [ , ] CODEPAGE [ = &#39;ACP&#39; | &#39;OEM&#39; | &#39;RAW&#39; | &#39;code_page&#39; ] ]
            [ [ , ] DATAFILETYPE [ =
                { &#39;char&#39; | &#39;native&#39;| &#39;widechar&#39; | &#39;widenative&#39; } ] ]
            [ [ , ] FIELDTERMINATOR [ = &#39;field_terminator&#39; ] ]
            [ [ , ] FIRSTROW [ = first_row ] ]
            [ [ , ] FIRE_TRIGGERS ]
            [ [ , ] FORMATFILE = &#39;format_file_path&#39; ]
            [ [ , ] KEEPIDENTITY ]
            [ [ , ] KEEPNULLS ]
            [ [ , ] KILOBYTES_PER_BATCH [ = kilobytes_per_batch ] ]
            [ [ , ] LASTROW [ = last_row ] ]
            [ [ , ] MAXERRORS [ = max_errors ] ]
            [ [ , ] ORDER ( { column [ ASC | DESC ] } [ ,...n ] ) ]
            [ [ , ] ROWS_PER_BATCH [ = rows_per_batch ] ]
            [ [ , ] ROWTERMINATOR [ = &#39;row_terminator&#39; ] ]
            [ [ , ] TABLOCK ]
        )
    ]

&lt;/pre&gt;
&lt;em&gt; Arguments &#39;database_name&#39; &lt;/em&gt;
&lt;/p&gt;</content><category label="sqlserver" scheme="http://www.varunpant.com/topics/sqlserver/1" term="sqlserver"></category><category label="database" scheme="http://www.varunpant.com/topics/database/1" term="database"></category><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category></entry><entry><title>Importing Exporting CSV Files in PostgreSQL Databases via COPY</title><link href="http://www.varunpant.com/posts/importing-exporting-csv-files-in-postgresql-databases-via-copy" rel="alternate" /><id>http://www.varunpant.com/posts/importing-exporting-csv-files-in-postgresql-databases-via-copy</id><published>2013-03-11T00:00:00z</published><updated>2013-03-11T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;This is going to be a short article which will illustrate importing and exporting a table from or to a csv file using PostgreSQL&amp;#160; &lt;a href=&#34;http://www.postgresql.org/docs/9.1/static/sql-copy.html&#34; target=&#34;_blank&#34;&gt;COPY&lt;/a&gt; command.&lt;/p&gt;  &lt;h4&gt;Importing a table from CSV&lt;/h4&gt;  &lt;p&gt;Assuming you already have a table in place with the right columns, the command is as follows&lt;/p&gt;  &lt;p&gt;&lt;code&gt;COPY &amp;lt;TargetTableName&amp;gt; &lt;strong&gt;FROM&lt;/strong&gt; &#39;/path/to/csv/SourceCSVFile.csv&#39;&amp;#160; DELIMITERS&amp;#160; &#39;&lt;strong&gt;,&lt;/strong&gt;&#39;&amp;#160; CSV;&lt;/code&gt;&lt;/p&gt;  &lt;h4&gt;Exporting a CSV from a table.&lt;/h4&gt;  &lt;p&gt;&lt;code&gt;COPY &amp;lt;SourceTableName&amp;gt; &lt;strong&gt;TO&lt;/strong&gt; &#39;/path/to/csv/TargetCSVFile&#39; DELIMITERS &#39;&lt;strong&gt;,&lt;/strong&gt;&#39; CSV;&lt;/code&gt;&lt;/p&gt;  &lt;p&gt;Its important to mention here that generally if your data is in unicode or need strict Encoding, then Always set client_encoding before running any of the above mentioned commands.&lt;/p&gt;  &lt;h4&gt;To set CLIENT_ENCODING parameter in PostgreSQL&lt;/h4&gt;  &lt;p&gt;&lt;code&gt;set client_encoding to &lt;strong&gt;&#39;UTF8&#39;&lt;/strong&gt;&lt;/code&gt;&lt;/p&gt; or   &lt;p&gt;&lt;code&gt;set client_encoding to &lt;strong&gt;&#39;latin1&#39;&lt;/strong&gt;&lt;/code&gt;&lt;/p&gt;  &lt;p&gt;Another thing to guard against is nulls, while exporting , if some fields are null then PostgreSQL will add &lt;strong&gt;&#39;/N&#39;&lt;/strong&gt; to represent a null field, this is fine but may cause issues if you are trying to import that data in say SQL server.&lt;/p&gt;  &lt;p&gt;A quick fix is modify the export command by specifying what would you prefer as a null placeholder in exported CSV&lt;/p&gt;  &lt;p&gt;&lt;code&gt;COPY &amp;lt;SourceTableName&amp;gt; TO &#39;/path/to/csv/TargetCSVFile&#39; DELIMITERS &#39;,&#39; &lt;strong&gt;NULL as E&#39;&#39;&lt;/strong&gt;;&lt;/code&gt;&lt;/p&gt;  &lt;p&gt;Another common requirement is import or export with the header.&lt;/p&gt;  &lt;h4&gt;Import CSV to table with Header for columns present in first row of csv file.&lt;/h4&gt;  &lt;p&gt;&lt;code&gt;COPY &amp;lt;TargetTableName&amp;gt; &lt;strong&gt;FROM&lt;/strong&gt; &#39;/path/to/csv/SourceCSVFile.csv&#39; DELIMITERS &#39;,&#39; CSV &lt;strong&gt;HEADER&lt;/strong&gt;&lt;/code&gt;&lt;/p&gt;  &lt;h4&gt;Export a table to CSV with Headers present in the first row.&lt;/h4&gt;  &lt;p&gt;&lt;code&gt;COPY &amp;lt;SourceTableName&amp;gt; &lt;strong&gt;TO&lt;/strong&gt; &#39;/path/to/csv/TargetCSVFile&#39; DELIMITERS &#39;,&#39; CSV &lt;strong&gt;HEADER&lt;/strong&gt;;&lt;/code&gt;&lt;/p&gt;  &lt;p&gt;A complete list of all supported settings can be found &lt;a href=&#34;http://www.postgresql.org/docs/9.1/static/sql-copy.html&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;&lt;/p&gt;  &lt;pre class=&#34;prettyprint linenums lang-sql&#34;&gt;COPY &lt;tt&gt;table_name&lt;/tt&gt; [ ( &lt;tt&gt;column&lt;/tt&gt; [, ...] ) ]
    FROM { &#39;&lt;tt&gt;filename&lt;/tt&gt;&#39; | STDIN }
    [ [ WITH ] ( &lt;tt&gt;option&lt;/tt&gt; [, ...] ) ]

COPY { &lt;tt&gt;table_name&lt;/tt&gt; [ ( &lt;tt&gt;column&lt;/tt&gt; [, ...] ) ] | ( &lt;tt&gt;query&lt;/tt&gt; ) }
    TO { &#39;&lt;tt&gt;filename&lt;/tt&gt;&#39; | STDOUT }
    [ [ WITH ] ( &lt;tt&gt;option&lt;/tt&gt; [, ...] ) ]

where &lt;tt&gt;option&lt;/tt&gt; can be one of:

    FORMAT &lt;tt&gt;format_name&lt;/tt&gt;
    OIDS [ &lt;tt&gt;boolean&lt;/tt&gt; ]
    DELIMITER &#39;&lt;tt&gt;delimiter_character&lt;/tt&gt;&#39;
    NULL &#39;&lt;tt&gt;null_string&lt;/tt&gt;&#39;
    HEADER [ &lt;tt&gt;boolean&lt;/tt&gt; ]
    QUOTE &#39;&lt;tt&gt;quote_character&lt;/tt&gt;&#39;
    ESCAPE &#39;&lt;tt&gt;escape_character&lt;/tt&gt;&#39;
    FORCE_QUOTE { ( &lt;tt&gt;column&lt;/tt&gt; [, ...] ) | * }
    FORCE_NOT_NULL ( &lt;tt&gt;column&lt;/tt&gt; [, ...] ) |
    ENCODING &#39;&lt;tt&gt;encoding_name&lt;/tt&gt;&#39;&lt;/pre&gt;</content><category label="database" scheme="http://www.varunpant.com/topics/database/1" term="database"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="postgres" scheme="http://www.varunpant.com/topics/postgres/1" term="postgres"></category></entry><entry><title>Raphael JS Tutorial - Part I</title><link href="http://www.varunpant.com/posts/raphael-js-tutorial-part-i" rel="alternate" /><id>http://www.varunpant.com/posts/raphael-js-tutorial-part-i</id><published>2013-03-10T00:00:00z</published><updated>2013-03-10T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;a href=&#34;http://raphaeljs.com/&#34; target=&#34;_blank&#34;&gt;Raphael.JS&lt;/a&gt; is a SVG/VML library which helps you to create quick vector shapes and images. Its very small and compact (only 86kb),easy to use,well documented and works in all browsers and yes even IE. Here is a list of all major browsers this library works on:&lt;p&gt; &lt;a href=&#34;http://en.wikipedia.org/wiki/Chrome_browser&#34;&gt;Chrome&lt;/a&gt; 5.0+ &lt;a href=&#34;http://en.wikipedia.org/wiki/Firefox&#34;&gt;Firefox&lt;/a&gt; 3.0+, &lt;a href=&#34;http://en.wikipedia.org/wiki/Safari_(web_browser)&#34;&gt;Safari&lt;/a&gt; 3.0+, &lt;a href=&#34;http://en.wikipedia.org/wiki/Opera_(web_browser)&#34;&gt;Opera&lt;/a&gt; 9.5+ and &lt;a href=&#34;http://en.wikipedia.org/wiki/Internet_Explorer&#34;&gt;Internet Explorer&lt;/a&gt; 6.0+&lt;/p&gt;,finally its distributed under &lt;a href=&#34;http://raphaeljs.com/license.html&#34; target=&#34;_blank&#34;&gt;MIT license&lt;/a&gt;.   &lt;p&gt;In this tutorial ,I intend to introduce basics of this library and help you get started. &lt;/p&gt;  &lt;p&gt;Lets begin with some basic concepts. &lt;a href=&#34;http://raphaeljs.com/&#34; target=&#34;_blank&#34;&gt;Raphael.JS&lt;/a&gt; uses the &lt;abbr&gt;SVG&lt;/abbr&gt; &lt;abbr&gt;W3C&lt;/abbr&gt; Recommendation and &lt;abbr&gt;VML&lt;/abbr&gt; as a base for creating graphics, it hides quite a lot of technology specific nitty-gritties and instead present a unified api model . Here is a quick code sample&lt;/p&gt;  &lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
// Creates canvas 250 × 250 at 0, 0
&lt;b&gt;var&lt;/b&gt; canvas = Raphael(0, 0, 250, 250 );
// Creates circle at x = 125, y = 125, with radius 50
&lt;b&gt;var&lt;/b&gt; circle = canvas .circle(125, 125, 50);
// Sets the fill attribute of the circle to red (#f00)
circle.attr(&lt;i&gt;&amp;quot;fill&amp;quot;&lt;/i&gt;, &lt;i&gt;&amp;quot;#f00&amp;quot;&lt;/i&gt;);
// Sets the stroke attribute of the circle to white
circle.attr(&lt;i&gt;&amp;quot;stroke&amp;quot;&lt;/i&gt;, &lt;i&gt;&amp;quot;#fff&amp;quot;&lt;/i&gt;);&lt;/code&gt;&lt;/pre&gt;
&lt;iframe style=&#34;width: 250px; height: 250px&#34; class=&#34;well&#34; src=&#34;http://www.varunpant.com/static/resources/Raphael.JS%20Tutorial/sample1.html&#34;&gt;&lt;/iframe&gt;

&lt;p&gt;The above code will create a circle in a middle of a canvas, here a canvas represent an HTML &lt;code&gt;canvas&lt;/code&gt; element which is used as a drawing board with an id &lt;code&gt;canvas&lt;/code&gt;. There is another way of binding your desired area with &lt;a href=&#34;http://raphaeljs.com/&#34; target=&#34;_blank&#34;&gt;Raphael&lt;/a&gt; and that is by simply passing in the container element itself by using plain old &lt;code&gt;document.getElementById(&amp;quot;element&amp;quot;).&lt;/code&gt; &lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
var canvas = new Raphael(x, y, width, height); //first option
var canvas = new Raphael(document.getElementById(&#39;element&#39;), width, height); //second option&amp;#160; &lt;/pre&gt;

&lt;p&gt;&lt;a href=&#34;http://raphaeljs.com/reference.html#Paper.circle&#34; target=&#34;_blank&#34;&gt;Circle&lt;/a&gt; is one of the shape which can be drawn by using Raphael, others included in the&amp;#160; library are &lt;a href=&#34;http://raphaeljs.com/reference.html#Paper.ellipse&#34; target=&#34;_blank&#34;&gt;ellipse&lt;/a&gt;,&lt;a href=&#34;http://raphaeljs.com/reference.html#Paper.rect&#34; target=&#34;_blank&#34;&gt;rect&lt;/a&gt; ,&lt;a href=&#34;http://raphaeljs.com/reference.html#Paper.path&#34; target=&#34;_blank&#34;&gt;path&lt;/a&gt; and finally &lt;a href=&#34;http://raphaeljs.com/reference.html#Paper.image&#34; target=&#34;_blank&#34;&gt;image&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here is a quick sample of drawing circle,ellipse and rectangle&lt;/p&gt;
&lt;iframe style=&#34;width: 250px; height: 250px&#34; class=&#34;well&#34; src=&#34;http://www.varunpant.com/static/resources/Raphael.JS%20Tutorial/sample2.html&#34;&gt;&lt;/iframe&gt;

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
// Creates canvas 250 × 250 at 0, 0
canvas = Raphael(0, 0, 250, 250 );
// Creates circle at x = 125, y = 125, with radius 50
var circle = canvas.circle(125, 125, 50);// Sets the fill attribute of the circle to red (#f00)
circle.attr(&amp;quot;fill&amp;quot;, &amp;quot;blue&amp;quot;);
// Sets the stroke attribute of the circle to white
circle.attr(&amp;quot;stroke&amp;quot;, &amp;quot;#fff&amp;quot;);
// Creates rectangle at x = 5, y = 5, with width and height = 50
var rectangle = canvas.rect(5, 5, 50, 50);
rectangle.attr(&amp;quot;fill&amp;quot;, &amp;quot;green&amp;quot;);
// Creates ellipse at x and y = 180 ,horizontal-axis = 20 and vertical-axis = 30
var ellipse = canvas.ellipse(180, 180, 20, 30);
ellipse.attr(&amp;quot;fill&amp;quot;, &amp;quot;red&amp;quot;); &lt;/pre&gt;

&lt;p&gt;Even though above mentioned are the most basic shapes which one might need, however it&#39;s the path element which actually gives us a true flexibility&lt;/p&gt;

&lt;p&gt;We start a path by calling canvas.path(&amp;quot;&amp;lt;instructions&amp;quot;) method, where instructions are a sequence of directions we can give a path element along with the coordinates. The list of instructions can be found &lt;a href=&#34;http://raphaeljs.com/reference.html#Paper.path&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;
  &lt;table class=&#34;gridtable&#34;&gt;&lt;thead&gt;
      &lt;tr&gt;
        &lt;th&gt;Command&lt;/th&gt;

        &lt;th&gt;Name&lt;/th&gt;

        &lt;th&gt;Parameters&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;&lt;tbody&gt;
      &lt;tr&gt;
        &lt;td&gt;M&lt;/td&gt;

        &lt;td&gt;moveto&lt;/td&gt;

        &lt;td&gt;(x y)+&lt;/td&gt;
      &lt;/tr&gt;

      &lt;tr&gt;
        &lt;td&gt;Z&lt;/td&gt;

        &lt;td&gt;closepath&lt;/td&gt;

        &lt;td&gt;(none)&lt;/td&gt;
      &lt;/tr&gt;

      &lt;tr&gt;
        &lt;td&gt;L&lt;/td&gt;

        &lt;td&gt;lineto&lt;/td&gt;

        &lt;td&gt;(x y)+&lt;/td&gt;
      &lt;/tr&gt;

      &lt;tr&gt;
        &lt;td&gt;H&lt;/td&gt;

        &lt;td&gt;horizontal lineto&lt;/td&gt;

        &lt;td&gt;x+&lt;/td&gt;
      &lt;/tr&gt;

      &lt;tr&gt;
        &lt;td&gt;V&lt;/td&gt;

        &lt;td&gt;vertical lineto&lt;/td&gt;

        &lt;td&gt;y+&lt;/td&gt;
      &lt;/tr&gt;

      &lt;tr&gt;
        &lt;td&gt;C&lt;/td&gt;

        &lt;td&gt;curveto&lt;/td&gt;

        &lt;td&gt;(x1 y1 x2 y2 x y)+&lt;/td&gt;
      &lt;/tr&gt;

      &lt;tr&gt;
        &lt;td&gt;S&lt;/td&gt;

        &lt;td&gt;smooth curveto&lt;/td&gt;

        &lt;td&gt;(x2 y2 x y)+&lt;/td&gt;
      &lt;/tr&gt;

      &lt;tr&gt;
        &lt;td&gt;Q&lt;/td&gt;

        &lt;td&gt;quadratic Bézier curveto&lt;/td&gt;

        &lt;td&gt;(x1 y1 x y)+&lt;/td&gt;
      &lt;/tr&gt;

      &lt;tr&gt;
        &lt;td&gt;T&lt;/td&gt;

        &lt;td&gt;smooth quadratic Bézier curveto&lt;/td&gt;

        &lt;td&gt;(x y)+&lt;/td&gt;
      &lt;/tr&gt;

      &lt;tr&gt;
        &lt;td&gt;A&lt;/td&gt;

        &lt;td&gt;elliptical arc&lt;/td&gt;

        &lt;td&gt;(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+&lt;/td&gt;
      &lt;/tr&gt;

      &lt;tr&gt;
        &lt;td&gt;R&lt;/td&gt;

        &lt;td&gt;&lt;a href=&#34;http://en.wikipedia.org/wiki/Catmull&amp;ndash;Rom_spline#Catmull.E2.80.93Rom_spline&#34;&gt;Catmull-Rom curveto&lt;/a&gt;*&lt;/td&gt;

        &lt;td&gt;x1 y1 (x y)+&lt;/td&gt;
      &lt;/tr&gt;
    &lt;/tbody&gt;&lt;/table&gt;
&lt;/p&gt;

&lt;p&gt;Here a simple diagonal line is created using path&lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
// Creates canvas 250 × 250 at 0, 0
canvas = Raphael(0, 0, 250, 250 );
// draw a diagonal line:
// move to 10,10, line to 90,90
var path = canvas.path(&amp;quot;M10 10 L 190 190&amp;quot;);
// Sets the stroke attribute of the path to red
path.attr(&amp;quot;stroke&amp;quot;, &amp;quot;red&amp;quot;);
// Sets the stroke-width attribute of the path to 3.
path.attr(&amp;quot;stroke-width&amp;quot;, &amp;quot;3&amp;quot;);&lt;/pre&gt;

&lt;p&gt;Path is extremly versatile and one could create other known shapes by using it. A simple circle can be created by using path for example&lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
// Creates canvas 250 × 250 at 0, 0
canvas = Raphael(0, 0, 250, 250 );
// Creates circle shape using path at x = 125, y = 125, with radius 50
var circleDrawnasPath = canvas.path(getCircletoPath(125, 125, 50));
circleDrawnasPath.attr(&amp;quot;stroke&amp;quot;, &amp;quot;green&amp;quot;);
circleDrawnasPath.attr(&amp;quot;stroke-width&amp;quot;, &amp;quot;3&amp;quot;);

//Helper method to take x,y and r and return a path instruction string.
// x and y are center and r is the radius
function getCircletoPath(x , y, r)  {  return &amp;quot;M&amp;quot;+ x + &amp;quot;,&amp;quot; + (y - r) + &amp;quot;A&amp;quot; + r + &amp;quot;,&amp;quot; + r + &amp;quot;,0,1,1,&amp;quot; + (x - 0.1) + &amp;quot;,&amp;quot; + (y - r) +&amp;quot; z&amp;quot;; }&lt;/pre&gt;
&lt;iframe style=&#34;width: 250px; height: 250px&#34; class=&#34;well&#34; src=&#34;http://www.varunpant.com/static/resources/Raphael.JS%20Tutorial/sample3.html&#34;&gt;&lt;/iframe&gt;

&lt;p&gt;Paths can be used to create other intesting controls as well&lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
			var canvas;
			window.onload = function () {
				// Creates canvas 250 × 300 at 0, 0
				canvas = Raphael(0, 0, 250, 270 );
				DrawBars(
				{
					&amp;quot;56%&amp;quot;:56,
					&amp;quot;28%&amp;quot;:28,
					&amp;quot;15%&amp;quot;:15,
					&amp;quot;01%&amp;quot;:1,
				} );
			};
			var DrawBars = function(data)
			{
				var vals = [];
				var labels = [];
				for(var key in data)
				{
					labels.push(key);
					vals.push(Number(data[key]));
				}
				var startingY = 55;
				var totalHeight = 60;
				var verticalGap = 8;
				var Height1 = Math.round(vals[0]/100*totalHeight);
				var Height2 = Math.round(vals[1]/100*totalHeight);
				var Height3 = Math.round(vals[2]/100*totalHeight);
				var Height4 = Math.round(vals[3]/100*totalHeight);

				//Cube 4
				drawCube((startingY + Height1 + Height2 + Height3 + (verticalGap*3)),Height4,canvas,&amp;quot;#BBE6FB&amp;quot;,&amp;quot;#89D7f8&amp;quot;,&amp;quot;#39C8F4&amp;quot;,labels[3]);
				//Cube 3
				drawCube((startingY + Height1 + Height2 + (verticalGap*2)),Height3,canvas,&amp;quot;#3FC8F4&amp;quot;,&amp;quot;#0CB5EB&amp;quot;,&amp;quot;#0094DA&amp;quot;,labels[2]);
				//Cube 2
				drawCube((startingY + Height1 + (verticalGap*1)),Height2,canvas,&amp;quot;#2A80B8&amp;quot;,&amp;quot;#0269A6&amp;quot;,&amp;quot;#003F84&amp;quot;,&amp;quot;28% Android&amp;quot;,labels[1]);
				//Cube 1
				drawCube(startingY,Height1,canvas,&amp;quot;#7F8184&amp;quot;,&amp;quot;#575759&amp;quot;,&amp;quot;#221E1F&amp;quot;,labels[0]);

			}

			var drawCube = function(y,height,canvas,f1,f2,f3,label)
			{
				var rect1 = canvas.path(&amp;quot;M 0 &amp;quot; + y + &amp;quot; 57 &amp;quot; + (y + 22) +&amp;quot; 188 &amp;quot; + y +&amp;quot; 127 &amp;quot; + (y - 16) + &amp;quot; 0 &amp;quot; + y);
				rect1.attr({fill: f1, stroke: f1, &#39;stroke-width&#39;: 0});

				var rect2 = canvas.path(&amp;quot;M 0 &amp;quot; + y + &amp;quot; 0 &amp;quot; +(y + height) +&amp;quot; 57 &amp;quot; + (y + height + 22) + &amp;quot; 57 &amp;quot; + (y + 22) + &amp;quot; 0 &amp;quot; + y);
				rect2.attr({fill: f2, stroke: f2, &#39;stroke-width&#39;: 0});

				var rect3 = canvas.path(&amp;quot;M 57 &amp;quot; + (y + 22) +&amp;quot; 57 &amp;quot; + (y + height + 22) +&amp;quot; 188 &amp;quot; + (y + height)+&amp;quot; 188 &amp;quot; + y +&amp;quot; 57 &amp;quot; + (y + 22));
				rect3.attr({fill: f3, stroke: f3, &#39;stroke-width&#39;: 0});
				var labely = y+height/2;
				var label1 = canvas.path(&amp;quot;M 188 &amp;quot; + labely + &amp;quot; 226 &amp;quot; + labely)
				label1.attr({stroke: &amp;quot;#fff&amp;quot;, &#39;stroke-width&#39;: 1});
				var text = canvas.text(226, labely, label);
				text.attr({&amp;quot;text-anchor&amp;quot;:&amp;quot;start&amp;quot;,&#39;font-size&#39;:12,&amp;quot;font-family&amp;quot;:&amp;quot;arial&amp;quot;,&amp;quot;fill&amp;quot;:&amp;quot;#fff&amp;quot;});


			}&lt;/pre&gt;
&lt;iframe style=&#34;width:270px; height: 250px&#34; class=&#34;well&#34; src=&#34;http://www.varunpant.com/static/resources/Raphael.JS%20Tutorial/sample4.html&#34;&gt;&lt;/iframe&gt;

&lt;p&gt;Rapael.js is a very versatile library, it suports many other feature like drawing images , text and animation. I intend to cover all that in future posts. Hope this helps. &lt;/p&gt;</content><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="html5" scheme="http://www.varunpant.com/topics/html5/1" term="html5"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="javascript" scheme="http://www.varunpant.com/topics/javascript/1" term="javascript"></category><category label="raphael js" scheme="http://www.varunpant.com/topics/raphael-js/1" term="raphael js"></category></entry><entry><title>How to configure Apache mod_wsgi</title><link href="http://www.varunpant.com/posts/how-to-configure-apache-mod_wsgi" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-configure-apache-mod_wsgi</id><published>2013-02-26T00:00:00z</published><updated>2013-02-26T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;I am a big fan and user of python. one of the most popular ways to create quick web app in python is via using mod wsgi.&lt;/p&gt;  &lt;p&gt;The aim of mod_wsgi is to implement a simple to use &lt;a href=&#34;http://httpd.apache.org/&#34;&gt;Apache&lt;/a&gt; module which can host any &lt;a href=&#34;http://www.python.org/&#34;&gt;Python&lt;/a&gt; application which supports the Python &lt;a href=&#34;http://www.wsgi.org/&#34;&gt;WSGI&lt;/a&gt; interface. &lt;/p&gt;  &lt;p&gt;The module would be suitable for use in hosting high performance production web sites, as well as your average self managed personal sites running on web hosting services.&lt;/p&gt;  &lt;p&gt;There are many frameworks in python, I like &lt;a href=&#34;http://webpy.org/&#34;&gt;web.py&lt;/a&gt; so here is&amp;#160; a quick example.&lt;/p&gt;  &lt;p&gt;First lets configure modwsgi in Ubuntu &lt;/p&gt;

&lt;p&gt;&lt;code&gt;sudo apt-get install libapache2-mod-wsgi&lt;/code&gt;&lt;/p&gt;
&lt;p&gt; &lt;code&gt;sudo a2enmod wsgi&lt;/code&gt;&lt;/p&gt;
 &lt;p&gt;&lt;code&gt;sudo service apache2 restart&lt;/code&gt;&lt;/p&gt;

 &lt;h5&gt;configuration in /etc/apache2/sites-available/defaults&lt;/h5&gt;  &lt;pre class=&#34;prettyprint linenums lang-python&#34;&gt;  WSGIScriptAlias /appname /var/www/webpy-app/code.py/

  Alias /appname/static /var/www/webpy-app/static/
  AddType text/html .py

  &amp;lt;Directory /var/www/webpy-app/&amp;gt;
      Order deny,allow
      Allow from all
  &amp;lt;/Directory&amp;gt; &lt;/pre&gt;
&lt;p&gt;
  There is generally a handler present in most web applications for wsgi calls, here is one from web.py
&lt;/p&gt;
&lt;pre class=&#34;prettyprint linenums lang-python&#34;&gt; import web

  urls = (
      &#39;/.*&#39;, &#39;hello&#39;,
      )

  class hello:
      def GET(self):
          return &amp;quot;Hello, world.&amp;quot;

  application = web.application(urls, globals()).wsgifunc() &lt;/pre&gt;


&lt;p&gt;
 and that&#39;s it.Hope it helps &lt;/p&gt;</content><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category></entry><entry><title>Serve the contents of any directory with Python&#39;s SimpleHTTPServer</title><link href="http://www.varunpant.com/posts/serve-the-contents-of-any-directory-with-python-s-simplehttpserver" rel="alternate" /><id>http://www.varunpant.com/posts/serve-the-contents-of-any-directory-with-python-s-simplehttpserver</id><published>2013-02-08T00:00:00z</published><updated>2013-02-08T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;Generally, when I am in&amp;#160; a middle of prototyping a concept or in a need of quickly executing Ajax requests or using browser features which would&amp;#160; need the page to be hosted on a web server, I use Python&#39;s &lt;a href=&#34;http://docs.python.org/2/library/simplehttpserver.html&#34; target=&#34;_blank&#34;&gt;SimpleHTTPServer&lt;/a&gt; module.&lt;/p&gt;  &lt;p&gt;Python&#39;s SimpleHTTPServer is a great way of serve the contents of the current directory,all one needs to do is change directory and execute a command which will expose all contents as if they were hosted in a web page. &lt;/p&gt;  &lt;pre class=&#34;prettyprint linenums lang=python&#34;&gt;cd myfolder
python -m SimpleHTTPServer &lt;port&gt; &lt;/pre&gt;

&lt;p&gt;you don&#39;t need a line of code or a even a python file anywhere inside the directory for this to work, the module works all on its own and just needs a &lt;strong&gt;port number&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;If there is a file called index.html inside the root, then its served when the user types &lt;code&gt;localhost:port.&lt;/code&gt; &lt;/p&gt;

&lt;p&gt;SimpleHTTPServer is a great module for quick start, however its not a production ready tool and must be used only for lightweight use.&lt;/p&gt;

&lt;p&gt;Another use of this module is a quick utility Proxy. This does need a few lines of code though :!&lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang=python&#34;&gt;import SocketServer
import SimpleHTTPServer
import urllib

PORT = 3333

class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.copyfile(urllib.urlopen(self.path), self.wfile)

httpd = SocketServer.ForkingTCPServer((&#39;&#39;, PORT), Proxy)
print &amp;quot;serving at port&amp;quot;, PORT
httpd.serve_forever()&lt;/pre&gt;

&lt;p&gt;Hope it helps.&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category></entry><entry><title>Avoid  console errors in browsers that lack a console</title><link href="http://www.varunpant.com/posts/avoid-console-errors-in-browsers-that-lack-a-console" rel="alternate" /><id>http://www.varunpant.com/posts/avoid-console-errors-in-browsers-that-lack-a-console</id><published>2013-01-30T00:00:00z</published><updated>2013-01-30T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;I love JavaScript and code a lot in it .Since I code, I also encounter problems and bugs from time to time and therefore need a Debugger and a debug mechanism to view whats going on.&lt;/p&gt;  &lt;p&gt;In good old days when I learned this language, I used JavaScript&#39;s inbuilt alert mechanism to view the value of a variable or a property of an object. This was a terrible mechanism, calling alert was blocking, one had to press OK to continue and if you had to take a look inside an array then well it was emotionally an overwhelming task is all I would say here.&lt;/p&gt;  &lt;p&gt;There were of course workarounds and techniques(like printing in a text area) but I guess people soon realized the need of console like mechanism which is present in other languages.&lt;/p&gt;  &lt;p&gt;I had my first encounter with console in FF and right there I had a Nerdgasm. It was nice , easy to use and simply put beautiful, and then chrome came in and did it even better. Today id you print an xml object then good capable consoles will actually pretty print the markup and objects will be printed in a tree structure thus a JavaScript programmer can breathe easy, well almost.... we still have IE to haunt us for ever.&lt;/p&gt;  &lt;p&gt;IE will as always screw with your happiness and will find a way to make you do something extra and different . To enable console in IE, Click the &amp;quot;Script&amp;quot; tab, then click &amp;quot;Console&amp;quot; on the right, however your JavaScript will throw error if you simply use console.log without enabling it, which we can safely assume our users will not.&lt;/p&gt;  &lt;p&gt;Here is a workaround&lt;/p&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt; HTML5 Boilerplate guys present us with this technique&lt;/p&gt;  &lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
(function() {
    var method;
    var noop = function () {};
    var methods = [
        &#39;assert&#39;, &#39;clear&#39;, &#39;count&#39;, &#39;debug&#39;, &#39;dir&#39;, &#39;dirxml&#39;, &#39;error&#39;,
        &#39;exception&#39;, &#39;group&#39;, &#39;groupCollapsed&#39;, &#39;groupEnd&#39;, &#39;info&#39;, &#39;log&#39;,
        &#39;markTimeline&#39;, &#39;profile&#39;, &#39;profileEnd&#39;, &#39;table&#39;, &#39;time&#39;, &#39;timeEnd&#39;,
        &#39;timeStamp&#39;, &#39;trace&#39;, &#39;warn&#39;
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());
&lt;/pre&gt;



&lt;p&gt;my personal fav is this&lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
var log = function (text) {
    // if (!window.console) window.console = {};
    // if (!window.console.log) window.console.log = function () { };
    &#34;use strict&#34;;

    if (typeof (console) !== &#34;undefined&#34; &amp;&amp; console.log !== undefined) {
        try {
            console.log.apply(console, arguments);
        } catch (e) {
            var log = Function.prototype.bind.call(console.log, console);
            log.apply(console, arguments);
        }
    }
}
&lt;/pre&gt;

&lt;p&gt;use which ever you prefer. Hope this helps.&lt;/p&gt;</content><category label="javascript" scheme="http://www.varunpant.com/topics/javascript/1" term="javascript"></category><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category></entry><entry><title>sqlite3 Bulk Import CSV from command line</title><link href="http://www.varunpant.com/posts/sqlite3-bulk-import-csv-from-command-line" rel="alternate" /><id>http://www.varunpant.com/posts/sqlite3-bulk-import-csv-from-command-line</id><published>2013-01-29T00:00:00z</published><updated>2013-01-29T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;I absolutely love &lt;a href=&#34;http://www.sqlite.org/&#34; target=&#34;_blank&#34;&gt;SQLite&lt;/a&gt;, be it windows, linux or mac, this light weight database never stops to amaze me.&lt;/p&gt;

&lt;p&gt;Few days ago I wanted to import a chunk of CSV data, which was 4 GB in size into a table in SQLite.&lt;/p&gt;

&lt;p&gt;I generally use Firefox &#39;s &lt;a href=&#34;https://addons.mozilla.org/en-us/firefox/addon/sqlite-manager/&#34; target=&#34;_blank&#34;&gt;sqlite-manager&lt;/a&gt; plug-in for usual tasks with SQLite database ,hence decided to use the import interface .&lt;/p&gt;

&lt;p&gt;I have had a very good experience with this GUI tool and it has rarely failed me, but this time I was disappointed. &lt;/p&gt;

&lt;p&gt;The import process started normally, but my RAM started increasing rapidly till it was 60% and after 20 minutes I was presented with some kind of a stack overflow/out of memory exception,luckily SQLite website is also one of the best documented ones, a quick search brought me to the command line utility &lt;a href=&#34;http://www.sqlite.org/sqlite.html&#34; target=&#34;_blank&#34;&gt;page&lt;/a&gt;, which has a &lt;code&gt;.import &lt;/code&gt;command which I was looking for.&lt;/p&gt;

&lt;p&gt;Before importing a CSV, you may want to have a well defined database structure,although this is not compulsory but I would highly recommend that you do that, once done then simply open the SQLite shell by typing &lt;strong&gt;sqlite3&lt;/strong&gt; followed by the &lt;strong&gt;database&lt;/strong&gt; file name, if you are in windows then you can download the command line utility packaged as an exe and open that via shell by typing in &lt;code&gt;sqlite3 &amp;lt;filename&amp;gt;&lt;/code&gt; , the default separator is &#39;&lt;strong&gt;,&lt;/strong&gt;&#39; , to change use .separator command in shell &lt;code&gt;sqlite&amp;gt; .separator &#39;&lt;strong&gt;|&lt;/strong&gt;&#39; &lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The next step is to let the utility know that you intend to use a CSV, by typing in &lt;code&gt;sqlite&amp;gt; .mode csv&lt;/code&gt; and finally the import command &lt;/p&gt;
&lt;code&gt;sqlite&amp;gt; .import &amp;lt;filename&amp;gt; &amp;lt;tablename&amp;gt;&lt;/code&gt;

&lt;p&gt;That should do it, there are more commands to configure the delimiter and the escape characters which can be found &lt;a href=&#34;http://www.sqlite.org/sqlite.html&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;The entire import of 28122486 was&amp;#160; finished in less than 6 minutes and surprisingly the SQLite file database took less space than the original CSV, the original file was 4.2 GB where as the SQLite file database file was only 3.13 GB, that&#39;s a whopping gig difference.&lt;/p&gt;

&lt;p&gt;I hope you find this useful and use SQLite more than you already do.&lt;/p&gt;</content><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category><category label="database" scheme="http://www.varunpant.com/topics/database/1" term="database"></category><category label="sqlite" scheme="http://www.varunpant.com/topics/sqlite/1" term="sqlite"></category></entry><entry><title>Install Apache Cassandra</title><link href="http://www.varunpant.com/posts/install-apache-cassandra" rel="alternate" /><id>http://www.varunpant.com/posts/install-apache-cassandra</id><published>2013-01-27T00:00:00z</published><updated>2013-01-27T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;&lt;a href=&#34;http://cassandra.apache.org&#34; target=&#34;_blank&#34;&gt;Cassandra&lt;/a&gt; is an Open Source Distributed Data Persistence system which is designed for storing and managing large amounts of data across servers.&lt;/p&gt;  &lt;p&gt;&lt;string&gt;To quote elevator pitch by &lt;em&gt;Eben Hewitt&lt;/em&gt; &lt;/strong&gt;&lt;/p&gt;  &lt;blockquote&gt;Apache Cassandra is an open source, distributed, decentralized, elastically scalable, highly available, fault-tolerant, tuneably consistent, column-oriented database that bases its distribution design on Amazon’s Dynamo and its data model on Google’s Bigtable. Created at Facebook, it is now used at some of the most popular sites on the Web.&lt;/blockquote&gt; &lt;strong&gt;Installing Cassandra&lt;/strong&gt;   &lt;p&gt;Cassandra can be installed in most popular&amp;#160; operating systems Windows (vista/XP/7/8), Mac OSX, and Linux variants such as Ubuntu, Red Hat, and CentOS.&lt;/p&gt;  &lt;p&gt;Ideally all platforms which have JVM 1.6 or higher should be just fine. There is a &lt;a href=&#34;http://wiki.apache.org/cassandra/DebianPackaging&#34; target=&#34;_blank&#34;&gt;Debian Packaging&lt;/a&gt; or a third party RPM distribution by &lt;a href=&#34;http://www.datastax.com/products/community&#34; target=&#34;_blank&#34;&gt;DataStax&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;There is a more popular way of downloading the tar distribution , follow this article by downloading and then un packing &lt;a href=&#34;http://www.apache.org/dyn/closer.cgi?path=/cassandra/1.2.0/apache-cassandra-1.2.0-bin.tar.gz&#34; target=&#34;_blank&#34;&gt;binary distribution&lt;/a&gt; from Apache website.&lt;/p&gt;  &lt;p&gt;I am demonstrating this in windows 7. &lt;/p&gt;  &lt;p&gt;Once un packed the folder structure should look like this.&lt;/p&gt;  &lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_2.png&#34;&gt;&lt;img  alt=&#34;cassandra folder structure&#34; src=&#34;http://varunpant.com/static/resources/cassandra_folder-structure.png&#34;  class=&#34;img-polaroid&#34; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;I generally create an environment variable &lt;code&gt;JAVA_HOME&lt;/code&gt; which points to java jdk and &lt;code&gt;CASSANDRA_HOME&lt;/code&gt; which points to the root directory of Cassandra as shown above in the screen shot.&lt;/p&gt; &lt;strong&gt;Quick details about the directory structure under Cassandra root &lt;/strong&gt;  &lt;ol&gt;   &lt;li&gt;&lt;strong&gt;bin&lt;/strong&gt;       &lt;p&gt;As the convention has it, this directory contains executable(batch and shell) to run Cassandra, along with the startup scripts and the nodetool utility. It also has scripts for converting SSTables (the datafiles) to JSON and back.&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;conf&lt;/strong&gt;       &lt;p&gt;This folder contains configurations for Cassandra. Storage-conf.xml file allows to create data store by configuring keyspace and column families,cassandra.yaml and SH file are for configuring cassandra and the environemnt, log4j files are to configure logging levels.&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;interface&lt;/strong&gt;       &lt;p&gt;This folder contains an &lt;a href=&#34;http://thrift.apache.org/&#34; target=&#34;_blank&#34;&gt;RPC&lt;/a&gt; Description file defining Cassandra&#39;s interface in cassandra.thrift&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;javadoc&lt;/strong&gt;       &lt;p&gt;Contains Standard Javadoc API documentation for Cassandra.Cassandra is a wonderful project, but the code contains precious few comments, so you might find the JavaDoc’s usefulness limited. It may be more fruitful to simply read the class files directly if you’re familiar with Java.&lt;/p&gt;   &lt;/li&gt;    &lt;li&gt;&lt;strong&gt;lib&lt;/strong&gt;       &lt;p&gt;This folder contains all the dependecies and libraries which Cassandra needs, there are json parsers and google&#39;s collection libraries.&lt;/p&gt;   &lt;/li&gt; &lt;/ol&gt;  &lt;p class=&#34;alert&#34;&gt;&lt;strong&gt;There is a git repo with source available&lt;/strong&gt; &lt;code&gt;git clone git://git.apache.org/cassandra.git&lt;/code&gt;&lt;/p&gt; &lt;strong&gt;Before starting Cassandra&lt;/strong&gt;   &lt;p&gt;By default, Cassandra uses the following directories for data and commitlog storage (this is linux filesystem): &lt;/p&gt;  &lt;p&gt;/var/lib/cassandra    &lt;br /&gt;/var/log/cassandra&lt;/p&gt;  &lt;p&gt;In the past (version &amp;lt;= 0.6), Cassandra use to have a file called &lt;code&gt;storage-conf.xml&lt;/code&gt;, however from 0.7 all log related stuff goes in &lt;code&gt;log4j-tools.properties&lt;/code&gt;,in windows I recommend changing them appropriately.&lt;/p&gt; If in Linux/Unix machine, you may have to give rights to the folder which Cassandra creates.   &lt;pre class=&#34;prettyprint linenums lang-sh&#34;&gt; cd apache-cassandra-$VERSION

 sudo mkdir -p /var/log/cassandra

 sudo chown -R `whoami` /var/log/cassandra

 sudo mkdir -p /var/lib/cassandra

 sudo chown -R `whoami` /var/lib/cassandra&lt;/pre&gt;

&lt;p&gt;If you like to configure other variables &lt;a href=&#34;http://www.datastax.com/docs/1.0/configuration/node_configuration&#34; target=&#34;_blank&#34;&gt;DataStax&lt;/a&gt; has a nice description of what goes in the &lt;code&gt;cassandra.yaml&lt;/code&gt; &lt;/p&gt;
&lt;strong&gt;Start Cassandra in windows &lt;/strong&gt;

&lt;p&gt;open command prompt, and type&lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;code&gt;cd %CASSANDRA_HOME%/bin&lt;/code&gt;

  &lt;br /&gt;&lt;code&gt;cassandra.bat -f &lt;/code&gt;&lt;/p&gt;
&lt;strong&gt;Start cassandra in *nix&lt;/strong&gt;

&lt;p&gt;&lt;code&gt;cd $CASSANDRA_HOME&lt;/code&gt;

  &lt;br /&gt;&lt;code   =&#34;&amp;lt;code&#34;&gt;sh bin/cassandra -f/&lt;code&gt; &lt;/code&gt;&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You should see something like this (Window screen shot)&lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/image_4.png&#34;&gt;&lt;img  title=&#34;start apache cassandra&#34; alt=&#34;start apache cassandra&#34; src=&#34;http://varunpant.com/static/resources/cassandra_console.png&#34; width=&#34;90%&#34; height=&#34;80%&#34;  class=&#34;img-polaroid&#34; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hope this helps &lt;/p&gt;</content><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="cassandra" scheme="http://www.varunpant.com/topics/cassandra/1" term="cassandra"></category></entry><entry><title>Position div in the center of the page using css</title><link href="http://www.varunpant.com/posts/position-div-in-the-center-of-the-page-using-css" rel="alternate" /><id>http://www.varunpant.com/posts/position-div-in-the-center-of-the-page-using-css</id><published>2013-01-27T00:00:00z</published><updated>2013-01-27T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;When I first started web programming, creating a center aligned div was one of the most common task that I saw myself doing. &lt;/p&gt;  &lt;p&gt;since div is a block element, i.e. it takes up the full width available, and has a line break before and after it, it can easily be centered using relative styling &lt;/p&gt;  &lt;pre class=&#34;prettyprint linenums lang-css&#34;&gt;.center
{
 margin-left:auto;
 margin-right:auto;
 width:70%;
 background-color:#b0e0e6;
}&lt;/pre&gt;

&lt;p&gt;However lately I have preferred using absolute positioning technique over relative, this works for all browsers and is best for login screens or alert messages over a translucent shim.&lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-css&#34;&gt;.center{
    position: absolute;
    top: 50%;
    left: 50%;
    height: 200px;
    width: 200px;
    margin-left: -100px
    margin-top: -100px;
}&lt;/pre&gt;

&lt;p&gt; In case yer wondering what is happening above, then here is a quick explanation.&lt;/p&gt;

&lt;p&gt;Absolute positioning works by treating the browser view port as a drawing board and top left and bottom right as axis-es. In the code above any element with center class will have top and left corners aligned to the center of the page, however since I need to align the center of the element with the page, I push them halfway to the right and half way to the top by applying negative margins.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here is how the div would look inside view port without margins&lt;/strong&gt;

  &lt;br /&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/imgalign2_2.png&#34;&gt;&lt;img title=&#34;image center align top&#34;  alt=&#34;image center align top&#34; src=&#34;http://varunpant.com/static/resources/imgalign2_2.png&#34; width=&#34;240&#34; height=&#34;203&#34; /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;strong&gt;This is how it looks with them (Properly aligned to the center)&lt;/strong&gt;

&lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/divalighn1_4.png&#34;&gt;&lt;img title=&#34;image center align&#34; alt=&#34;image center align &#34; src=&#34;http://varunpant.com/static/resources/divalighn1_4.png&#34; width=&#34;240&#34; height=&#34;205&#34; /&gt;&lt;/a&gt;&lt;/p&gt;</content><category label="css" scheme="http://www.varunpant.com/topics/css/1" term="css"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category></entry><entry><title>A guide to hosting in Red Hats OpenShift PaaS</title><link href="http://www.varunpant.com/posts/a-guide-to-hosting-in-red-hats-openshift-paas" rel="alternate" /><id>http://www.varunpant.com/posts/a-guide-to-hosting-in-red-hats-openshift-paas</id><published>2013-01-25T00:00:00z</published><updated>2013-01-25T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;In this post,I am going to write about &lt;a href=&#34;https://openshift.redhat.com/app/&#34; target=&#34;_blank&#34;&gt;OpenShift&lt;/a&gt;, which is Red hat&#39;s free, auto-scaling Platform as a Service (&lt;a href=&#34;http://en.wikipedia.org/wiki/Platform_as_a_service&#34; target=&#34;_blank&#34;&gt;PaaS&lt;/a&gt;) for applications.&lt;/p&gt;

&lt;p&gt;OpenShift to me is very similar to &lt;a href=&#34;https://developers.google.com/appengine/&#34; target=&#34;_blank&#34;&gt;Google&#39;s app engine&lt;/a&gt; in some ways,but openshift&#39;s offerings are quite diverse, for instance support for ruby, php, Perl, node.js, etc.. &lt;/p&gt;

&lt;p&gt;Openshift is not like a traditional VPS hosting , although once registered with them, user does get a shell access,but its quite limited , instead OpenShift has a concept of gears and cartridges.&lt;/p&gt;

&lt;p&gt;A Cartridge is a like a capability which an application can use, for eg: mysql,mongodb,phpmyadmin etc. There are some officially supported ones available for quick inclusion otherwise users can &lt;a href=&#34;https://openshift.redhat.com/community/wiki/introduction-to-cartridge-building&#34; target=&#34;_blank&#34;&gt;create&lt;/a&gt; their own as well,even though thats a tricky task.&lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;$image6.png&#34;&gt;&lt;img  src=&#34;http://www.varunpant.com/static/resources/image_4.png&#34; class=&#34;img-polaroid&#34; width=&#34;98%&#34; height=&#34;80%&#34; /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I also like the &lt;a href=&#34;https://openshift.redhat.com/community/developers/pricing&#34; target=&#34;_blank&#34;&gt;pricing structure&lt;/a&gt; of OpenShift (Developers Preview), which may be what many developers are looking for,however the web site says right at the top that it may change in future.&lt;/p&gt;

&lt;p&gt;So basically to use,&lt;a href=&#34;http://gb.redhat.com/&#34; target=&#34;_blank&#34;&gt;Redhat&#39;s&lt;/a&gt; &lt;a href=&#34;http://en.wikipedia.org/wiki/Platform_as_a_service&#34; target=&#34;_blank&#34;&gt;PaaS&lt;/a&gt; hosting, one needs to

  &lt;br /&gt;1. Quickly &lt;a href=&#34;https://openshift.redhat.com/app/account/new?then=/community/get-started&#34; target=&#34;_blank&#34;&gt;sign up&lt;/a&gt; for an account.&lt;/p&gt;

&lt;p&gt;2.Use web interface to create an application (good for rapid kick start),or use a ruby command line client tool(good for coding/debugging/app-management) or even use tools integrated in IDE (Eclipse)&lt;/p&gt;

&lt;p&gt;3.OpenShift follows a code check-in model,where a git repository is created and associated with the application created in above step, every check in in that folder structure will cause a rebuild of environment and will reboot the web server.&lt;/p&gt;

&lt;p&gt;To download the repo simply type &lt;code&gt;git clone ssh://...rhcloud.com/~/git/myapp.git/&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;When changes have been made then type &lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-sh&#34;&gt;$ cd myapp
$ vim php/index.php
(Make a change...  :wq)
$ git commit -a -m &amp;quot;My first change&amp;quot;
$ git push&lt;/pre&gt;

&lt;p&gt;To get you up and running quickly&amp;#160; OpenShift has a bunch of quick starts &lt;a href=&#34;https://openshift.redhat.com/community/developers/get-started&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;, there is also a getting started &lt;a href=&#34;https://openshift.redhat.com/community/developers/get-involved/creating-quickstarts&#34; target=&#34;_blank&#34;&gt;guide&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;OpenShift also has a well maintained&amp;#160; &lt;a href=&#34;https://openshift.redhat.com/community/blogs&#34; target=&#34;_blank&#34;&gt;blog&lt;/a&gt;&amp;#160; , a &lt;a href=&#34;https://openshift.redhat.com/community/faq&#34; target=&#34;_blank&#34;&gt;FAQ&lt;/a&gt; and even &lt;a href=&#34;https://openshift.redhat.com/community/videos&#34; target=&#34;_blank&#34;&gt;videos&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;I must say that the companion &lt;a href=&#34;https://openshift.redhat.com/community/developers/install-the-client-tools#windows&#34; target=&#34;_blank&#34;&gt;rhc command line utility&lt;/a&gt; is very helpful, it can be installed in all popular operating systems.&lt;/p&gt;

&lt;p&gt;I also like their &lt;a href=&#34;https://github.com/openshift&#34; target=&#34;_blank&#34;&gt;github page&lt;/a&gt; where they have many examples (see the bottom of list).&lt;/p&gt;

&lt;p&gt;There is a concept of gear in openshift, which to me is very similar to what a compute instance is in Amazon.&lt;/p&gt;

&lt;p&gt;This is what guys at OpenShift say about it&lt;/p&gt;

&lt;blockquote&gt;A gear is a resource constrained container that runs one or more user-specified software stacks, also known as cartridges. Each gear has a limited amount of RAM and disk space. If an application needs more resources, it can use multiple gears. Gears come in multiple sizes to suit the needs of various software stacks.&lt;/blockquote&gt;

&lt;p&gt;If you would like to read more about their architecture, here is a &lt;a href=&#34;https://openshift.redhat.com/community/wiki/architecture-overview&#34; target=&#34;_blank&#34;&gt;link&lt;/a&gt;, the best part is that every bit is &lt;a href=&#34;https://openshift.redhat.com/community/open-source/download-origin&#34; target=&#34;_blank&#34;&gt;open sourced&lt;/a&gt;.&lt;/p&gt;</content><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category><category label="linux" scheme="http://www.varunpant.com/topics/linux/1" term="linux"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category><category label="ubuntu" scheme="http://www.varunpant.com/topics/ubuntu/1" term="ubuntu"></category></entry><entry><title>Basic authentication in web.py via attribute</title><link href="http://www.varunpant.com/posts/basic-authentication-in-web-py-via-attribute" rel="alternate" /><id>http://www.varunpant.com/posts/basic-authentication-in-web-py-via-attribute</id><published>2013-01-23T00:00:00z</published><updated>2013-01-23T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;Here I demonstrate the process of &lt;a href=&#34;http://en.wikipedia.org/wiki/Basic_access_authentication&#34;&gt;Basic Authentication&lt;/a&gt; in &lt;a href=&#34;http://webpy.org/&#34;&gt;web.py&lt;/a&gt; python web framework. &lt;/p&gt;  &lt;p&gt;There is a proof of concept article &lt;a href=&#34;http://webpy.org/cookbook/userauthbasic&#34;&gt;provided&lt;/a&gt; in the main site,however I just thought doing the same via an attribute might be a cleaner solution.&lt;/p&gt;  &lt;p&gt;HTTP Basic authentication implementation is one of the easiest ways to secure web pages because it doesn&#39;t require cookies, session handling, or the development of login pages. Rather, HTTP Basic authentication uses static headers which means that no handshakes have to be done in anticipation,however the n the credentials are passed as &lt;a href=&#34;http://en.wikipedia.org/wiki/Plaintext&#34;&gt;plain-text &lt;/a&gt;and could be intercepted.&amp;#160; &lt;/p&gt;  &lt;p&gt;The header looks something like this &lt;/p&gt; &lt;code&gt;WWW-Authenticate: Basic realm=&amp;quot;&lt;i&gt;insert realm&lt;/i&gt;&amp;quot;&lt;/code&gt;   &lt;p&gt;To construct the header&lt;/p&gt;  &lt;p&gt;Username and password are concatenated into a string &amp;quot;username:password&amp;quot; and this sting is encoded using &lt;a href=&#34;http://en.wikipedia.org/wiki/Base64&#34;&gt;Base64&lt;/a&gt; and then a constant string is prepended with a space &lt;strong&gt;Authorization: Basic &lt;/strong&gt;. So the final value looks like &lt;code&gt;Authorization: Basic dXNlcm5tYWU6cGFzc3dvcmQ=&lt;/code&gt; &lt;/p&gt;  &lt;p&gt;To decode the string on server side, the reverse of above mentioned process is performed.&lt;/p&gt;  &lt;pre class=&#34;prettyprint linenums lang-python&#34;&gt;
###############################################################################
# BASIC AUTH      #############################################################
###############################################################################

def check_auth(username, password):
    return username == &#39;username&#39; and password == &#39;password&#39;


def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = web.ctx.env[&#39;HTTP_AUTHORIZATION&#39;] if &#39;HTTP_AUTHORIZATION&#39; in  web.ctx.env else None
        if auth:
            auth = re.sub(&#39;^Basic &#39;, &#39;&#39;, auth)
            username, password = base64.decodestring(auth).split(&#39;:&#39;)
        if not auth or not check_auth(username, password):
            web.header(&#39;WWW-Authenticate&#39;, &#39;Basic realm=&amp;quot;admin&amp;quot;&#39;)
            web.ctx.status = &#39;401 Unauthorized&#39;
            return Unauthorized()

        return f(*args, **kwargs)

    return decorated

class Unauthorized():
    def GET(self):
        return &amp;quot;401 Unauthorized&amp;quot;

    def POST(self):
        return &amp;quot;401 Unauthorized&amp;quot;&lt;/pre&gt;


&lt;p&gt;So basically if a route handler needs authentication, all it needs is an attribute
&lt;pre class=&#34;prettyprint linenums lang-python&#34;&gt;
@requires_auth
class Index:
    def GET(self):
	pass;
&lt;/pre&gt;&lt;/p&gt;

&lt;p&gt;Hope this helps. &lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="web.py" scheme="http://www.varunpant.com/topics/web-py/1" term="web.py"></category></entry><entry><title>Cross browser drop shadow with CSS3</title><link href="http://www.varunpant.com/posts/cross-browser-drop-shadow-with-css3" rel="alternate" /><id>http://www.varunpant.com/posts/cross-browser-drop-shadow-with-css3</id><published>2013-01-23T00:00:00z</published><updated>2013-01-23T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;When &lt;strong&gt;css3&lt;/strong&gt; arrived, one of the goodies that I found was, the inclusion of &lt;strong&gt;Drop Shadow effect&lt;/strong&gt;, namely &lt;strong&gt;Box Shadow &lt;/strong&gt;and &lt;strong&gt;Text Shadow&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Here I present a cross browser utility css&amp;#160; class which can be used for a drop shadow effect, without any image. &lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-css&#34;&gt;.shadow {
       /* For IE 8 */
	-ms-filter: &amp;quot;progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color=&#39;#000000&#39;)&amp;quot;;
	/* For IE 5.5 - 7 */
	filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color=&#39;#000000&#39;);
	-moz-box-shadow: 3px 3px 4px #000;
	-webkit-box-shadow: 3px 3px 4px #000;
	box-shadow: 3px 3px 4px #000;
}&lt;/pre&gt;
For cross browser &lt;strong&gt;text shadow&lt;/strong&gt;&amp;#160; effect ,I found a nice article &lt;a href=&#34;http://www.workingwith.me.uk/examples/css-drop-shadows.html#final_example&#34;&gt;here&lt;/a&gt;.

&lt;pre class=&#34;prettyprint linenums lang-css&#34;&gt;* default setup that everything sees */
.shadow {
  /* needed for Internet explorer */
  height: 1em;
  filter: Shadow(Color=#666666,
                 Direction=135,
                 Strength=5);

  /* Needed for Gecko */
  line-height: 2em;
  white-space: nowrap;
}

/*
 * used by browsers which know about
 * :before to create the shadow
 */
.shadow:before {
  display: block;
  margin: 0 0 -2.12em 0.15em;
  padding: 0;
  color: #666666;
}

#shadow_1:before {
  content: &#39;In shadow&#39;;
}
#second_2:before {
  content: &#39;Happy Shadowing!&#39;;
}

/*\*/
html*.shadow {

  [color:red;/* required by Safari
              * so that [] is correctly
              * begun. associated with
              * the property, yet hiding
              * it. Seen by IE6 */

    /*
     * seen by IE6 and Safari, but hidden
     * from Gecko
     */
    text-shadow: #666666 5px 5px 5px;

  ]color:auto; /* resets color for IE6 */
}/**/

/*
 * end hack using dummy attribute selector
 * for IE5 mac
 */
.dummyend[id]{clear: both;}

/*\*/
html*.shadow:before {

  [color:red;/* required by Safari.
                seen by IE6 */

    /*
     * seen by IE6 and Safari, but hidden
     * from Gecko
     */
    display: none;

  ]color:auto; /* resets color for IE6 */
}/**/

/*
 * end hack using dummy attribute selector
 * for IE5 mac
 */
.dummyend[id]{clear: both;}&lt;/pre&gt;



&lt;p&gt;Hope this helps. &lt;/p&gt;</content><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="util" scheme="http://www.varunpant.com/topics/util/1" term="util"></category><category label="css" scheme="http://www.varunpant.com/topics/css/1" term="css"></category></entry><entry><title>Cross browser CSS3 border-radius (rounded corners)</title><link href="http://www.varunpant.com/posts/cross-browser-css3-border-radius-rounded-corners" rel="alternate" /><id>http://www.varunpant.com/posts/cross-browser-css3-border-radius-rounded-corners</id><published>2013-01-22T00:00:00z</published><updated>2013-01-22T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;When I started programming and had to begin designing my first user interface in HTML, I was always puzzled as to why are all visual elements in HTML rectangular. I soon learned that in those days if one would want a circle to be drawn on a page, then the only way possible was using an image, the same was true for drawing elements with rounded corners.&lt;/p&gt;
&lt;p&gt;Thankfully HTML5/CSS3 guys were listening and the latest css3 standard supports defining the corner radius of a circle, this can be used to make an element look like a circle too if you want.&lt;/p&gt;

&lt;p&gt;
Here I present a cross browser css3 class which will introduce a curve on otherwise rectangular elements.
&lt;h4&gt;&lt;strong&gt;Border-radius for modern browsers including IE9 &lt;/strong&gt;&lt;/h4&gt;
&lt;pre class=&#34;prettyprint linenums lang-css&#34;&gt;
.curve{
  -webkit-border-radius: 10px; /* Safari, Chrome */

  -moz-border-radius: 10px; /* Firefox */

  border-radius: 10px; /* CSS3 */
}
&lt;/pre&gt;



&lt;h4&gt;&lt;strong&gt;Border-radius for IE (version &lt; 9)&lt;/strong&gt;&lt;/h4&gt;
&lt;p&gt;Download the &lt;a href=&#34;http://curved-corner.googlecode.com/files/border-radius.htc&#34; target=&#34;_blank&#34;&gt;border-radius.htc&lt;/a&gt; file,and put it on the website.&lt;/p&gt;
&lt;pre class=&#34;prettyprint linenums lang-css&#34;&gt;
.curve{
  behavior: url(http://mywebsite.com/border-radius.htc);
}
&lt;/pre&gt;


If you would like to convert your rectangular element to circle the trick is to make your corner radius half the width/height of your shape and make sure that the shape is originally a square,i.e. height and width of the shape should be same.
&lt;pre class=&#34;prettyprint linenums lang-css&#34;&gt;
#circular {
height: 100px;
width: 100px;
-webkit-border-radius: 50px;
-moz-border-radius: 50px;
border-radius: 50px;
}
&lt;/pre&gt;

In above example, a div of id &lt;em&gt;circular&lt;/em&gt; with height and width of &lt;strong&gt;100px&lt;/strong&gt; will look circular as the border radius is &lt;code&gt;100 / 2 = 50px &lt;/code&gt;.


Hope this helps ;)
&lt;/p&gt;</content><category label="css" scheme="http://www.varunpant.com/topics/css/1" term="css"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="util" scheme="http://www.varunpant.com/topics/util/1" term="util"></category></entry><entry><title>Cross Browser Opacity or Transparency</title><link href="http://www.varunpant.com/posts/cross-browser-opacity-or-transparency" rel="alternate" /><id>http://www.varunpant.com/posts/cross-browser-opacity-or-transparency</id><published>2013-01-22T00:00:00z</published><updated>2013-01-22T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;Css has a very useful property called Opacity, which basically is a measure of transparency of an element.&lt;/p&gt;
&lt;p&gt;All modern browsers &lt;em&gt;Yes yes even &lt;strong&gt;IE&lt;/strong&gt;&lt;/em&gt; has support for it. &lt;/p&gt;
&lt;p&gt;
 In most browsers the value is between &lt;strong&gt;0&lt;/strong&gt; &lt;em&gt;minimum [transparent] i.e not visible&lt;/em&gt; to &lt;strong&gt;1&lt;/strong&gt; &lt;em&gt;maximum [opaque] i.e. completely visible&lt;/em&gt;
&lt;/p&gt;

&lt;p&gt;
In &lt;strong&gt;IE&lt;/strong&gt; the value is between 0 and 100  &lt;em&gt;,don&#39;t ask why they just like to make us unhappy.&lt;/em&gt;  &lt;/p&gt;

&lt;p&gt;
Here I present a helper css class which will work in all browsers.

&lt;pre class=&#34;prettyprint linenums lang-css&#34; &gt;
.transparent {
 /* IE 5-7 */
  filter: alpha(opacity=50);

  /* IE 8 */
  -ms-filter: &#34;progid:DXImageTransform.Microsoft.Alpha(Opacity=50)&#34;;

  /* FF/Netscape */
  -moz-opacity: 0.5;

  /* Safari 1.x */
  -khtml-opacity: 0.5;

  /* Good browsers  (aka chrome ;) ) */
  opacity: 0.5;
}
&lt;/pre&gt;

I hope you find this use full

&lt;/p&gt;</content><category label="css" scheme="http://www.varunpant.com/topics/css/1" term="css"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category></entry><entry><title>Installing Redis on Ubuntu</title><link href="http://www.varunpant.com/posts/installing-redis-on-ubuntu" rel="alternate" /><id>http://www.varunpant.com/posts/installing-redis-on-ubuntu</id><published>2013-01-20T00:00:00z</published><updated>2013-01-20T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;&lt;a href=&#34;http://redis.io/&#34;&gt;Redis&lt;/a&gt; is an open source, advanced key-value store. Installing it on Linux debian platforms is pretty easy.&lt;/p&gt;    &lt;p&gt;There are two ways of getting this done, one is perhaps an easy and less verbose method and it involves using an alternative repository &lt;a href=&#34;http://www.dotdeb.org/&#34;&gt;Dotdeb.&lt;/a&gt; &lt;/p&gt;  &lt;p&gt;A while ago I had posted a &lt;a href=&#34;http://www.varunpant.com/posts/how-to-set-up-redis-in-ubuntu-linux&#34;&gt;tutorial&lt;/a&gt; about installing redis from the &lt;a href=&#34;http://redis.googlecode.com/files/redis-2.2.4.tar.gz&#34;&gt;googlecode&lt;/a&gt; repo, but things have changed since then and here I post a fairly latest way of installing it.&lt;/p&gt;  &lt;h4&gt;Install using aptitude and Dotdeb repo&lt;/h4&gt;  &lt;p&gt;My experience with &lt;a href=&#34;http://www.dotdeb.org/&#34;&gt;Dotdeb&lt;/a&gt; has been pretty nice,it has a bunch of nice packages, always up to date with the very latest version.&lt;/p&gt;  &lt;p&gt;Begin by adding Dotdeb repositories to your APT sources. Create a new list file in &lt;code&gt;/etc/apt/sources.list.d/&lt;/code&gt; and fill it with the following content. &lt;/p&gt;  &lt;pre class=&#34;prettyprint linenums lang-sh&#34;&gt;# /etc/apt/sources.list.d/dotdeb.org.list
deb http://packages.dotdeb.org squeeze all
deb-src http://packages.dotdeb.org squeeze all&lt;/pre&gt;
Then you need to authenticate these repositories using their public key. &lt;code&gt;wget -q -O - http://www.dotdeb.org/dotdeb.gpg | sudo apt-key add -&lt;/code&gt; Finally update the apt-cache and install

&lt;pre class=&#34;prettyprint linenums lang-sh&#34;&gt;$ sudo aptitude update
$ sudo aptitude install redis-server&lt;/pre&gt;

&lt;h4&gt;Manual Install&lt;/h4&gt;

&lt;p&gt;The other way is downloading the source, building it and then installing it&lt;/p&gt;

&lt;p&gt;Download redis from its git repo. &lt;code&gt;git clone https://github.com/antirez/redis.git&lt;/code&gt; Change directory to the redis folder and type &lt;code&gt;make&lt;/code&gt;, for 32 bits type&lt;code&gt;make 32bit&lt;/code&gt; and then test &lt;code&gt;make test&lt;/code&gt; To run redis with default configuration change directory to src &lt;code&gt;cd src&lt;/code&gt; and then type &lt;code&gt;./redis-server&lt;/code&gt; If you want to provide your custom conf, then simply pass it in as an arg &lt;code&gt;./redis-server /path/to/redis.conf&lt;/code&gt; To install Redis here &lt;code&gt;/usr/local/bin &lt;/code&gt;type &lt;code&gt;make install&lt;/code&gt; , this however simply copies the binaries at the said location. Redis provides a proper script to install it properly in Ubuntu and Debian systems. change directory to Utils &lt;code&gt;cd utils&lt;/code&gt; and then execute&lt;code&gt;./install_server&lt;/code&gt; use commands below to start stop the server &lt;/p&gt;

&lt;pre class=&#34;prettyprint linunums lang-sh&#34;&gt;$ sudo start redis-server
$ sudo restart redis-server
$ sudo stop redis-server&lt;/pre&gt;</content><category label="redis" scheme="http://www.varunpant.com/topics/redis/1" term="redis"></category><category label="ubuntu" scheme="http://www.varunpant.com/topics/ubuntu/1" term="ubuntu"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category></entry><entry><title>gzip compression in apache using mod_deflate</title><link href="http://www.varunpant.com/posts/gzip-compression-in-apache-using-mod_deflate" rel="alternate" /><id>http://www.varunpant.com/posts/gzip-compression-in-apache-using-mod_deflate</id><published>2013-01-19T00:00:00z</published><updated>2013-01-19T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;&lt;a href=&#34;http://en.wikipedia.org/wiki/HTTP_compression&#34;&gt;HTTP Compression&lt;/a&gt; is a very simple and effective way to save bandwidth and improve web applications performance over network.&lt;/p&gt;  &lt;p&gt;Output compression is basically a process of compressing web servers response by using a loss-less compression algorithm called &lt;a href=&#34;http://en.wikipedia.org/wiki/Deflate&#34;&gt;gzip&lt;/a&gt;. &lt;/p&gt;  &lt;p&gt;This technique is fairly modern and almost all modern browsers honor it, however if a page is requested from a browser which does not send a header &lt;code&gt;Accept-Encoding: gzip,deflate &lt;/code&gt;then the response comes back uncompressed.&lt;/p&gt;  &lt;p&gt;In Apache under Ubuntu OS this is fairly simple.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;Enable mod_deflate in Apache2 &lt;/strong&gt;&lt;code&gt;sudo a2enmod deflate&lt;/code&gt;&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;configure /etc/apache2/httpd.conf mod_deflate &lt;/strong&gt; by adding content mentioned below.&lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-html&#34;&gt;
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# Or, compress certain file types by extension:
&amp;lt;files *.html&amp;gt;
SetOutputFilter DEFLATE
&amp;lt;/files&amp;gt;
&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;Restart apache to anable the changes&lt;/strong&gt; &lt;code&gt;sudo apachectl graceful&lt;/code&gt; &lt;/p&gt;
&lt;p&gt; There is another powerfull apache module called &lt;code&gt;mod_gzip &lt;/code&gt;which can precompress output as well. &lt;/p&gt;
&lt;p&gt;Hope this helps.&lt;/p&gt;</content><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category></entry><entry><title>Start Stop Restart Apache 2 Web Server</title><link href="http://www.varunpant.com/posts/start-stop-restart-apache-2-web-server" rel="alternate" /><id>http://www.varunpant.com/posts/start-stop-restart-apache-2-web-server</id><published>2013-01-19T00:00:00z</published><updated>2013-01-19T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt; I have been using Linux environment a lot lately, particularly for hosting my web experiments and other application. One of the biggest and most searched question for newbies have been &lt;blockquote&gt;How do I restart Apache 2 Web Server under Debian / Ubuntu Linux or UNIX operating systems?&lt;/blockquote&gt; &lt;/p&gt;

&lt;p&gt;In this post I simply attempt to lay this down for my and their benifit.&lt;/p&gt;

&lt;p&gt;
	&lt;strong&gt;Start Apache2&lt;/strong&gt;
	&lt;code&gt;# sudo /etc/init.d/apache2 start&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
	&lt;strong&gt;Stop Apache2&lt;/strong&gt;
	&lt;code&gt;# sudo /etc/init.d/apache2 stop&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
	&lt;strong&gt;Restart Apache2&lt;/strong&gt;
	&lt;code&gt;# sudo /etc/init.d/apache2 restart&lt;/code&gt;
&lt;/p&gt;

&lt;p&gt;
	&lt;strong&gt;Graceful&lt;/strong&gt;
	&lt;code&gt;# sudo /etc/init.d/apache2 graceful&lt;/code&gt;

	or

	&lt;code&gt;# sudo /etc/init.d/apache2 reload&lt;/code&gt;
&lt;/p&gt;

 &lt;p&gt;There are other less verbose ways as well. If using apache2ctl (If its not on your path generally apche2ctl can be found here &lt;code&gt;/usr/sbin/apache2ctl&lt;/code&gt;&lt;/p&gt;

 &lt;p&gt;
 &lt;strong&gt;Restart Apache2 gracefully&lt;/strong&gt;
 &lt;code&gt;sudo apache2ctl graceful&lt;/code&gt;
 &lt;strong&gt;Stop Apache2 gracefully&lt;/strong&gt;
 &lt;code&gt;sudo apache2ctl graceful-stop&lt;/code&gt;
 &lt;/p&gt;</content><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category></entry><entry><title>Factorial in python</title><link href="http://www.varunpant.com/posts/factorial-in-python" rel="alternate" /><id>http://www.varunpant.com/posts/factorial-in-python</id><published>2012-08-14T00:00:00z</published><updated>2012-08-14T00:00:00z</updated><author><name>Varun Pant</name></author><content type="html">&lt;p&gt;

  Mathematically, the formula for the factorial is as follows. If n is an integer greater than or equal to 1, then

  &lt;code&gt;n ! = n ( n - 1)( n - 2)( n - 3) ... (3)(2)(1)&lt;/code&gt; If &lt;code&gt;p = 0&lt;/code&gt;, then &lt;code&gt;p ! = 1&lt;/code&gt; by convention.


&lt;/p&gt;



&lt;pre&gt;
def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)
&lt;/pre&gt;

&lt;p&gt;Hope this helps&lt;/p&gt;</content><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="algorithms" scheme="http://www.varunpant.com/topics/algorithms/1" term="algorithms"></category></entry><entry><title>Auto Complete with Redis (Python)</title><link href="http://www.varunpant.com/posts/auto-complete-with-redis-python" rel="alternate" /><id>http://www.varunpant.com/posts/auto-complete-with-redis-python</id><published>2012-05-06T00:00:00z</published><updated>2012-05-06T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;This is a quick port of &lt;a href=&#34;http://antirez.com/post/autocomplete-with-redis.html&#34;&gt;auto complete&lt;/a&gt; implementation in ruby using &lt;a href=&#34;http://redis.io/&#34;&gt;Redis&lt;/a&gt; by &lt;a href=&#34;http://invece.org/&#34;&gt;antirez&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;I like python&amp;nbsp; and had little time to burn today, so here goes:&lt;/p&gt;

&lt;script src=&#34;https://gist.github.com/2624605.js&#34;&gt; &lt;/script&gt;


&lt;p&gt;The file used for input is &lt;a href=&#34;http://antirez.com/misc/female-names.txt&#34;&gt;female-names.txt&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Hope it helps :)&lt;/p&gt;</content><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="redis" scheme="http://www.varunpant.com/topics/redis/1" term="redis"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category></entry><entry><title>How To Install and use Python Web.py framework on Windows</title><link href="http://www.varunpant.com/posts/how-to-install-and-use-python-webpy-framework-on-windows" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-install-and-use-python-webpy-framework-on-windows</id><published>2012-05-06T00:00:00z</published><updated>2012-05-06T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;
    &lt;a href=&#34;http://webpy.org/&#34;&gt;Web.py&lt;/a&gt; has been one of my favorite web frameworks as its pretty easy
    to get cracking on it.&lt;/p&gt;
&lt;p&gt;It&#39;s super quick to install and one can come up with a prototype and rapid
    web services in  matter of minutes.&lt;/p&gt;
 &lt;h2&gt;Install on windows&lt;/h2&gt;
&lt;p&gt;If you haven&#39;t configured easy_install on windows, then read
    &lt;a href=&#34;http://www.varunpant.com/posts/how-to-setup-easy_install-on-windows&#34;&gt; this &lt;/a&gt; article.&lt;/p&gt;
&lt;p&gt;Once easy_install has been configured believe it or not, all you have
    to do is open a command prompt and type&lt;/p&gt;
&lt;blockquote&gt;
    &lt;p&gt;&lt;code&gt;easy_install web.py&lt;/code&gt;
    &lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;and that’s it, you are all set ,     to test if things work properly, create
    a test.py file and paste this code from
    &lt;a href=&#34;http://webpy.org/&#34;&gt;Web.py&lt;/a&gt; web site&lt;/p&gt;
&lt;pre class=&#34;prettyprint linenums lang-python&#34;&gt;
  import web

  urls = (
      &#39;/(.*)&#39;, &#39;hello&#39;
  )
  app = web.application(urls, globals())

  class hello:
      def GET(self, name):
          if not name:
              name = &#39;World&#39;
          return &#39;Hello, &#39; + name + &#39;!&#39;

  if __name__ == &amp;quot;__main__&amp;quot;:
      app.run()
&lt;/pre&gt;

&lt;p&gt;run the code by typing &lt;code&gt;python test.py 3333&lt;/code&gt;, then open the web browser and
    go to&lt;/p&gt;
&lt;p&gt;
    &lt;code&gt;&lt;a href=&#34;http://localhost:3333/Einstein&#34;&gt;http://localhost:3333/Einstein&lt;/a&gt;&lt;/code&gt;, on the browser you should see Hello,Einstein.&lt;/p&gt;
&lt;p&gt;Hope this helps .&lt;/p&gt;</content><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category></entry><entry><title>How to setup easy_install on Windows</title><link href="http://www.varunpant.com/posts/how-to-setup-easy_install-on-windows" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-setup-easy_install-on-windows</id><published>2012-05-06T00:00:00z</published><updated>2012-05-06T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;
If one has been using python, then installing various libraries and modules is basically a breeze using easy_install utility, however for folks using windows, easy_install utility has to be setup properly before using it.
&lt;/p&gt;
&lt;p&gt;
First lets make sure that python is properly installed and &lt;code&gt;PYTHON_HOME&lt;/code&gt; environment variable is configured:
&lt;/p&gt;
&lt;h4&gt;Install Python on Windows&lt;/h4&gt;
&lt;p&gt;
If not already installed download python installer from &lt;a href=&#34;http://python.org/download/&#34;&gt;here.&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
After it&#39;s done downloading, double click to run the installer, and select default options (unless you have other custom needs of course ).
&lt;/p&gt;
&lt;p&gt;
Once done lets quickly setup a &lt;strong&gt;PYTHON_HOME&lt;/strong&gt; environment variable which points to the python directory which contains python exe, in my case its &lt;code&gt;c:/Python27&lt;/code&gt;, to set up environment variable right click &amp;quot;&lt;code&gt;My Computer&lt;/code&gt;   select &lt;code&gt;properties&lt;/code&gt; &lt;code&gt;Advanced Tab&lt;/code&gt; &lt;code&gt;Environment Variables Button&lt;/code&gt; , add new environment variable and call it &lt;code&gt;“PYTHON_HOME”&lt;/code&gt; and set path to whatever is in your case, to make sure every thing is proper ,open NEW dos prompt and type &lt;code&gt;echo %PYTHON_HOME%&lt;/code&gt; and you should see the path you have entered.
&lt;/p&gt;
&lt;p&gt;
Next open you environment variables GUI again as instructed above and this time locate your path variable, once found append &lt;code&gt;%PTHON_HOME%&lt;/code&gt; at the end by separating it with a semicolon. To check everything is setup properly open NEW command line and enter&lt;code&gt;echo %PATH%&lt;/code&gt;, and you should see your entry at the end of the string.
&lt;/p&gt;
&lt;h2&gt;Setup Easy_Install&lt;/h2&gt;
&lt;p&gt;
First we&#39;ll need to download &lt;a href=&#34;http://pypi.python.org/pypi/setuptools&#34;&gt;setuptools&lt;/a&gt;.Download the exe and run it.
&lt;/p&gt;
&lt;p&gt;
The directory that contains easy_install is by default&lt;code&gt;c:\&amp;lt;pythonfolder&amp;gt;\Scripts&lt;/code&gt;
&lt;/p&gt;
&lt;p&gt;
All you need to do now is append &lt;code&gt;%PYTHON_HOME%\Scripts &lt;/code&gt;, separated by a semicolon ; at the end of path variable in your environment settings as instructed above, as usual enter&lt;code&gt;echo %PATH%&lt;/code&gt; to confirm change, then open command promt and type &lt;code&gt;easy_install&lt;/code&gt; and you should see a warning (its ok we havent passed in a package name or url )
&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;
error: No urls, filenames, or requirements specified (see --help) &lt;br/&gt;
&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;
And that’s it folks. Happy easy_installing.
&lt;/p&gt;</content><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category></entry><entry><title>Find Longitude and Latitude in Google Maps</title><link href="http://www.varunpant.com/posts/find-longitude-and-latitude-in-google-maps" rel="alternate" /><id>http://www.varunpant.com/posts/find-longitude-and-latitude-in-google-maps</id><published>2012-04-15T00:00:00z</published><updated>2012-04-15T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;This post is basically a way of quick appreciation to the &lt;strong&gt;Google maps Team&lt;/strong&gt;, they are&amp;#160;&amp;#160; obviously a bunch of caring, loving people ,who make useful (although &lt;strong&gt;surreptitious&lt;/strong&gt;) tools for the betterment of Geek Kind.&lt;/p&gt;  &lt;p&gt;So as most of you may have accidently clicked a mysterious looking link at the bottom of your Google maps page&amp;#160; ( on the left hand panel)&lt;a href=&#34;http://varunpant.com/static/resources/google_latlon_tool1_4.png&#34;&gt;&lt;img alt=&#34;google_latlon_tool1&#34; src=&#34;http://varunpant.com/static/resources/google_latlon_tool1_thumb_1.png&#34; width=&#34;90%&#34;  /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;This awesome looking link opens up a popup which lets you choose wonderful goodies which makes your Google maps page more useful than it already is:&lt;/p&gt;  &lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/google_latlon_tool2_2.png&#34;&gt;&lt;img title=&#34;google_latlon_tool2&#34; alt=&#34;google_latlon_tool2&#34; src=&#34;http://varunpant.com/static/resources/google_latlon_tool2_thumb.png&#34; width=&#34;90%&#34; height=&#34;366&#34; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Now one can choose things like Smart Zoom but this post is about &lt;strong&gt;LatLng&lt;/strong&gt; marker and tooltip ,&lt;/p&gt;  &lt;p&gt;which are very handy,especially if one works as a GIS application developer.&lt;/p&gt;  &lt;p&gt;Ones you are done selecting, simply click &lt;strong&gt;Save changes&lt;/strong&gt; and that’s it.(You may have to refresh your page though ).&lt;/p&gt;  &lt;p&gt;After these features have been enabled, a user can now right click anywhere on the map, and in the options window , a new link “&lt;strong&gt;Drop latLng Marker&lt;/strong&gt;” will appear.&lt;/p&gt;  &lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/google_latlon_tool3_2.png&#34;&gt;&lt;img title=&#34;google_latlon_tool3&#34; alt=&#34;google_latlon_tool3&#34; src=&#34;http://varunpant.com/static/resources/google_latlon_tool3_thumb.png&#34; width=&#34;195&#34;  /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;Select that and the obvious will happen.&lt;/p&gt;  &lt;p&gt;&lt;a href=&#34;http://varunpant.com/static/resources/google_latlon_tool4_2.png&#34;&gt;&lt;img title=&#34;google_latlon_tool4&#34; alt=&#34;google_latlon_tool4&#34; src=&#34;http://varunpant.com/static/resources/google_latlon_tool4_thumb.png&#34; width=&#34;240&#34; height=&#34;155&#34; /&gt;&lt;/a&gt;&lt;/p&gt;  &lt;p&gt;and there you have it , an easy, helpful, Hidden(not anymore), but never the less extremely &lt;strong&gt;useful&lt;/strong&gt; utility to get latitude and longitude from Google maps.&lt;/p&gt;</content><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="gis" scheme="http://www.varunpant.com/topics/gis/1" term="gis"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category></entry><entry><title>How to set up Redis in Ubuntu Linux</title><link href="http://www.varunpant.com/posts/how-to-set-up-redis-in-ubuntu-linux" rel="alternate" /><id>http://www.varunpant.com/posts/how-to-set-up-redis-in-ubuntu-linux</id><published>2012-04-14T00:00:00z</published><updated>2012-04-14T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;&lt;a href=&#34;http://redis.io/&#34;&gt;Redis&lt;/a&gt; is an open source, advanced key-value store, and is quickly picking up momentum in real-time software development , it is now a well known and trusted product and can be used in various&amp;#160; problem scenarios as a No SQL implementation.&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;a href=&#34;http://redis.io/&#34;&gt;Redis&lt;/a&gt; is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets. &lt;/p&gt;

&lt;p&gt;Here is quick guide to Install &lt;a href=&#34;http://redis.io/&#34;&gt;Redis&lt;/a&gt; in Ubuntu 10.04, and it should be similar for higher versions and similar deb environment. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prepare System for &lt;/strong&gt;&lt;a href=&#34;http://redis.io/&#34;&gt;&lt;strong&gt;Redis&lt;/strong&gt;&lt;/a&gt;&lt;strong&gt; &lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Issue the following commands to update your system&#39;s package repositories and ensure that all installed packages are up to date: &lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-sh&#34;&gt;apt-get update
apt-get upgrade&lt;/pre&gt;

&lt;p&gt;You may also need to prepare a vanilla system to get some installation tools. &lt;/code&gt;apt-get install build-essential &lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Begin the installation process by issuing the following sequence of commands to download the software and prepare it for use: &lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-sh&#34;&gt;cd /tmp
wget &lt;a href=&#34;http://redis.googlecode.com/files/redis-2.2.4.tar.gz&#34;&gt;http://redis.googlecode.com/files/redis-2.2.4.tar.gz&lt;/a&gt;
tar -zxf redis-2.2.4.tar.gz
cd redis-2.2.4
make
sudo make install&lt;/pre&gt;

&lt;p&gt;Your &lt;a href=&#34;http://redis.io/&#34;&gt;Redis&lt;/a&gt; binaries should now be located in &lt;strong&gt;/usr/local/bin&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;note:&lt;/strong&gt;Check the &lt;strong&gt;Redis&lt;/strong&gt; upstream project source to ensure that you are downloading the most up to date version of &lt;strong&gt;Redis&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;All Redis configuration options can be specified in the &lt;strong&gt;redis.conf&lt;/strong&gt; file located at &lt;strong&gt;/tmp/redis/redis.conf.&lt;/strong&gt;&amp;#160;&amp;#160; &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;u&gt;Sample redis conf&lt;/u&gt;&lt;/strong&gt; &lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-sh&#34;&gt;daemonize yes
pidfile /var/run/redis.pid
logfile /var/log/redis.log
port 6379
bind 127.0.0.1
timeout 300
loglevel notice
##Default configuration options
databases 16
save 900 1
save 300 10
save 60 10000
rdbcompression yes
dbfilename dump.rdb
dir /tmp/redis/
appendonly no
glueoutputbuf yes
&lt;/pre&gt;

&lt;p&gt;Most of the values in this configuration mirror the default &lt;a href=&#34;http://redis.io/&#34;&gt;Redis&lt;/a&gt; configuration. However, this configuration configures &lt;a href=&#34;http://redis.io/&#34;&gt;Redis&lt;/a&gt; to run in a daemon mode bound only to the local network interface. You may want to change these values depending on the needs of your application. &lt;/p&gt;

&lt;p&gt;Before you can fire up the &lt;strong&gt;Redis&lt;/strong&gt; server for the first time, you’ll need add a &lt;strong&gt;Redis&lt;/strong&gt; user and prep a data and logging folder. &lt;/p&gt;

&lt;pre class=&#34;prettyprint linenums lang-sh&#34;&gt;sudo mkdir -p /var/lib/redis
sudo mkdir -p /var/log/redis
sudo useradd --system --home-dir /var/lib/redis redis
sudo chown redis.redis /var/lib/redis
sudo chown redis.redis /var/log/redis
&lt;/pre&gt;

&lt;p&gt;Also, you need to activate your &lt;strong&gt;Redis&lt;/strong&gt; services init script by adding it to your system’s run-level configuration. That way the service will startup during the boot sequence and stop nicely during the OS’ shutdown procedure. &lt;/p&gt;

&lt;code&gt;sudo update-rc.d redis-server defaults &lt;/code&gt;

&lt;p&gt;Finally &lt;strong&gt;Start&lt;/strong&gt; &lt;/p&gt;

&lt;code&gt;sudo /etc/init.d/redis-server start&lt;/code&gt;&lt;/pre&gt;</content><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="how to" scheme="http://www.varunpant.com/topics/how-to/1" term="how to"></category><category label="redis" scheme="http://www.varunpant.com/topics/redis/1" term="redis"></category></entry><entry><title>Installing Ubuntu Linux in VMware and VMwareTools</title><link href="http://www.varunpant.com/posts/installing-ubuntu-linux-in-vmware-and-vmwaretools" rel="alternate" /><id>http://www.varunpant.com/posts/installing-ubuntu-linux-in-vmware-and-vmwaretools</id><published>2012-01-09T00:00:00z</published><updated>2012-01-09T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;I have been using Ubuntu for last two years as a deployment environment
    for my pet projects, however recently, after&amp;#160; having installed “Natty
    Narwhal” on one of my old ‘HP’ laptop I moved into using Ubuntu as a full
    time development environment.&lt;/p&gt;
&lt;p&gt;There are times when I need more than one deployment units and since I
    use
    &lt;a href=&#34;http://www.linode.com/&#34;&gt;Linode&lt;/a&gt;as my primary deployment VPS host, I sometime need to test the
    perf of my software locally thus there came a need of replicating an exact
    or close to exact “Deployment Environment”&lt;/p&gt;
&lt;p&gt;Enter
    &lt;a href=&#34;http://www.vmware.com/&#34;&gt;VmWare&lt;/a&gt;, as most of you folks know, there is nothing like a quick and
    dirty VM Image boot, and
    &lt;a href=&#34;http://www.vmware.com/&#34;&gt;VmWare&lt;/a&gt;is one of the best in the market although “
    &lt;a href=&#34;https://www.virtualbox.org/&#34;&gt;Oracle’s Virtual box&lt;/a&gt;” and
    &lt;a href=&#34;http://www.parallels.com/uk/products/desktop/&#34;&gt;“Parallels for mac&lt;/a&gt;” are pretty awesome too, there also&amp;#160; is a
    repository for pre-installed&amp;#160; vanilla images for most of the popular
    flavours of Linux
    &lt;a href=&#34;http://www.thoughtpolice.co.uk/vmware/#ubuntu11.04&#34;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The cheapest version of Linode is 512MB RAM and 20GB HD and this is exactly
    what you get when you download the image from above link, although you
    can tweak and configure it to you likings at all times.&lt;/p&gt;
&lt;p&gt;Another important step to remember is&amp;#160; installing VMware Tools .&lt;/p&gt;
&lt;p&gt;
    &lt;a name=&#34;wp1103338&#34;&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;With the VMware Tools SVGA driver installed, Workstation supports significantly
    faster graphics performance. The VMware Tools package provides support
    required for shared folders and for drag and drop operations. Other tools
    in the package support synchronization of time in the guest operating system
    with time on the host, automatic grabbing and releasing of the mouse cursor,
    copying and pasting between guest and host, and improved mouse performance
    in some guest operating systems. To install choose &lt;b&gt;VM &lt;/b&gt;&amp;gt;&lt;b&gt; Install VMware Tools&lt;/b&gt; from
    the VMware Workstation menu, although you will be automatically prompted
    when you boot you Image for the first time.&lt;/p&gt;
&lt;p&gt;If this is your first time dealing with this stuff then you may need a
    little help installing the script written in pearl, If GNOME has been your
    baby for a while, then the installed location and booting your image is
    not so obvious for the command line server interface.&lt;/p&gt;

 &lt;pre class=&#34;prettyprint linenums lang-sh&#34;&gt;

  #install kernel headers so modules will work
  #needed this on a 10.04 guest running in a Fusion 3 host
  apt-get install linux-headers-virtual

  # install kernel modules
  apt-get install --no-install-recommends open-vm-dkms

  # EITHER: install tools for an xorg install
  apt-get install open-vm-tools
  # OR: a headless install
  apt-get install --no-install-recommends open-vm-tools

 &lt;/pre&gt;


&lt;blockquote&gt;Start up a terminal window and do the following to ensure that you have
    the required packages for building VMware Tools or your kernel.&lt;/blockquote&gt;

&lt;code&gt;
	sudo apt-get install build-essential linux-headers-`uname -r` psmisc

 &lt;/code&gt;


&lt;p&gt;If the cdrom was not automatically mounted, mount the cdrom (in your guest
    OS) by doing&lt;/p&gt;
&lt;pre class=&#34;prettyprint linenums lang-sh&#34;&gt;

	# make a mount point if needed :
	sudo mkdir /media/cdrom

	# Mount the CD
	sudo mount /dev/cdrom /media/cdrom

	# Copy and extract VMWareTools

	sudo cp /media/cdrom/VMwareTools*.tar.gz /tmp

	# You can extract with archive manager, right click on the archive and extract ... or

	cd tmp

	tar xvf VMwareTools*.tar.gz

	cd vmware-tools-distrib
	sudo ./vmware-install.pl

	#You can configure the tools as root
	sudo vmware-toolbox

&lt;/pre&gt;


&lt;p&gt;Once you are done installing you can simply issue sudo shutdown –P or
    sudo init 0 and shutdown the VM safely. Have fun Vm-innnng :)&lt;/p&gt;
&lt;/strong&gt;</content><category label="linux" scheme="http://www.varunpant.com/topics/linux/1" term="linux"></category><category label="ubuntu" scheme="http://www.varunpant.com/topics/ubuntu/1" term="ubuntu"></category><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category></entry><entry><title>LIMBO Game Review</title><link href="http://www.varunpant.com/posts/limbo-game-review" rel="alternate" /><id>http://www.varunpant.com/posts/limbo-game-review</id><published>2011-10-19T00:00:00z</published><updated>2011-10-19T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;
    &lt;a href=&#34;http://varunpant.com/static/resources/limbo_psn_4.jpg&#34;&gt;
        &lt;img  class=&#34;img-polaroid&#34;
        title=&#34;limbo_psn&#34;  alt=&#34;limbo_psn&#34; src=&#34;http://varunpant.com/static/resources/limbo_psn_thumb_1.jpg&#34;
        width=&#34;90%&#34;&gt;
    &lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;LIMBO is a horrifically beautiful, monochrome or rather a gray-scale purgatory
    painted perhaps while watching Tim burton movie on the side. It was published
    initially in Jul 2010&amp;nbsp; by
    &lt;a href=&#34;http://en.wikipedia.org/wiki/Microsoft_Game_Studios&#34;&gt;Microsoft Game Studios&lt;/a&gt;(XBLA) and
    &lt;a href=&#34;http://en.wikipedia.org/wiki/Playdead&#34;&gt;Playdead&lt;/a&gt;(PSN, Windows), and then later released for Windows platform
    by
    &lt;a href=&#34;http://en.wikipedia.org/wiki/Steam_(software)&#34;&gt;Steam&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The primary character of the game is a boy, who wakes up right at the
    beginning of the game i.e while you are trying to figure out WTF is happening
    or wonder if you graphics driver (windows platform) screwed up or something,
    but there as you are fiddling with the movement buttons in keyboard you
    will see pair of bright white eyes flickering, and that’s when you start
    falling in love with the game and the care of detail added in a game which
    is totally unlike other in its league.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;LIMBO game essentially is a 2D puzzle game, the boy with a twee outline
    and messy hair ideally is in search of her sister, the games puzzle are
    master minded by Dino Patti and lead designer of
    &lt;a href=&#34;http://limbogame.org/company/&#34;&gt;PlayDead&lt;/a&gt;&amp;nbsp; Jeppe Carlsen,according to Wikipedia, Dino Patti had
    conceived this idea around 2004, and had even tried coding it in visual
    basic,he later made a video trailer to recruit a developer. They had grants
    from Nordic game program and Danish Government.&lt;/p&gt;
&lt;p&gt;Although Patti helped in the first few months with programming, he realised
    that the project was much larger than what the two of them could handle,
    and Patti developed the business around the game&#39;s expanded development&lt;/p&gt;
&lt;p&gt;	&lt;i&gt;Limbo&lt;/i&gt; was awarded both the &#34;Technical Excellence&#34; and &#34;Excellence
    in Visual Art&#34; titles at the
    &lt;a href=&#34;http://en.wikipedia.org/wiki/Independent_Games_Festival&#34;&gt;Independent Games Festival&lt;/a&gt;during the 2010
    &lt;a href=&#34;http://en.wikipedia.org/wiki/Game_Developers_Conference&#34;&gt;Game Developers Conference&lt;/a&gt;, at the 2010
    &lt;a href=&#34;http://en.wikipedia.org/wiki/Electronic_Entertainment_Expo&#34;&gt;Electronic Entertainment Expo&lt;/a&gt;—about a month before its release—&lt;i&gt;Limbo&lt;/i&gt; won
    &lt;a
    href=&#34;http://en.wikipedia.org/wiki/GameSpot&#34;&gt;GameSpot&lt;/a&gt;&#39;s &#34;Best Downloadable Game&#34;,and was nominated for several
        other &#34;Best of Show&#34; awards, including &#34;Best Platformer&#34; by
        &lt;a href=&#34;http://en.wikipedia.org/wiki/IGN&#34;&gt;IGN&lt;/a&gt;, “Most Original Game&#34; by
        &lt;a href=&#34;http://en.wikipedia.org/wiki/G4_TV&#34;&gt;G4 TV&lt;/a&gt;and &#34;Best Puzzle Game&#34; by GameSpot&amp;nbsp; The game was nominated
        as one of 32 finalists at the 2010
        &lt;a href=&#34;http://en.wikipedia.org/wiki/IndieCade&#34;&gt;IndieCade&lt;/a&gt;festival for independent developers, ultimately winning the
        &#34;Sound&#34; award.&lt;/p&gt;
&lt;p&gt;	&lt;sup&gt;&amp;nbsp;&lt;/sup&gt;

&lt;/p&gt;
&lt;p&gt;
    &lt;iframe src=&#34;http://player.vimeo.com/video/31446564?title=0&amp;amp;byline=0&amp;amp;portrait=0&#34;
    width=&#34;90%&#34;  frameborder=&#34;0&#34; webkitallowfullscreen=&#34;&#34; allowfullscreen=&#34;&#34;&gt;&lt;/iframe&gt;
&lt;/p&gt;
&lt;p&gt;
    &lt;a href=&#34;http://vimeo.com/31446564&#34;&gt;Limbo Game Play&lt;/a&gt;from
    &lt;a href=&#34;http://vimeo.com/varunpant&#34;&gt;varun pant&lt;/a&gt;on
    &lt;a href=&#34;http://vimeo.com&#34;&gt;Vimeo&lt;/a&gt;.&lt;/p&gt;
 </content><category label="animation" scheme="http://www.varunpant.com/topics/animation/1" term="animation"></category><category label="fun" scheme="http://www.varunpant.com/topics/fun/1" term="fun"></category><category label="simulation" scheme="http://www.varunpant.com/topics/simulation/1" term="simulation"></category></entry><entry><title>VPS Hosting Past and Present</title><link href="http://www.varunpant.com/posts/vps-hosting-past-and-present" rel="alternate" /><id>http://www.varunpant.com/posts/vps-hosting-past-and-present</id><published>2011-09-27T07:26:00z</published><updated>2011-09-27T07:26:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;I had been hosting this blog in the past&amp;nbsp; for an extremely competitive (read cheap) price &lt;a href=&#34;http://www.arvixe.com/asp_net_web_hosting&#34;&gt;here&lt;/a&gt; at &lt;a href=&#34;http://www.arvixe.com/&#34;&gt;Arvixe&lt;/a&gt; . I was using ASP.net based blogging software called &lt;a href=&#34;http://www.dotnetblogengine.net/&#34;&gt;BlogEngine&lt;/a&gt;. over and all I will describe my experience as pleasant. Arvixe is a great Hosting Provider, has good up time and has plans which are easy on the pocket, and does almost all the common stuff like emails and cpanel ,blah blah that other hosting provider do, but kinda does it on a low price. I was a happy blogger for an year although I could only manage close to 8 post and and few &lt;a href=&#34;http://varunpant.com/lab&#34;&gt;demos&lt;/a&gt; in that time.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;Enter &lt;a href=&#34;http://www.linode.com/&#34;&gt;Linode&lt;/a&gt;.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;Linode is a different beast than Arvixe, this baby gives you way more control than any conventional  hosting provider(shared) or a VPS provider generally gives you , and this is done by a custom made dash board panel which has a plethora of features, now Arvixe also has other plans which will end up giving you a dedicated hosting (VPS) and I bet they would be better than most others in the similar category, but Linode (a different league) is like Amazon Elastic,but only for Linux operating system like Ubuntu (debian), Fedora(centos) etc or rather dedicated for them, Linode means Linux Node anyways ;) &lt;/p&gt;  &lt;p&gt;If I quote them verbatim:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;We&#39;re a VPS hosting company built upon one simple premise: provide the best possible tools and services to those that know what they need — better hosting.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;and this is pretty true , they have many features which can be found &lt;a href=&#34;http://www.linode.com/features.cfm&#34;&gt;here&lt;/a&gt;. They also do a Getting Started video &lt;a href=&#34;http://www.linode.com/features.cfm&#34;&gt;here&lt;/a&gt;, if you still have questions look &lt;a href=&#34;http://www.linode.com/why.cfm&#34;&gt;here&lt;/a&gt; and &lt;a href=&#34;http://www.linode.com/faq.cfm&#34;&gt;here&lt;/a&gt;, they also have an Irc channel and other discussions and bulletin boards which can be reached through &lt;a href=&#34;http://www.linode.com/community/&#34;&gt;this&lt;/a&gt; page.&lt;/p&gt;  &lt;p&gt;Linode has six data &lt;a href=&#34;http://www.linode.com/avail/&#34;&gt;centers&lt;/a&gt; around the world , so one can switch between them either while setting up an account or even migrate like a hot swap later on, depending on what &lt;a href=&#34;http://www.linode.com/speedtest/&#34;&gt;speed&lt;/a&gt; they would like to get for dedicated regional customers, they do a &lt;a href=&#34;http://blog.linode.com/&#34;&gt;blog&lt;/a&gt; as well.&lt;/p&gt;  &lt;p&gt;Linode does a lotta stuff and does is good, but the bang on the buck is that they have a kinda “&lt;a href=&#34;http://library.linode.com/&#34;&gt;do it yourself library&lt;/a&gt;”, which is pretty vast, quality and covers every thing you need to know, or at least the important bits. I have lately spend hours just browsing through it, this library will have “getting started” information and stuff which you need to do to get cracking!!.&lt;/p&gt;  &lt;p&gt;By the way did I mention that since I had purchased a good(slightly expensive than earlier )&lt;a href=&#34;https://manager.linode.com/signup/#plans&#34;&gt;plan&lt;/a&gt; from them I also decided to write my own blog,I have used python and SQLite so that it stays light weight and have used WSGI . I will soon be open sourcing it at &lt;a href=&#34;https://github.com/varunpant/Message&#34;&gt;git hub&lt;/a&gt;. I used &lt;a href=&#34;http://bottlepy.org/docs/dev/&#34;&gt;Bottle.py&lt;/a&gt;, micro web-framework to build it so I will be calling the software Message, “Message in the bottle…..”, rings any silly bell anywhere ?? &lt;/p&gt;  &lt;p&gt;I wish my very best to Linode team and hope some of you linux ninjas would like to give it a try someday.&lt;/p&gt;</content><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category><category label=".net" scheme="http://www.varunpant.com/topics/net/1" term=".net"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category><category label="linode" scheme="http://www.varunpant.com/topics/linode/1" term="linode"></category></entry><entry><title>Web Sockets in HTML 5</title><link href="http://www.varunpant.com/posts/web-sockets-in-html-5" rel="alternate" /><id>http://www.varunpant.com/posts/web-sockets-in-html-5</id><published>2011-01-10T00:00:00z</published><updated>2011-01-10T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;
	HTML5 &lt;a href=&#34;http://en.wikipedia.org/wiki/WebSockets&#34; target=&#34;_blank&#34;&gt;WebSockets&lt;/a&gt;, defines a full-duplex communication channel that operates through a single socket over the web. &lt;strong&gt;WebSocket&lt;/strong&gt; is not just another incremental enhancement to conventional HTTP communications, it represents a large advance, especially for real-time, &lt;a href=&#34;http://en.wikipedia.org/wiki/Event-driven_programming&#34; target=&#34;_blank&#34;&gt;event driven&lt;/a&gt; web applications.
&lt;/p&gt;
&lt;p&gt;
	Normally when a browser visits a web page, an HTTP request is sent to the web server that hosts that page. The web server acknowledges this request and sends back the response. In many cases—for example, for stock prices, news reports, ticket sales, traffic patterns, medical device readings, and so on—the response could be stale by the time the browser renders the page.
&lt;/p&gt;
&lt;p&gt;
	Current attempts to provide real-time web applications largely revolve around polling and other server-side push technologies, the most notable of which is &#34;&lt;a href=&#34;http://en.wikipedia.org/wiki/Comet_(programming)&#34; target=&#34;_blank&#34;&gt;Comet&lt;/a&gt;&#34;, which delays the completion of an HTTP response to deliver messages to the client.
&lt;/p&gt;
&lt;p&gt;
	There are many open source implementation of Http Push, one of my personal favorite is &lt;a href=&#34;http://www.ape-project.org/&#34; target=&#34;_blank&#34;&gt;APE&lt;/a&gt; i.e. Ajax Push Engine.
&lt;/p&gt;
&lt;blockquote&gt;
	&lt;p&gt;
		&lt;strong&gt;&lt;span style=&#34;text-decoration: underline;&#34;&gt;Update&lt;/span&gt;&lt;/strong&gt;: Microsoft has added a small demo of HTML5 support , it comes as an extension to WCF (Windows communication foundation) .The links can be found &lt;a href=&#34;http://connect.microsoft.com/VisualStudio/feedback/details/520742/use-of-html-5-web-sockets-for-wcf-duplex-services-and-silverlight&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;, &lt;a href=&#34;http://html5labs.interoperabilitybridges.com/media/1165/readme.htm&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt; and &lt;a href=&#34;http://msdn.microsoft.com/en-us/magazine/ee309879.aspx&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;.
	&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;
	There is still no news of Microsoft adding this feature in IE 9, at the time of writing this post, only Firefox 4, Chrome 4, Safari 5 and Opera 11 and above have support for this feature.
&lt;/p&gt;
&lt;blockquote&gt;
	&lt;p&gt;
		&lt;strong&gt;&lt;span style=&#34;text-decoration: underline;&#34;&gt;Update&lt;/span&gt;&lt;/strong&gt;: Due to security flaw Firefox and Opera have disabled their support for Web Sockets, more info can be found &lt;a href=&#34;http://www.webmonkey.com/2010/12/security-flaws-force-firefox-opera-to-turn-off-websockets/&#34; target=&#34;_blank&#34;&gt;here&lt;/a&gt;.
	&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;
	For those interested here is the &lt;a href=&#34;http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-03&#34; target=&#34;_blank&#34;&gt;draft&lt;/a&gt; , official &lt;a href=&#34;http://websocket.org/&#34; target=&#34;_blank&#34;&gt;website&lt;/a&gt;, the &lt;a href=&#34;http://dev.w3.org/html5/websockets/&#34; target=&#34;_blank&#34;&gt;API&lt;/a&gt; and a nice &lt;a href=&#34;http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/&#34; target=&#34;_blank&#34;&gt;tutorial&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
	To establish a WebSocket connection, the client and server upgrade from the HTTP protocol to the WebSocket protocol during their initial handshake, as shown in below, note that this connection description represents draft 76 of the protocol, the connection handshake may change during future specification revisions.
&lt;/p&gt;
&lt;blockquote&gt;
	&lt;p&gt;
		&lt;strong&gt;&lt;span style=&#34;text-decoration: underline;&#34;&gt;From client to server&lt;/span&gt;: &lt;br&gt;
		&lt;/strong&gt;GET /demo HTTP/1.1 &lt;br&gt;
		Host: example.com &lt;br&gt;
		Connection: Upgrade &lt;br&gt;
		Sec-WebSocket-Key2: 12998 5 Y3 1 .P00 &lt;br&gt;
		Sec-WebSocket-Protocol: sample &lt;br&gt;
		Upgrade: WebSocket &lt;br&gt;
		Sec-WebSocket-Key1: 4@1 46546xW%0l 1 5 &lt;br&gt;
		Origin: &lt;a href=&#34;http://example.com&#34;&gt;http://example.com&lt;/a&gt;&lt;br&gt;
		[8-byte security key]
	&lt;/p&gt;
	&lt;p&gt;
		&lt;br&gt;
		&lt;strong&gt;&lt;span style=&#34;text-decoration: underline;&#34;&gt;From server to client&lt;/span&gt;&lt;/strong&gt;: &lt;br&gt;
		HTTP/1.1 101 WebSocket Protocol Handshake &lt;br&gt;
		Upgrade: WebSocket &lt;br&gt;
		Connection: Upgrade &lt;br&gt;
		WebSocket-Origin: &lt;a href=&#34;http://example.com&#34;&gt;http://example.com&lt;/a&gt;&lt;br&gt;
		WebSocket-Location: ws://example.com/demo &lt;br&gt;
		WebSocket-Protocol: sample &lt;br&gt;
		[16-byte hash response]
	&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;
	I was trying to find an alternative which is comfortable enough to be used in my pet projects in Microsoft Tech stack, at the time of writing I couldn’t any so I here it is my very own HTTP Web Socket server written in .Net via C#, this implementation does not use WCF and is basically written using HTTP Async Sockets, the client API is pretty straight forward
&lt;/p&gt;


&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
var url = &#34;ws://localhost:999&amp;amp;rdquo&#34;
var sock = new WebSocket(url);
sock.onopen = function () {
    log(&#34;open&#34;);
    sock.send(&#34;Message….&#34;);
}
sock.onmessage = function (e) {
    log(e.data);
}
sock.onclose = function (e) {
    log(&#34; closed&#34;);
}
&lt;/pre&gt;


&lt;p&gt;
	and that&#39;s it!!!
	I plan to add some more examples and perhaps come with something more concrete later, till then I hope you enjoy using this code sample and enhancing it as you desire.
&lt;/p&gt;
&lt;a href=&#34;http://www.varunpant.com/demo/WebSocketServer.rar&#34; rel=&#34;nofollow&#34; class=&#34;btn&#34;&gt;A complete example in c# can be downloaded from here &lt;i class=&#34;icon-download-alt&#34;&gt;&lt;/i&gt;&lt;/a&gt;</content><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="websockets" scheme="http://www.varunpant.com/topics/websockets/1" term="websockets"></category><category label="httppush" scheme="http://www.varunpant.com/topics/httppush/1" term="httppush"></category><category label=".net" scheme="http://www.varunpant.com/topics/net/1" term=".net"></category><category label="javascript" scheme="http://www.varunpant.com/topics/javascript/1" term="javascript"></category></entry><entry><title>Water Simulation</title><link href="http://www.varunpant.com/posts/water-simulation" rel="alternate" /><id>http://www.varunpant.com/posts/water-simulation</id><published>2010-09-25T00:00:00z</published><updated>2010-09-25T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;Its been a while since my last post, had been busy with office work…sigh!!!&lt;/p&gt;
&lt;p&gt;Anyways, I was poking around web to come up with interesting water simulation techniques, as you could see in many games these days, so I did find a reference to an old C-based technique, after little refinement, what I have is a water simulation which uses a very old algorithm based on two &lt;a href=&#34;http://en.wikipedia.org/wiki/Heightmap&#34; target=&#34;_blank&#34;&gt;heightmaps&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;As always it’s a&amp;nbsp; grid based animation which divides the screen into&amp;nbsp; a mesh(more slices better this simulation looks), I use a jagged array in c# to do this (load it with a texture of 640 X 480 dimension ), to animate I use another array of same dimensions, now to make every thing move I kinda do something like this&lt;/p&gt;

        &lt;pre class=&#34;prettyprint linenums lang-java&#34;&gt;
               for (int y = 1; y &amp;lt; 479; y++) {
                    for (int x = 1; x &amp;lt; 639; x++) {
                        this.currentState[x, y] = ((this.oldState[(x - 1), y] + this.oldState[(x + 1), y] + this.oldState[x, (y + 1)] + this.oldState[x, (y - 1)] &amp;gt;&amp;gt; 1) - this.currentState[x, y]);
                        this.currentState[x, y] -= (this.currentState[x, y] &amp;gt;&amp;gt; 7);
                        int data = (short)(1024 - this.currentState[x, y]);
                        int a = (x - 640) * data / 1024 + 640;
                        int b = (y - 480) * data / 1024 + 480;
                        if (a &amp;gt;= 640) a = 639;
                        if (a &amp;lt; 0) a = 0;
                        if (b &amp;gt;= 480) b = 479;
                        if (b &amp;lt; 0) b = 0;
                        int textOffset = x + y * 640;
                        bmp.Pixels[textOffset] = texture[(a + b * 640)];
                    }
                }

        &lt;/pre&gt;

&lt;p&gt;The choice of display entity(acting as viewport and display canvas) is &lt;a href=&#34;http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx&#34; target=&#34;_blank&#34;&gt;WritableBitmap&lt;/a&gt;,&amp;nbsp; and rest is pretty much fun to play.&lt;/p&gt;


&lt;a href=&#34;http://varunpant.com/static/resources/Silverlight/water.html&#34; class=&#34;btn&#34;&gt;Click here to watch demo &lt;i class=&#34;icon-download-alt&#34;&gt;&lt;/i&gt;&lt;/a&gt;
&lt;/br&gt;
&lt;p class=&#34;well&#34;&gt;
&lt;object width=&#34;98%&#34; height=&#34;300px&#34; type=&#34;application/x-silverlight-2&#34; data=&#34;data:application/x-oleobject;base64,QfXq3+HzJEysrJnDBxUISgAJAADYEwAA2BMAAAwAAAB3AGgAaQB0AGUAAAAAAAAAAAAAAAAAAABkAAAAaAB0AHQAcAA6AC8ALwB2AGEAcgB1AG4AcABhAG4AdAAuAGMAbwBtAC8AZABlAG0AbwAvAFMAaQBsAHYAZQByAGwAaQBnAGgAdAAvAEYAbAB1AGkAZABlAGUALgB4AGEAcAAAADwAAAAAAAAAJgAAAG8AbgBTAGkAbAB2AGUAcgBsAGkAZwBoAHQARQByAHIAbwByAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAABAAAAAAAAAAAAAAAAAAAAGAAAADQALgAwAC4ANQAwADgAMgA2AC4AMAAAAAoAAAB0AHIAdQBlAAAAAAAAAAAAAAAAAAAA&#34;&gt;
&lt;param name=&#34;source&#34; value=&#34;http://varunpant.com/static/resources/Silverlight/Fluidee.xap&#34;&gt;
&lt;param name=&#34;onError&#34; value=&#34;onSilverlightError&#34;&gt;
&lt;param name=&#34;background&#34; value=&#34;white&#34;&gt;
&lt;param name=&#34;minRuntimeVersion&#34; value=&#34;4.0.50826.0&#34;&gt;
&lt;param name=&#34;autoUpgrade&#34; value=&#34;true&#34;&gt;
&lt;/object&gt;
&lt;/p&gt;</content><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="silverlight" scheme="http://www.varunpant.com/topics/silverlight/1" term="silverlight"></category><category label="animation" scheme="http://www.varunpant.com/topics/animation/1" term="animation"></category><category label="simulation" scheme="http://www.varunpant.com/topics/simulation/1" term="simulation"></category><category label="water" scheme="http://www.varunpant.com/topics/water/1" term="water"></category></entry><entry><title>Liquid Particles</title><link href="http://www.varunpant.com/posts/liquid-particles" rel="alternate" /><id>http://www.varunpant.com/posts/liquid-particles</id><published>2010-07-03T00:00:00z</published><updated>2010-07-03T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;After ages of constantly being one of the most used browser as well as a serious pain in Butt!!! IE is finally about to mature into something good and perhaps a useful software , with its support to &lt;a href=&#34;http://www.quirksmode.org/blog/archives/2010/06/more_ie9_goodne.html&#34; target=&#34;_blank&#34;&gt;most&lt;/a&gt; of the standards being used today , IE will join back the league of web 3.0 browsers, hopefully very soon&lt;/p&gt;
&lt;p&gt;So I was going through various experiments done with Canvas and came across a great example on &lt;a href=&#34;http://spielzeugz.de/html5/liquid-particles.html&#34; target=&#34;_blank&#34;&gt;Liquid Particle physics simulation&lt;/a&gt;, which amazingly is written in JavaScript and Canvas element, I was so mesmerized by the application that I had to port it to &lt;a href=&#34;http://msdn.microsoft.com/en-us/bb187358.aspx&#34; target=&#34;_blank&#34;&gt;SilverLight&lt;/a&gt;, using &lt;a href=&#34;http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx&#34; target=&#34;_blank&#34;&gt;WritableBitmap&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://www.varunpant.com/static/resources/lqdPrticle.png&#34;&gt;
&lt;img title=&#34;Liquid Particle&#34; src=&#34;http://www.varunpant.com/static/resources/lqdPrticle_thumb.png&#34; alt=&#34;Liquid Particle&#34; width=&#34;80%&#34; &gt;&lt;/a&gt;&lt;/p&gt;

&lt;a href=&#34;http://varunpant.com/static/resources/ParticlesSilverLight.html&#34; class=&#34;btn&#34;&gt;Click Here to watch Demo. &lt;i class=&#34;icon-download-alt&#34;&gt;&lt;/i&gt;&lt;/a&gt;</content><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="fun" scheme="http://www.varunpant.com/topics/fun/1" term="fun"></category><category label="silverlight" scheme="http://www.varunpant.com/topics/silverlight/1" term="silverlight"></category><category label="html5" scheme="http://www.varunpant.com/topics/html5/1" term="html5"></category><category label="particles" scheme="http://www.varunpant.com/topics/particles/1" term="particles"></category><category label="simulation" scheme="http://www.varunpant.com/topics/simulation/1" term="simulation"></category></entry><entry><title>Image Carousel</title><link href="http://www.varunpant.com/posts/image-carousel" rel="alternate" /><id>http://www.varunpant.com/posts/image-carousel</id><published>2010-06-29T00:00:00z</published><updated>2010-06-29T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;Here is another of many JavaScript based Image Carousel, I had seen many similar to these made in SilverLight and Flash, I came across a wonderful &lt;a href=&#34;http://www.shinedraw.com/animation-effect/flash-vs-silverlight-image-carousel/&#34; target=&#34;_blank&#34;&gt;carousel&lt;/a&gt; made in SilverLight sometimes back which was very fluid in behavior and could easily be customized and configured to take various shape and form.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://www.varunpant.com/static/resources/carousel.png&#34;&gt;&lt;img title=&#34;carousel&#34; src=&#34;http://www.varunpant.com/static/resources/carousel_thumb.png&#34; alt=&#34;carousel&#34; width=&#34;90%&#34; &gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;I have managed to port it to JavaScript, it works best on chrome or FF, hope this would be fun to play with.&lt;/p&gt;
&lt;p&gt;Enjoy!!!&lt;/p&gt;
&lt;a href=&#34;http://varunpant.com/static/resources/Carousel.html&#34; class=&#34;btn&#34;&gt;Click here to watch it in action &lt;i class=&#34;icon-download-alt&#34;&gt;&lt;/i&gt;&lt;/a&gt;</content><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="fun" scheme="http://www.varunpant.com/topics/fun/1" term="fun"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="javascript" scheme="http://www.varunpant.com/topics/javascript/1" term="javascript"></category><category label="carousel" scheme="http://www.varunpant.com/topics/carousel/1" term="carousel"></category><category label="fluid" scheme="http://www.varunpant.com/topics/fluid/1" term="fluid"></category><category label="css" scheme="http://www.varunpant.com/topics/css/1" term="css"></category></entry><entry><title>I-Phone Scroll</title><link href="http://www.varunpant.com/posts/i-phone-scroll" rel="alternate" /><id>http://www.varunpant.com/posts/i-phone-scroll</id><published>2010-06-18T00:00:00z</published><updated>2010-06-18T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;One of the amazing features of i-phone user interface is smooth panning/scrolling animation.&lt;/p&gt;
&lt;p&gt;I-phone “List Scrolling” perhaps gives a very funky and usable List –View to its users and allows them to scroll up and down the interface without any need of a scroll bar.&lt;/p&gt;
&lt;p&gt;This interface is&amp;nbsp; sensitive to the push speed and also shows traces of resilience.&lt;/p&gt;
&lt;p&gt;I have been experimenting with various techniques to bring out similar effect using JavaScript and HTML, I am not quite sure if this would be useful in its present form but with some modifications may be this sample could prove its worthiness somewhere.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://www.varunpant.com/static/resources/iphone_1.png&#34;&gt;&lt;img title=&#34;iphone&#34; src=&#34;http://www.varunpant.com/static/resources/iphone_thumb_1.png&#34; alt=&#34;iphone&#34; width=&#34;164&#34; height=&#34;244&#34;&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;The code involved is also very little.&lt;/p&gt;

   &lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
    var scroll = {
    down: false,
    verticalOffset: -5,
    ym: 0,
    decay: .93,
    mdDecay: 0.27,
    speedOffset: 0.4,
    sprinessOffset: 0.08,
    _velocity: 0,
    _mouseDownY: 0,
    $: function (id) {
        return document.getElementById(id);
    },
    /* --- events --- */
    addEvent: function (o, e, f) {
        if (window.addEventListener) o.addEventListener(e, f, false);
        else if (window.attachEvent) r = o.attachEvent(&#39;on&#39; + e, f);
    },
    init: function () {
        setInterval(scroll.compositiontarget_rendering, 30);

        scroll.verticalOffset = scroll.$(&#39;scrollMe&#39;).offsetTop;

        scroll.addEvent(scroll.$(&#39;scrollMe&#39;), &#39;mousedown&#39;, function (e) {
            scroll.$(&#39;scrollMe&#39;).style.cursor = &#39;move&#39;;
            if (!scroll.down) {
                scroll.down = true;
                scroll.ym = e.clientY;
                scroll._mouseDownY = scroll.$(&#39;scrollMe&#39;).offsetTop;
            }

            if (e.preventDefault) e.preventDefault();
        });

        scroll.addEvent(scroll.$(&#39;scrollMe&#39;), &#39;mouseup&#39;, function () {
            scroll.down = false;
            scroll.$(&#39;scrollMe&#39;).style.cursor = &#39;default&#39;;

        });


        scroll.addEvent(scroll.$(&#39;scrollMe&#39;), &#39;mousemove&#39;, function (e) {
            if (scroll.down) {
                if (scroll.canScrollFurther()) scroll.$(&#39;scrollMe&#39;).style.top = (scroll._mouseDownY + (e.clientY - scroll.ym)) + &#39;px&#39;;
                // update the velocity
                scroll._velocity += ((e.clientY - scroll.ym) * scroll.speedOffset);
            }

        });

        document.onselectstart = function () {
            return false;
        }
    },
    compositiontarget_rendering: function () {
        // decay the velocity
        if (scroll.down) {
            scroll._velocity *= scroll.mdDecay;
        } else {
            scroll._velocity *= scroll.decay;

            var screenHeight = scroll.$(&#39;screen&#39;).offsetHeight;
            var scrolRegionHeight = scroll.$(&#39;scrollMe&#39;).offsetHeight;

            var y = scroll.$(&#39;scrollMe&#39;).offsetTop - scroll.verticalOffset;
            var spriness = 0;

            // calculate a spriness when the text moves over the canvas size
            if (y &amp;gt; 0) {
                spriness = -y * scroll.sprinessOffset;
            } else if (y + scrolRegionHeight &amp;lt; screenHeight) {
                spriness = ((screenHeight - scrolRegionHeight - y) * scroll.sprinessOffset);
            }
            if (!scroll.canScrollFurther()) {
                scroll._velocity = -(scroll._velocity / 8)
            }
            scroll.$(&#39;scrollMe&#39;).style.top = (y + scroll._velocity + spriness) + &#39;px&#39;;
        }


    },
    canScrollFurther: function () {
        var _top = scroll.$(&#39;scrollMe&#39;).offsetTop;
        var bottom = _top + scroll.$(&#39;scrollMe&#39;).offsetHeight;
        var center = (scroll.$(&#39;screen&#39;).offsetTop + scroll.$(&#39;screen&#39;).offsetHeight) / 2;
        return (_top &amp;lt; center &amp;amp;&amp;amp; bottom &amp;gt; center);
    }
};

    &lt;/pre&gt;
&lt;/figure&gt;
&lt;a href=&#34;http://varunpant.com/static/resources/Demo.html&#34; class=&#34;btn&#34;&gt;Click here to watch demo&lt;br&gt; &lt;i class=&#34;icon-download-alt&#34;&gt;&lt;/i&gt;&lt;/a&gt;</content><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="fun" scheme="http://www.varunpant.com/topics/fun/1" term="fun"></category><category label="iphone scroll" scheme="http://www.varunpant.com/topics/iphone-scroll/1" term="iphone scroll"></category><category label="javascript" scheme="http://www.varunpant.com/topics/javascript/1" term="javascript"></category><category label="animation" scheme="http://www.varunpant.com/topics/animation/1" term="animation"></category></entry><entry><title>Data URI and IE</title><link href="http://www.varunpant.com/posts/data-uri-and-ie" rel="alternate" /><id>http://www.varunpant.com/posts/data-uri-and-ie</id><published>2010-06-15T00:00:00z</published><updated>2010-06-15T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;Few days ago I was experimenting with a nifty technique of embedding images
    in web pages by base64 encoding them first and then using&amp;nbsp; a standard
    known as
    &lt;a href=&#34;http://en.wikipedia.org/wiki/Data_URI_scheme&#34; target=&#34;_blank&#34;&gt;Data URI Scheme&lt;/a&gt;, which basically defines a method of assigning a &amp;lsquo;src&amp;rsquo;
    of an image tag as a base64 serialized string, like this:&lt;/p&gt; &lt;pre class=&#34;prettyprint linenums lang-c#&#34;&gt;

background - image: url(&#34;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAUBAMAAACKWYuOAAAAMFBMVEX///92dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnYvD4PNAAAAD3RSTlMAACTkfhvbh3iEewTtxBIFliR3AAAAUklEQVQY02NgIBMwijgKCgrAef5fkHnz/y9E4kn+/4XEE6z/34jEE///A4knev7zAwQv7L8RQk40/7MiggeUQpjJff+zIpINykbIbhFSROIRDQAWUhW2oXLWAQAAAABJRU5ErkJggg==&#34;);

    &lt;/pre&gt;

&lt;p&gt;Although this technique could save some server round trips, however Microsoft
    ver. (IE &amp;lt; 8). does not support this scheme even though its a
    &lt;a href=&#34;http://tools.ietf.org/html/rfc2397&#34;
    target=&#34;_blank&#34;&gt;standard&lt;/a&gt;, which then makes this technique unfavorable to use as its
    not cross browser.&lt;/p&gt;
&lt;p&gt;I was trying to find a work around and came across
    &lt;a href=&#34;http://www.phpied.com/mhtml-when-you-need-data-uris-in-ie7-and-under/&#34;
    target=&#34;_blank&#34;&gt;MHTML hack&lt;/a&gt;which is not an elegant approach especially for dynamic
    solutions and is also not supported by Microsoft any more.&lt;/p&gt;
&lt;p&gt;I found an interesting
    &lt;a href=&#34;http://dean.edwards.name/weblog/2005/06/base64-ie/&#34;
    target=&#34;_blank&#34;&gt;article&lt;/a&gt;by Dean Edwards, which suggested in IE &amp;lt;8 scenarios a request
    could be send back with base64 encoded data as a query string to server,
    where a server module would then de-serialize the image and write it back
    in response:&lt;/p&gt;
&lt;p&gt;Client Side:&lt;/p&gt;
&lt;pre class=&#34;prettyprint linenums lang-javascript&#34;&gt;
function urlEncode(str) {
    str = escape(str);
    str = str.replace(new RegExp(&#39;\\+&#39;, &#39;g&#39;), &#39;%2B&#39;);

    return str.replace(new RegExp(&#39;%20&#39;, &#39;g&#39;), &#39;+&#39;);
}

function assign() {
    document.getElementById(&#34;img1&#34;).src = &#34;Handler.ashx?q=&#34; + urlEncode(&#34;iVBORw0KGgoAAAANSUhEUgAAABkAAAAUBAMAAACKWYuOAAAAMFBMVEX///92dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnZ2dnYvD4PNAAAAD3RSTlMAACTkfhvbh3iEewTtxBIFliR3AAAAUklEQVQY02NgIBMwijgKCgrAef5fkHnz/y9E4kn+/4XEE6z/34jEE///A4knev7zAwQv7L8RQk40/7MiggeUQpjJff+zIpINykbIbhFSROIRDQAWUhW2oXLWAQAAAABJRU5ErkJggg==&#34;);
}
    &lt;/pre&gt;

&lt;p&gt;and on the server side one can use a generic http Handler like this&lt;/p&gt;
&lt;pre
class=&#34;prettyprint linenums lang-c#&#34;&gt;public class Handler: IHttpHandler { public void ProcessRequest(HttpContext
    context) { context.Response.ContentType = &#34;image/gif&#34;; try { string data
    = context.Request.QueryString[&#34;q&#34;]; byte[] todecode_byte = Convert.FromBase64String(data);
    context.Response.BinaryWrite(todecode_byte); } catch (Exception e) { //Log
    } } }&lt;/pre&gt;
    &lt;p&gt;The only thing to note here is to URLEncode the string before sending
        it to avoid &lt;em&gt;FormatException&lt;/em&gt; .&lt;/p&gt;
    &lt;p&gt;This is not by any means an elegant solution and will work only for small
        images, as bigger images will serialize into large string chunks and browsers
        limits urls to 2083 characters, but I just thought writing a c# version
        of this approach would be interesting. :)&lt;/p&gt;</content><category label="programming" scheme="http://www.varunpant.com/topics/programming/1" term="programming"></category><category label="utility" scheme="http://www.varunpant.com/topics/utility/1" term="utility"></category><category label="web" scheme="http://www.varunpant.com/topics/web/1" term="web"></category><category label="data uri" scheme="http://www.varunpant.com/topics/data-uri/1" term="data uri"></category><category label=".net" scheme="http://www.varunpant.com/topics/net/1" term=".net"></category></entry><entry><title>Notepad++ with Python</title><link href="http://www.varunpant.com/posts/notepad-with-python" rel="alternate" /><id>http://www.varunpant.com/posts/notepad-with-python</id><published>2010-06-15T00:00:00z</published><updated>2010-06-15T00:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;After reading an excellent article by
    &lt;a href=&#34;http://weblogs.asp.net/rashid/&#34;
    target=&#34;_blank&#34;&gt;Kazi Manzur Rashid&lt;/a&gt;on setting up a development environment for Iron
    Ruby using
    &lt;a href=&#34;http://notepad-plus-plus.org/&#34; target=&#34;_blank&#34;&gt;Notepad++&lt;/a&gt;, I was immediately struck with an idea of using the same
    excellent tool with Python 2.6.&lt;/p&gt;
&lt;p&gt;Now don&amp;rsquo;t get me wrong here, theoretically there is nothing wrong
    with IDLE, but having a light weight IDE for those who don&amp;rsquo;t want
    to use
    &lt;a href=&#34;http://pydev.org/&#34; target=&#34;_blank&#34;&gt;Pydev&lt;/a&gt;plugin for
    &lt;a href=&#34;http://www.aptana.com/&#34; target=&#34;_blank&#34;&gt;Aptana&lt;/a&gt;or
    &lt;a href=&#34;http://www.eclipse.org/&#34; target=&#34;_blank&#34;&gt;Eclipse&lt;/a&gt;, I think Notepad++ is indeed a nice little dev tool.&lt;/p&gt;
&lt;p&gt;One of the amazing capabilities in Notepad++ is that one can assign shortcuts
    like(Cntrl + F5) and debug/interpret python script with python interpreter.&lt;/p&gt;
&lt;p&gt;In order to Run python script from Run menu in Notepad++ you must Open
    Run &amp;gt; Run (or simply press F5), in the window that opens&lt;/p&gt;
&lt;p&gt;&amp;nbsp;
    &lt;a href=&#34;http://www.varunpant.com/static/resources/notepad_Run.png&#34;&gt;
        &lt;img title=&#34;notepad_Run&#34; src=&#34;http://www.varunpant.com/static/resources/notepad_Run_thumb.png&#34;
        alt=&#34;notepad_Run&#34; width=&#34;400&#34; height=&#34;279&#34; /&gt;
    &lt;/a&gt;
&lt;/p&gt;

        &lt;code &gt;
           cmd /K &#34;$(FULL_CURRENT_PATH)&#34;
        &lt;/code&gt;

&lt;p&gt;this command assumes that Python path i.e.&lt;/p&gt;

        &lt;code &gt;
           c:/PythonXX/Python.exe
        &lt;/code&gt;

&lt;p&gt;or&lt;/p&gt;

        &lt;code &gt;
          c:/PythonXX/Pythonw.exe
        &lt;/code&gt;

&lt;p&gt;(If you don&amp;rsquo;t like console) is added in your Environment variables
    , if not you couldeither go to:&lt;/p&gt;

        &lt;code class=&#34;brush: javascript language-javascript&#34;&gt;
          My Computer -&amp;gt; Properties -&amp;gt; Advanced -&amp;gt; Environment Variables -&amp;gt; System Variables -&amp;gt; PATH &amp;ndash;&amp;gt; Edit
        &lt;/code&gt;


&lt;p&gt;and add this path there or use&lt;/p&gt;

        &lt;code &gt;
         cmd /k C:\Python26\python.exe
        &lt;/code&gt;

&lt;p&gt;then press save after putting in a friendly name and assigning a key board
    shortcut for example CNTRL + F5.&lt;/p&gt;
&lt;p&gt;You could now see your entry in Run drop down menu at the last, incase
    you want to edit or remove this go to Settings&amp;gt;Shortcut mapper and press
    Run Commands tab and then right click to choose options from context menu
    and your all set.&lt;/p&gt;
&lt;p&gt;Hope this helps :)&lt;/p&gt;</content><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category><category label="fun" scheme="http://www.varunpant.com/topics/fun/1" term="fun"></category><category label="python" scheme="http://www.varunpant.com/topics/python/1" term="python"></category><category label="notepad++" scheme="http://www.varunpant.com/topics/notepad/1" term="notepad++"></category></entry><entry><title>Hello World!</title><link href="http://www.varunpant.com/posts/hello-world" rel="alternate" /><id>http://www.varunpant.com/posts/hello-world</id><published>2010-06-12T18:00:00z</published><updated>2010-06-12T18:00:00z</updated><author><name>admin</name></author><content type="html">&lt;p&gt;After&amp;nbsp; long period of wait, here it is my very first and personal Blogging Space.&lt;/p&gt;
&lt;p&gt;I have been hoping to go online for about an year now, but then there always were events happening around to prevent this immense desire of mine.&lt;/p&gt;
&lt;p&gt;I intend to blog about .net in general , JavaScript, Silverlight, Animation and maybe some other cool stuff .&lt;/p&gt;
&lt;p&gt;Hope to update this space again.&lt;/p&gt;
&lt;p&gt;Cheers!!!&lt;/p&gt;
&lt;p&gt;-- Varun&lt;/p&gt;</content><category label="general" scheme="http://www.varunpant.com/topics/general/1" term="general"></category></entry></feed>