Posts

Showing posts from 2015

Determining image file size in Javascript

After a lot of googling and searching, I realized the best way to do this is to create a service call to the backend witht he url of the image whose size needs to be figured out. This service should make a HEAD call to the server to get the content - length. And pass it along as a response. Not all servers support HEAD calls so as a fallback make a GET call to the get the request and determine the file size from the headers. We need to set few headers for this to work universally. One of them is user-agent. Code for the same is : private void makeRequest( @FormParam ( "url" ) String url, Map response, String requestMethod) { try { HttpURLConnection urlCon = (HttpURLConnection) new URL(url).openConnection(); urlCon.setRequestMethod(requestMethod); urlCon.setRequestProperty( "User-Agent" , "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" ); //urlCon.setDoOutput

Most expensive product on Amazon India By Category

Image
Amazon India today has become the most visited e-commerce site in India. So, I decided to analyze the most expensive products that Amazon India Sells across various category. So lets start. Book worth Rs 53,46,000.00 This is quiet modest. I think its a must in every library! DVD worth Rs 40,045.23 My kids are gonna die uneducated :( A Flip Cover worth Rs 255,255.00 I would get around 40 actual Micromax Juice phone at the same price. A pen worth Rs 1,700,000.00 "No doubt a pen is mightier (worthier) then a sword" Telescope worth Rs 896,000.00 This might actually be a fair price. Should understand technical part of it to comment. Help! Spoons worth Rs 2,183,731.00 I might by a house with a kitchen at the same price. Though each spoon would just cost you mere 33,000. Thats a relief! A Game worth Rs 868,434.00 That might be correct again, with import duty on all. I don't know. MultiGym worth Rs 2,950,000

Fixing Deployment.AddInAlreadyInstalledException.

Image
If you are building any VSTO for any of the office applications, then its quite common to run into this issue. The error message would say that "The customization cannot be installed because another version is currently installed and cannot be upgraded from this location. To install this version of the customization, first use Add or Remove Programs to uninstall this program: TestUpdatedVersion. Then install the new customization from the following location: file:///D:/Samples/TestUpdatedVersion/bin/Debug/TestUpdatedVersion.vsto ********** Exception Text ********** Microsoft.VisualStudio.Tools.Applications.Deployment.AddInAlreadyInstalledException: The customization cannot be installed because another version is currently installed and cannot be upgraded from this location. To install this version of the customization, first use Add or Remove Programs to uninstall this program: TestUpdatedVersion. Then install the new customization from the following location: file:/

Buy Gobar Online on Amazon.

Image
Ever wanted to gift someone Gobar? Now you can. Just follow the link below!   Buy Now! And suppose if you dont wanto buy Cow Dung Cake, then you can also get it in powder form here:

One Plus X invite Finder

Image
Lots of people are looking for one plus X invite so I decided to write a crawler to scrape it. Use this buy link to test your invite. I would keep on updating new invites here and would request people to add invite in the comment section.           Buy Here. Another invite at  https://invites.oneplus.net/claim/IN11-AD09-16B0-E083

Visual Studio Quirks

Image
On clicking debug in Visual Studio, it gives "The debugger cannot continue running the process. Unable to start debugging" The problem here is that no project is selected as default startup project. You would need to right click a project which is start up project and select "Set as start-up project".

How to access banned sites in India?

Today lots of ISP's have banned tonnes of site in India. But they can still be accessed. There are various options to do that: 1) If its a page without media, video content, then search it on google, press the down arrow below the search result, and select cached. This would display the cached result of the page as stored in google. 2) Use a set of proxy server from here . 3) Go to https://www.proxysite.com/ and start accessing websites from there. Happy Surfing!

Ubuntu DNS error on Virtualbox

Quite often on my Guest Ubuntu system on virtual box, I face this problem, where network is accessible via IP but not my domain name. I am able to ping any IP but DNS resolution fails. In those scenarios I have found the following command quite useful: sudo dpkg-reconfigure resolvconf This resets/regenrates the resolv.conf and everything is back to normal :)

How to free up space on Windows?

Image
I have been facing this problem where entire of my drive C had always been full, though it was having almost 50 GB, and no content apart from windows and program files. I have tried disk clean up and  disk clean up with system files with no effect. Finally to solve it, I went to I changed the attributed of the files on my drive C: Write click on Drive C and click properties. In properties, select "Compress drive to save disk space" and unselect "Allow files on the drive to have contents indexed in addition to file properties". Press Apply. The process with take a couple of hours on my SSD drive. and Hola, I had ann extra 7GB of space. Other Techniques: Reduce the amount of space system restore takes. To do so go to system restore settings in control panel. Reduce the amount of space hibernate files take. Run command prompt as administrator and execute  Powercfg.exe /hibernate /size 50 .   Additionally, switch off fast boot up /start up in

Promises vs EventEmitters vs Callbacks

There is a lot of material online about these and I would try to keep it short and sweet to explain what is my current understanding of these. Promises are syntax to implement callbacks, so lets get rid of callback from the proportions. Now we are left with Promises vs EventEmitters . Internally or performance wise all are quite similar. So based on coding practices these are my observations: Promise : Promise are good abstraction of asynchronous commands which will happen in given amount of time. Making a db query is a promise, making a rest cal is a promise. Your code needs to wait for promise to be fulfilled. Lets give it an analogy,  a cab driver promises to come to pick you up at 6AM and when he fulfills the promise, you promise him to sit in the cab and reach office. I know analogy is little lame, but hope it explains the idea. EventEmitters : EventEmitters are used for truely async events, like someone clicked on a particular button on a page, or while operating

Linkedin Status Update Image not displayed

I was facing this problem when I was updating images from my site on linkedin. I even asked a question on stackoverflow ( When using linkedin share api submitted-picture-url or sharing url via linkedin, particular url format doesnot work? ) but never got a good response. After that I did lots of experimentation to figure out few things about linkedin in status update image url. I would list them out below: Max size for image should be 100 MB (read somewhere, have not tried it myself.) Linkedin caches the images on its server for 7 days. So if the image on the url shared have changed, linkedin won't update it. A good workaround is to add a query parameter to the image url with some random string of the timestamp while sharing. So, this would make each image url unique. Set the correct mime-type on the servlet serving the image. I was using cdn and with my servlet acting at a proxy to cdn to serve the image. In the process I was missing out the mime-type in the response head

Email Validation Jquery Plugin.

Image
Recently I wrote a jquery plugin which would allow you to validate an email address for: Syntax checks (RFC defined grammar)   DNS validation Spell checks  Email Service Provider (ESP) specific local-part grammar (if available)  MX  Validation . Free Email Service Check Disposable Email Service check. Sanatize email id based on service provider. In future, I am planning to incorpoprate: Corporate Company details. If you have any suggestion then you can comment.  You can download the plugin here . Try a demo here . Some screenshots of the demo are: Media mention:  Its featured in  10+ Newest Free jQuery Plugins For This Week #16 (2015)   In  10+ Newest Free jQuery Plugins For This Week April #10 (2015) In  4月份本周超过 10 款最新免费 jQuery 插件 In  4月份本周超过 10 款最新免费 jQuery 插件

How to set Tomcat 7 source level to Java 7? Avoid "Resource specification not allowed here for source level below 1.7" error

I have been facing problem where whenever I was accessing jsp page which were using some Java 7 specific features, the compilation of such JSP pages use to fail with following error: Resource specification not allowed here for source level below 1.7 To fix this I googled for hours and set up the JDK home correctly on my catalina.sh with env.sh to point to jdk7. But this never solved my problem. Finally today I hit the gold while reading the apache tomcat jasper  documentation . The JSP compiler had to be set to use 1.7 as target and source version. To do this we need to add two extra init-params in the conf/web.xml file in the tomcat home.  The JSP servlet configuration should have      <servlet>         <servlet-name>jsp</servlet-name>         <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>         <init-param>             <param-name>fork</param-name>             <param-value>false</param-v

NPM Install Failing with EROFS in npm-debug.log on VirtualBox shared Drive [Updated for ETXTBSY]

I have a set up where I use my IDE on my host system and build my code on an Ubuntu server and deploy there. To achieve this I have used virtual box to install and run Ubuntu as a guest system. My host system is Windows.  I have shared a drive across to the guest. Every time my ubuntu comes up, I mount the drive using the command: sudo mount -t vboxsf SHARE_NAME folder_to_mount_on Things were working fine, with my Java server development. Now I decided to move my js and node environment to the same set up and BOOM! it failed. Only hint was EROFS error on the npm-debug.log. Some googling and I find out that VirtualBox has a bug and it does not support sysmlink and since ubuntu by default support symlink creation, npm was failing at the time of creation of sysmlink. My initial solution was to write a build script which rsynced my working directory to a level above and run the build command there. I worked but was slow and hacky. Then I found out that we can switch on symlink

Making Twitter Media Upload Api work with Java

I was trying to upload an image and do status update on twitter using there api version 1.1. For this I was using media/upload.json  . I was trying to send content of files as base64 encoded string and setting the appropriate content-type and content-transfer-encoding. But this didn't work. I was getting errors like: 1) Missing paramter media 2) Could not authenticate. My main reason to use this approach was I was getting image url and didn't wanted to save it into a file. But this never worked, then I took a different approach of saving the imageurl into a file and doing a multi part upload. Code for it is below. Hope this helps someone. private String uploadImage(String imageUrl) { File f = new File("/tmp/twitterUploadImage_"+StringUtil.encodeURL(imageUrl)); try { FileUtils.copyURLToFile(new URL(imageUrl), f); } catch (IOException e) { logger.severe("Failed to save image in a file"); return null; } U

Making Facebook Graph Photos Api Work with url

As per the documentation on Facebook https://developers.facebook.com/docs/graph-api/reference/v2.2/user/photos/ For /photos api if we want to post a photo to user timeline, using an url on open internet then we must: POST /v2.2/me/photos HTTP/1.1 Host: graph.facebook.com source=%7Bimage-data%7D But this gives: {   "error": {     "message": "An unknown error has occurred.",     "type": "OAuthException",     "code": 1   } } We should avoid adding {} or encode %7B and %7D around image-url for this to work. So correct would be: POST /v2.2/me/photos HTTP/1.1 Host: graph.facebook.com source=image-data

Git CheatSheet/Quickguide

Git Rebase Command git checkout branch name # checkout branch on which you want to merge git rebase branch_name # Original branch would be rebased to current branch. Rebase would remove changes in your branch and merge all the changes from the new branch then applyour changes on top of it. Git merge from a branch. git checkout branch name # checkout branch on which you want to merge git merge branch_name # branch_name is the branch from which you want to merge Reverting merge conflict files git reset --hard HEAD file_name # hard revert to HEAD Reverting to the last commited changes on a branch: git reset --hard HEAD # hard revert to HEAD Switching branches without committing changes: git add uncommited_files # Add uncommitted files to index git stash # Stash your changes git checkout new_branch # Switch to new branch, # Work on the new branch git stash pop # Switch back to

How to run npm installed components from commandline in Windows?

Image
When you are working with windows and nodejs, then you might face this problem, whatever npn packages you install might not be accessible through commandline. By this I mean, is that, suppose you did: npm install -g bower And then executed : bower install Windows might give you an error that 'bower' is unrecognized. A solution to the problem is to add npm global repository to your system path. To do so execute npm config get prefix To get the npm global repository path. Copy this path and follow following steps to add to windows path: On your computer, select  Start->Settings->Control Panel->System : A "System Properties" dialog box will appear. Click it's  Advanced  tab: Click the  Environment variables  button: An  Environment Variables  dialog box will appear. In the  System variables  section, scroll down until you find the  PATH  variable. Select this variable: Click the  Edit  button to edit the value of th

AI Planning Tree Search Algorithm for Missionary And Cannibal Problem in Java

I have been doing AI Planning course and I decided to implement the first basic problem in Java. To implement this, i tried to create the algorithm with right level of abstractions so that it can be applied to any problem in future. Some take aways in my package structure is that, I have maintained all the generic reusable code in definitions package and problem specific code in monkcannibal package. To solve the problem, I have implemented State which had successor method, IProblem which defined the problem to solve and IStrategy which defined the strategy to take for state transition. Here I have used two strategies for tree travesal, breadth first search aka, BFS and Depth First Search, aka DFS. The code is available on github at: https://github.com/biplav/aiplanning The main file is : com.biplav.aiplanning.problems.monkcanibbal.MissionaryCannibalPlan.java And the output is: 1:L->3m1cfalseboat R->0m2ctrueboat 2:L->3m2ctrueboat R->0m1cfals

Zopper Programming assignment Question 3 (Project Group)

The third question is also a simple one: Link to the question is on HackerRank:  http://www.hackerearth.com/problem/algorithm/project-team/ The submission code in python can be seen here:

Zopper Programming Assessment Problem 2 with solution

This is the second problem from HackerEarth that I tried for the friend for interview: Problem: HackerMan says that 5 and 8 are smart digits. A positive integer is called a smart number if it has only smart digits in its decimal representation. HackerMan has three sets of numbers. And he needs your help to find out the number of distinct smart numbers that he can make using one number from each of the three sets. You have to help in it Note:  You must not count the same smart number more than once. Constraints The three sets will contain between 1 and 50 elements, inclusive. Each number in the three sets will contain numbers between 1 and 30,000, inclusive. Input Format The first, third and fifth lines will contain a number N that will specify the count of numbers in the sets on the second, fourth and sixth lines of input. The second, fourth and sixth line will contain the three sets of numbers respectively. Output Format Print a single line containing the coun

Zopper online assesment question on HackerEarth with solution.

Recently a friend asked me to solve a problem which he got on one of the interview, online assessment test. I decided to document my solution here. The companies name was Zopper and the question was asked on the initial online screening test on HackerEarth. Problem: HackerMan says that 5 and 8 are smart digits. A positive integer is called a smart number if it has only smart digits in its decimal representation. HackerMan has three sets of numbers. And he needs your help to find out the number of distinct smart numbers that he can make using one number from each of the three sets. You have to help in it Note:  You must not count the same smart number more than once. Constraints The three sets will contain between 1 and 50 elements, inclusive. Each number in the three sets will contain numbers between 1 and 30,000, inclusive. Input Format The first, third and fifth lines will contain a number N that will specify the count of numbers in the sets on the second, fourth

Breaking open https://web.whatsapp.com/

Image
Today whatsapp have launched an online/web version of their overly popular smartphone messaging app. I was very much interested in seeing the architecture of this app because as far as i knew, they never stored messages on their server but all the data was only stored in users phone. So I started to look under the hood of the webapp and what I saw was a beauty. First let me list down the frameworks they have used in creating this app: React .js : A JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES from Facebook. Underscore.js  : Unerscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive immediately, what do I need?” … and the tie to go along with jQuery's tux and Backbone's suspenders. Velocity.js : Velocity is an animation engine with the same API as jQuery's $.animate(