August 7, 2011

(My) Three reasons why Twitter works

Filed under: tech — vik @ 6:01 pm

Drafted this post a little over an year back when Twitter was really picking up steam.. only just published it. In a way it proves my bonus point #4 below. :D

My Three Reasons why Twitter works -

  1. Re-tweeting = Word of Mouth. It’s not just passing on the message..it’s a stamp of approval.
  2. Feels like sitting next to friends and chitchatting.
  3. Instant relay leads to instant feedback – pushing you to improve the quality or your tweets, or the timelines (respond faster/stay updated)
  4. Bonus reason:

  5. Low expectations from our stressed out mental capacity – “I just need to utter 140 chars or less” vs. “I need to write a few paragraphs for my blog post”. To a blogger/writer, every Twitter post is a small win!

June 12, 2011

Formatting MS Word 2003 Documents for Kindle publishing: MS Word VBA Macro

Filed under: code,kindle — vik @ 10:23 am

The Kindle Direct Publishing program is a great way for authors to self-publish their books for Kindle users. There are several limitations however when it comes to readying your book for the Kindle since Kindle only supports very basic HTML. You have to abandon any fancy formatting you may have done in recent word processors and give your book a ’1999 Netscape Navigator 3.0 compatible website’ look.

I recently decided to move one of my Dad’s books into this channel. The book was written in MS-word and formatted to properly print on both sides of a page. Additionally there were many non-standard formatting techniques – eg different Header styles applied to different chapter headings. Properly formatting the book for Kindle would have taken a lot of effort, so I decided to accomplish at least part of that effort, using VBA for MS-word.

The VBA Macro I developed is below with instructions for use. This macro Kindle-readies a word document by:
1 – Transforming Page size to be 4.5″x5.5″, plus very small margins.
2 – Justifies all paragraphs, and reduces their indents to a very small value
3 – Merges all columns within Tables, so there are only tables with one column and as many rows as originally existed. I did this because the tables in my word documents were poorly formatted, and I decided to go with a 1-column table layout that the kindle could handle more easily.
4 – Centers all tables and shapes on the page

This macro will also save the current document and save a copy as a HTML (Filtered) file in a specified subdirectory with a “KDP_” prefix. You can choose to switch off either option.

What this macro does not do -
1 – Clean up headers/footers
2 – Standardize formatting – e.g. the header styles for different sections
3 – Clean up any font issues
4 – Clean up the resulting HTML code  – I recommend running HTMLTidy within Notepad++ on the HTML files generated through this code. One specific problem that HTMLTidy resolved was long strings of space, newline or tab characters that create unnecessary whitespace on the Kindle. As this kind of whitespace may have specific purpose in your word document, I did not make this cleanup part of the code.
5 – Reduce image size. Still need to figure this one out – does Kindle automatically reduce all images to viewable size?
6 – a lot of other issues your word files may have!

Below are instructions on using the code and the code itself. Please note this was made for a very specific purpose, and there are absolutely no warranties of any kind. Use this at your own risk! And take a backup of all your files before proceeding. Also I will only make future updates to the code as required to suit my purpose. This macro was designed and tested on MS Office 2003.

How to use this macro -

  1. I run this Macro in the Normal.dot file. See these steps at the end to know how to insert this code into the Normal.dot file
  2. After the Macro has been inserted into the Normal.dot file, I created a toolbar button to run it. You could choose to run it from the Tools menu everytime.
  3. If you would like to save resulting HTML files in a subdirectory of the folder where your word document is, then modify the KDPPATH variable in the macro.
  4. This macro will save the current document (Doc) and also save a HTML version. To stop either option, you can comment out the corresponding line in the macro.
  5. Open the word document that you need to convert.
  6. Run the macro using the toolbar button or from the Tools menu.
  7. Wait until you get a ‘Done’ message box. Then your doc/html file should be ready. The MSWord window will show the HTML file after completion (unless you opted out of the HTML generation).
  8. You may need to further work on the DOC file and address other issues before it is finally ready for Kindle formatting. If you do this, you will need to save it as an HTML from the File menu yourself.

Macro Code

Option Explicit
Dim KDPPATH As String
Dim INDENTVALUE As Single
Public Sub PerformKindleFormatting()
‘if you have a subdirectory in the SAME folder as the DOC file where you want the KDP html files to be saved, then
‘put that subdirectory name in the KDPPATH variable below. Leave blank if you want html files to be in the same location as the DOC
KDPPATH = “myKDP/”   ‘ don’t remove the trailing backslash \ if you put a value here  !!!!!

INDENTVALUE = 1 / 72

‘MsgBox “Starting ‘” & ActiveDocument.Name & “‘ You will receive another message when the process is done.”
Step1DoPagesetup
Step2FixAlignments
‘ Step3
‘Step4SaveDocument   ‘ comment out this line if you don’t want to save the modified DOC file itself
Step5SaveAsWebpage  ‘ comment out this line if you don’t want to save a copy in HTML (Filtered) format
MsgBox “Done”
End Sub

Sub Step1DoPagesetup()
‘ MOST OF THE CODE HERE GENERATED BY RECORDING A MACRO..SOME TWEAKS AS COMMENTED BELOW
With ActiveDocument.Styles(wdStyleNormal).Font
If .NameFarEast = .NameAscii Then
.NameAscii = “”
End If
.NameFarEast = “”
End With
With ActiveDocument.PageSetup
.LineNumbering.Active = False
.Orientation = wdOrientPortrait
.TopMargin = InchesToPoints(INDENTVALUE)   ‘VERY SMALL MARGIN
.BottomMargin = InchesToPoints(INDENTVALUE) ‘VERY SMALL MARGIN
.LeftMargin = InchesToPoints(INDENTVALUE)  ‘VERY SMALL MARGIN
.RightMargin = InchesToPoints(INDENTVALUE) ‘VERY SMALL MARGIN
.Gutter = InchesToPoints(0)
.HeaderDistance = InchesToPoints(0) ‘HEADER IS RIGHT ON TOP
.FooterDistance = InchesToPoints(0) ‘FOOTER IS RIGHT AT BOTTOM
.PageWidth = InchesToPoints(4.5)    ‘USING 4.5 INCHES TO SOMEWHAT ALIGN WITH KINDLE VIEWABLE SCREEN WIDTH
.PageHeight = InchesToPoints(5.5)   ‘USING 5.5 INCHES TO SOMEWHAT ALIGN WITH KINDLE VIEWABLE SCREEN HEIGHT
.FirstPageTray = wdPrinterDefaultBin
.OtherPagesTray = wdPrinterDefaultBin
.SectionStart = wdSectionContinuous ‘ MODIFIED THIS TO CONTINOUS. TEST WITH NEWPAGE OPTION ALSO?
.OddAndEvenPagesHeaderFooter = False
.DifferentFirstPageHeaderFooter = False
.VerticalAlignment = wdAlignVerticalTop
.SuppressEndnotes = False
.MirrorMargins = False
.TwoPagesOnOne = False
.BookFoldPrinting = False
.BookFoldRevPrinting = False
.BookFoldPrintingSheets = 1
.GutterPos = wdGutterPosLeft
End With
If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
ActiveWindow.Panes(2).Close
End If
If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow.ActivePane.View.Type = wdOutlineView Then
ActiveWindow.ActivePane.View.Type = wdPrintView
End If
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub
Public Sub Step2FixAlignments()
Dim i As Long
Dim j As Long
With ActiveDocument
For i = 1 To .Paragraphs.Count
.Paragraphs(i).Alignment = wdAlignParagraphJustify  ‘ JUSTIFY ALL TEXT
.Paragraphs(i).FirstLineIndent = InchesToPoints(INDENTVALUE)    ‘ SMALL INDENT TO FIRST LINE OF PARAS
.Paragraphs(i).LeftIndent = InchesToPoints(INDENTVALUE) ‘ SMALL INDENT TO PARA
Next i
For i = 1 To .Sections.Count
‘Sections(i).Range.Borders.InsideLineStyle = wdLineStyleThickThinLargeGap    ‘DOING NOTHIN TO SECTIONS
Next i
For i = .Tables.Count To 1 Step -1
For j = 1 To .Tables(i).Rows.Count
.Tables(i).Rows(j).Select
Selection.Cells.Merge       ‘ MERGE COLUMNS IN TABLES SO THERE ARE ONLY TABLES WITH SINGLE COLUMNS
Next j
.Tables(i).Rows.Alignment = wdAlignRowCenter    ‘CENTER TABLE
.Tables(i).AutoFitBehavior (wdAutoFitWindow)    ‘MAKE TABLE AUTOFIT TO WINDOW
Next i
‘For i = 1 To .InlineShapes.Count
‘   .InlineShapes(i).Borders.Enable = True
‘   .InlineShapes(i).Borders.OutsideLineWidth = wdLineWidth150pt
‘   .InlineShapes(i).Borders.OutsideColor = wdColorBrightGreen
‘   .InlineShapes(i).Borders.OutsideLineStyle = wdLineStyleDashLargeGap
‘Next i
Dim oILShp As InlineShape
For Each oILShp In ActiveDocument.InlineShapes
oILShp.Select
Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter    ‘ CAUSE INLINE SHAPES TO CENTER
Next
For i = 1 To .Shapes.Count
.Shapes(i).Left = wdShapeCenter
.Shapes(i).RelativeHorizontalPosition = wdRelativeHorizontalPositionMargin  ‘CENTER SHAPES
Next i
End With
End Sub
Sub Step4SaveDocument()
‘ Currently we just save the document AS-IS. We don’t save a copy. Because if we save a copy,
‘ its the copy that’s open when the HTML file is being saved next, and that distorts the path/filenames
ActiveDocument.Save

‘Dim fn As String
‘fn = “KDP_” & ActiveDocument.Name
‘Debug.Print “Saving as ” & ActiveDocument.Path & fn
‘ActiveDocument.SaveAs FileName:=ActiveDocument.Path & “\” & KDPPATH & fn, FileFormat:=wdFormatDocument

End Sub
Sub Step5SaveAsWebpage()

With ActiveDocument.WebOptions
.RelyOnCSS = False              ‘ STILL RESULTS IN CSS .. MSWORD #FML
.OptimizeForBrowser = True      ‘ OK YA?
.OrganizeInFolder = True
.UseLongFileNames = True
.RelyOnVML = False              ‘ VML HA HA
.AllowPNG = False               ‘ I LIKE MY LAWSUITS IN GIF
.ScreenSize = msoScreenSize640x480  ‘ CLOSEST OPTION TO KINDLE?
.PixelsPerInch = 72             ‘ READ SOMEWHERE THAT KINDLE IS GOOD WITH 72 DPI?
.Encoding = msoEncodingWestern
End With
With Application.DefaultWebOptions
.UpdateLinksOnSave = True
.CheckIfOfficeIsHTMLEditor = True
.CheckIfWordIsDefaultHTMLEditor = True
.AlwaysSaveInDefaultEncoding = False
.SaveNewWebPagesAsWebArchives = False
End With

‘ this part takes the file name, removes the DOC (or any) extension, and prepends KDP to form a new filename with extension html
‘ it will save the new html file in the same location as the original DOC file.
‘ If you put a value in the KDPPATH variable in the GLOBAL section on the top of this code,
‘ the html file will be saved in the resulting KDPPATH subdirectory
Dim fn As String
fn = ActiveDocument.Name
fn = “KDP_” & Left(fn, InStr(fn, “.”) – 1)
Debug.Print “Saving as ” & ActiveDocument.Path & fn
ActiveDocument.SaveAs FileName:=ActiveDocument.Path & “\” & KDPPATH & fn, FileFormat:=wdFormatFilteredHTML
End Sub

Other Useful links:

  1. John August’s basics for Kindle formatting
  2. Aaron Shepard’s tutorial on word to Kindle formatting
  3. Kindle Formatting Faq
  4. HTML tags compatible with Kindle
  5. Understand Normal.dot

How to add a macro to your Normal.dot file

1 – Open MS Word
— Close any documents such as the “New blank document” that opens up.
2 – Click on the menu Tools->Macros->Visual Basic Editor (Alternatively press Alt-F11)
3 – If you don’t see a “Project” pane on the left hand side of the VB editor, click on the menu View->Project Explorer
4 – In the project pane, you should be able to see a high level item called “Normal”, under which there will be a subitem called “Modules”.
5 – If under “Modules”. you see a module called “NewMacros”, then double click on it to open it in the editor. If you don’t, then right click on “Modules”, and select the contextmenu item Insert->Module. Open the new module for editing.
6 – Paste the macro into the module, in the editor window.
7 – Save the file. Close word. Now the macro should be a permanent part of your MSWord and can be used on any word document you open in the future.

July 24, 2010

Ford Fiesta, Or “My mechanic’s early retirement plan”

Filed under: Uncategorized — vik @ 9:48 pm

Flashback – Aug 2006. One year into my post-MBA job, just married and can’t wait to buy my first car. The midrange options at the time are the long running Maruti Baleno, Swift, Hyundai Accent, Tata Indigo, Honda City and a couple of others. And the newly launched Ford Fiesta. The fiesta looks good, is priced well and is the latest kid on the block.

So I buy it. The 1.6 Sxi from Harpreet Ford in Gurgaon. I go with the cherry color (Paprika red) that’s available immediately. I’m so excited about it that I don’t really haggle for any deals from the dealer at all (no car covers/extended warranty, discounts, lower interest rate  etc – hey, they did give my wife a rose bouquet after our purchase!). I love the car! After having had a Maruti 800 for 8 years, this is such a dream (power windows?? woooo!).

The car drives great, and my dad loves the surprise. We make sure we do all the regular servicing at .. who else.. Harpreet Ford!

Cut forward 8 months to summer of 2007.

I’m doing 70 kph or so in the Fiesta on the Dehradun highway. Just as we hit the ‘Mohand’ forests, the AC conks out – so we need to open the windows in the searing afternoon heat. We’re still getting along when suddenly, the car begins to grind. I’m pressing the pedal and NOTHING’S happening (no engine roaring, no acceleration) and the car is hurtling forward on its own. I pull over to a side, wait 5 minutes and try re-starting the engine. It starts and we’re on our way again. Until 5 mins later when the same happens and we again need to stop and cool down. This goes on, until we drag our way through the mountain roads at 15 kph with no AC and finally make it to our destination.

It is at this point that I should insert this Ford one-liner -

How is a golf ball different from a Ford? You can drive a golf ball 200 yards!

In Dehradun, we take the car to the local Ford workshop – the guy gives the car a look, gives us a look, decides we’re good for a couple of thousand bucks and lets us out after we’ve paid him the requisite amount and had our coolant changed (With official Ford coolant of course – no other coolant will do even if they’re from leading coolant manufacturers).

After we come back to Delhi, we get a servicing done at Harpreet Ford, who tell us nothing is wrong while ensuring our maintenance bill stays as close to the well rounded figure of 5000 as possible.

Summer of 2008 – the entire sequence is re-enacted on our way to Dehradun again. This time the entire family experiences it, and we’re forced to add a Castrol coolant because, well, there’s no Ford certified service center outside of the major towns.

Again back in Delhi, Harpreet Ford finds no major issue and has no clue of the root cause. Of course the problem is un-replicable at their premises so we can’t really prove it.

Summer of 2009 and 2010 – this happens again. Whether on the Jaipur highway, or in the city – the car just blanks out irrespective of the speed and needs to be pulled over. (A bit of googling will reveal that other customers have had the same issue with Ford cars – here’s one link)

Go Fida with the Ford Service options, or Go Broke

Not only is this a complex defect in the car that puts the passengers at extremely high risk, the service center is also either unequipped or in denial or just plain careless about trying to fix it at the root cause. There were (at least until 2009), only two places you could go to get your Ford repaired in Delhi – Harpreet Ford in Gurgaon and Moti Nagar, and another dealer in Noida (can’t remember the name – was it South City ford?). The alternatives are non-Ford-authorised service centers.

Also with the Ford you’re required to only use the Ford engine oil and other paraphernalia – which are costlier than the usual market options (average servicing costs Rs 4000 approx – I was shocked to learn that my friend with an SX4 got his servicing done in about Rs 800!). All this means you’re locked in to one dealer and his practices. At Harpreet Ford, that usually means getting a service quote with items you don’t understand, leaving your car with them for a couple of days and no opportunity to look at it while its being worked on, and then receiving your car with no one to explain what was done on it. Payment in advance, thank you very much.

Once, after we got our rear door repaired at Harpreet Ford after a small accident, they fixed it after we reminded them by tying up the old wire that connects the handle to the door latch. Which broke in a couple of days when we got back home. Worse, the front power windows button on the driver side, which had no issue at all, started behaving erratically.

On another occasion, our battery died overnight possibly because some lights were left on (we never found out why actually – because the internal electricals usually fade out after the car is locked up from outside). When we took our car to Harpreet Ford, we were told that the car computer (ECU) was damaged and needed to be replaced – setting us back by a cool Rs 40,000 approx!!! Worse, while the car was being inspected in the Harpreet Ford Moti Nagar lot, they got some scratches on the rear wheel rim and broke the pullout bonnet opener  – and wouldn’t take responsibility for it!

By this time we had had it with Harpreet Ford and stopped dealing with them – instead we now get our car serviced at Bosch Service Center Rajouri Garden – where we can at least see what’s being done to our car and get the full range of service by Bosch certified mechanics. Way more transparent and satisfactory.

No resale value

Sorry I should re-do that headline. A Ford does not have zero resale value – it has a negative resale value. Since the last 2 years, any quote I got on this car did not even cover the outstanding on the loan. With the new models being priced even more aggressively by Ford and bundled with features like an MP3 player, it only means you’re forever stuck with the Ford.

The sorry tale continues…

Apart from the issues above, many other defects have surfaced through the years -

2008 – The  engine started misfiring – needed a Rs 1000+ replacement (i think it was this sparkplug component)
2009 – The dashboard speedometer and odometer stopped working – the speedometer will simply die down and start working randomly.
Every summer the AC needs the gas refuelled, or its tubing changed. In any case it works subpar compared to other cars

Wheelplates – Ford wheelplates are clamp-ons, not screwed in to the wheel – which means every year you lose a couple to burglars or if you hit a really bad pothole. The company sells sets of 4 at Rs 500 per wheelplate – outside you can buy a set of 4 at about Rs 700.
2010 – Two new problems for 2010! The front axle now makes a sound (like metal pipes falling over one other) while making turns or going over potholes in the road – it appears the axle connection to the wheel has gone out of sync, and requires the axle to be replaced at about Rs 20,000 from Ford. Second, the driver door key lock has stopped working – I can lock it but I can’t unlock from that side, so I need to unlock every time from the passenger side. I’m not even thinking of getting this repaired until I absolutely need to – because I vaguely remember the service center telling me that the locks are all computerised and I will need to change the whole set at a cost of roughly Rs 20,000!!
In general, the car needs frequent servicing – best is every 3 months – if you top 5 months or so without servicing, it starts showing in the performance

Ford

The service network and most importantly, the fundamental flaws in the ford fiesta have all added up to a HUGE DISAPPOINTMENT for me and my family, and mean that not only will I never buy a Ford myself ever in the future, I will also recommend strongly to anyone I know that they avoid touching a Ford even with a 30 foot pole.

Unless of course, its my Ford they’re helping push.

—–

PS – Ford Jokes on the post are from this page. Also to mention, the silver lining in the Ford Fiesta experience was the service I received from ICICI Lombard – with claims being handled quickly and with minimal hassles.

July 17, 2010

How passionate can you be?

Filed under: Uncategorized — vik @ 9:25 pm

Remember how, as a kid, we used to go totally crazy with every little thing from a toy to a chocolate cake (yeah, back when we didn’t know what brownies were and could have only thought they were elves. ok, digressing right in the first line of the post!)…point is, we were simply incapable of not putting our heart into things unabashedly.  Most of us, a good majority I’m sure, can’t say the same still holds.

And then this…checkout this video of a hiker totally flipping out when he witnesses a double rainbow in Yosemite, USA (the vids become really popular). Totally smitten by the view, he goes from “oohs” to hysterical sobbing in 3 minutes. And you can’t help but ‘feel’ the scene with him.

When were you last as passionate as him about anything?

July 2, 2010

Shanghai and the World Expo 2010

Filed under: travel — vik @ 8:24 pm

Shanghai is hosting the World Exposition 2010 – a huge show where most countries setup a showcase pavilion that I’d never heard of before :-)

With 200 countries participating this year for the Expo that will run from May to October, 70 million visitors are expected – that’s about 400,000 visitors a day – with 22 million having already visited to-date!

Consequently the queues are long – i.e. between 0.5 hrs (Morocco) to 7 hours (UAE). The Expo covers an area of 5 sq km so its a lot of walking too.

As expected, this is another grand show from the Chinese – the infrastructure is tremendous: easy commute to/from the expo site that’s located about 30 mins by taxi from Shanghai city center, all kinds of amenities inside and pretty good crowd flow.

I reached the gates at 8 AM and was still behind thousands of people. After the 2 hr airport-like security scan, I found I couldn’t enter the Chinese pavilion since I didn’t receive the “First-come-first-serve Reservation” for that Pavilion – which was a disappointment as the Chinese pavilion looked great. (Reservations applied to Taiwan as well)

I then made my way to the next nearest one – Pakistan. The high point of the Paki pavilion was a “projected pseudo-holographic image” on a water-curtain — looked neat. The rest of the pavilion had mostly photos of the country – with a heavy emphasis on the Paki-China friendship – and ending with a kebab restaurant.

The next one was India. A queue of 2.5 hours waited patiently to enter the pavilion whose external design was meant to depict a ‘tree of life’ and had a facade with miniature carvings.

Encircling the stage were small handicraft shops with nothing more than the usual Dilli Haat stuff (ok it may not have been so ‘usual’ for the local crowd).

With no general “flow” to follow, I roamed around and saw crowds moving to the left into a narrow passage. A 15 min wait later in a passage that probably violated most ‘emergency exit’ guidelines, I finally realize it’s the entry to the ‘main’ dome of the pavilion and I take that phew-there’s-still-some-hope-left breath. Inside the dome, the walls are lined up with photographs, artefacts, etc, with the Taj Mahal, Tagore and Lata Mangeshkar among others getting their regular wallspace. There is no description – only a few photos have names – and the crowds keep moving on without really understanding anything.

Quite unfortunately, but not entirely unexpectedly, the pavilion was a HUGE disappointment. For starters, once you enter, there’s a stage in front where performances happen. When I entered, there was a classical instrumental about to end (looked like Amjad Ali Khan’s kids – not sure though) – when it ended, the performer said thanks and quickly pointed out to everyone that his CDs were on sale that they could buy. :-/

Suddenly the lights begin dimming and the crowds start taking seats around a glass structure in the center. Then a AV presentation starts happening – one of those ‘pseudo-hologram projections on tilted glass’. The holograms show 3D line images (not real photos) of various things through Indian history with a narration in Chinese. The show ends in about 7 minutes with the audience not really getting the point of it all.

At the dome exit, I notice the high point for the crowds – a decorated Elephant head that everyone’s queuing up to take pictures with.

After a small Chicken Tikka at an exorbitant price at the Indian restaurant, I make my way out and pity the 2.5 hour queue to the pavilion which only looks longer!

Sadly, an opportunity for us to showcase our progress in the 21st century and to highlight our partnership with China to those it matters most – the Chinese people, falls prey to a (possibly) minimal budget and babu-style-execution. And equally unfortunately, most Indians back home are never going to know how we failed on the world stage given the lack of coverage.

This article does complete justice to our shoddy show at the Expo.

I then visited Morocco – a pavilion looking like a typical white-desert-palace with a beautifully/lavishly done interior. There was a single flow of people in and out – mostly a photo+handicraft display again.

Nepal was next – I wasn’t sure if I wanted to visit it – but the pavilion was setup as an exquisite monastery over quite a big area. There was even a Stupa in the center that you could walk up and around to – and get a good view of the Expo.

During the walk up to the Stupa, you see this humongous dome appearing in the horizon – turns out to be the Cultural center. I think its the “largest” building I’ve ever seen!

I then walked over to the other zone to visit the USA pavilion – which is mostly about 2 AV presentations – but with some neat surprises. After 11 hours at the Expo, I had no time or energy left to go to visit any other countries.

In all, you can spend a whole week trying to cover the Expo. Be prepared for hours of queues and miles of walking. Food etc is easily available.  Another thing I noticed – all day I must have seen about 50 foreigners in the teeming millions of locals – was certainly expecting far more – but it says a lot about the Chinese taking interest in stuff their Govt invests in. (I mean – when did you last go see an Expo at Pragati Maidan, eh?)

In other stuff, most of the days in Shanghai were either rained out or smoggy – with about 2 days of sunshine. See gallery below for some photos – followed by one of the Meridien lighted up at night (like most Shanghai Skyscrapers are).

Later, Shanghai!

June 15, 2010

New Comet in the sky

Filed under: astro — vik @ 9:41 pm

Comet McNaught named after its discoverer R. H. McNaught, is now visible to the naked eye. It is currently reported to be at magnitude 3 but only 15 degrees over the Eastern horizon around 3 AM in the morning – in the Perseus constellation.

Here is the path of the comet (in PDF too)

Comet McNaught - path

Comet McNaught - path

Below is a picture from the Cometography site-

Comet McNaught - From http://cometography.com/lcomets/2009r1.html

Comet McNaught - From http://cometography.com/lcomets/2009r1.html

June 13, 2010

Chicago 2010

Filed under: travel — vik @ 7:29 pm

Made a trip to Itasca/Chicago in April.. beautiful city (whatever I got to see in half a day).. high point was the vie from the 96th floor of the John Hancock Tower lounge.

Lansdowne May 2010

Filed under: travel — vik @ 6:44 pm

The scorching summer heat drives flatlanders like us Delhi-ites out to the hill stations every May/June. Unfortunately but expectedly, the usual spots are at this time way too crowded and congested.  There still are thankfully, some places that haven’t been trampled under scorpios and endeavours and/or littered by colored polybags yet. One of them is Lansdowne, about 230 kms north of Delhi, via Bijnor and Kotdwar.

The town is strictly under army control – hence the good roads, spotless town center and litter bins everywhere. There’s not a lot of touristy places, and there are only a handful of hotels. But there are tall Deodar forests, scenic hills and curving roads, and a couple of divine churches. The town center itself is a small junction with market lanes. The hotel recommendation is Fairydale resort – by far the best and well located (and owned by an XLer!) – there’s another call Blue Pines but it’s way lower than the main town.

Lansdowne

The two Churches


Tarkeshwar Temple – nestled in a Deodar valley – as divine as it gets

Rock formations – One of the many

Boating Lake

December 9, 2009

Golf swing

Filed under: golf — vik @ 9:43 am

A great video of Tiger Wood’s golf swing, that’s helped me get my swing back this weekend.

Awesome tip:  Start the downswing with your left hip rotating outwards, and leading the rest of the body. (More like a reminder..sort of forgot that since I started). The torque generated this way is tremendous – far more than by just hitting the ball with the hands. And it’s A-OK to let the left knee drop forward while you’re reaching for the backswing.

Also, great tip to get more power into your shot : maintain the 90 degrees between the left hand and the club from the top of the backswing, until you’re almost ready to hit the ball at downswing.

Another tip also evident in the video – is to keep the right hand loose and sort of swinging it ‘under’ the ball. The right forearm and hand are almost facing straight (in the direction of your nose).

Apart from that..keep the ball positioned slightly ahead of the center of your feet (for a mid iron).



November 20, 2009

Turning a webcam into a home security monitor while you’re away

Filed under: code — vik @ 9:36 am

Due to security concerns in our vicinity last year, I needed a way to keep tabs on our home while the whole family was away on vacation. The idea was to be able to view images of your home, live over the internet from whereever we were. CCTV solutions weren’t an option as they were expensive and none seemed to have a remote viewing option. I believe now there are advanced Logitech webcams in the market that also pivot and stream images to the net, but again they come at a price, and don’t take care of a few things like problems with your internet connection or laptop power when you’re not available to take care of them.

However, there are freeware/shareware solutions on the internet that allow you to capture your webcam and stream it online, even at a particular schedule.The software that I used was a super little app called Active Webcam from Pysoft.

Further, I needed a software that would take care of laptop restarts/windows crashes/net connection blips (and also auto logging into the net account if the login expires every 24 hrs) and that would automatically start Active Webcam every time the system started up – I decided to code that in VB.

Apart from the software I also needed my personal laptop, regular webcam and a DSL internet connection. I had gprs activated on my phone as well, in order to view the images uploaded.

First, i installed Active Webcam and set it up so it would stream images from the webcam to my website at a specific URL.  (Yes, you need a website host that offers FTP where the images will be uploaded to – possibly there are options to upload to photo services like flickr/photobucket too, or to send emails to you with attached images)

Second, compile the code below into an exe and include that exe in the Windows Startup so it runs at system startup.

When this program runs, it will
- check for internet connection availability, and if not available will to restart the local modem
- if the internet connection doesn’t come up after 3 modem restarts, it will restart Windows. It won’t restart windows more than once in 15 mins though.
- log the laptop’s battery status
- log everything to a remote php file so the logs can be viewed remotely too

Download the entire VB project.

This VB project has :
1. a form called frmMain
2. a module called Module1.bas

The code for both is shown below – a lot of the sections came from various sources on the net, so no claims there and a big thanks to them. Also, it all seemed to work at the time. :-)

Also there are certain urls – while most are simply used to check the internet connection, the ’192.168.1.1′ is my modem’s local admin page that you may need to change accordingly. (In order to restart the modem, I used the code here to login to the local admin at 192.168.1.1 and post my username/password etc to the appropriate file (restartmodem.htm))

————————————————————————————————————

frmMain.frm – code

Private Declare Function InternetGetConnectedState Lib “wininet.dll” (ByRef dwFlags As Long, ByVal dwReserved As Long) As Long

Private Declare Function InternetCheckConnection Lib “wininet.dll” Alias “InternetCheckConnectionA” (ByVal lpszUrl As String, ByVal dwFlags As Long, ByVal dwReserved As Long) As Long

Private Declare Function SendMessage Lib “user32″ Alias “SendMessageA” (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Function OpenProcess Lib “kernel32″ (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long
Private Declare Function WaitForSingleObject Lib “kernel32″ (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function CloseHandle Lib “kernel32″ (ByVal hObject As Long) As Long

Private Declare Function GetExitCodeProcess Lib “kernel32″ _
(ByVal hProcess As Long, lpExitCode As Long) As Long

Private Declare Function TerminateProcess Lib “kernel32″ _
(ByVal hProcess As Long, ByVal uExitCode As Long) As Long

Private Const FLAG_ICC_FORCE_CONNECTION = &H1

Private Declare Function NetUserGetInfo Lib “netapi32″ (lpServer As Any, lpUserName As Any, ByVal Level As Long, lpBuffer As Any) As Long
Private Declare Function GetUserName Lib “advapi32.dll” Alias “GetUserNameA” (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function GetComputerName Lib “kernel32″ Alias “GetComputerNameA” (ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Sub CopyMemory Lib “kernel32″ Alias “RtlMoveMemory” (Destination As Any, Source As Any, ByVal Length As Long)

Private Const UNLEN As Long = 256         ‘ Maximum username length
Private Const CNLEN As Long = 31          ‘ Maximum computer name length
Private Const NERR_Success As Long = 0&

Dim actcamShellID As Long

Dim nwErrorCounter As Integer
Const nwErrorThreshold = 1

Dim WinHttpReq As WinHttp.WinHttpRequest
Const HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0
Const HTTPREQUEST_SETCREDENTIALS_FOR_PROXY = 1

Public Enum shutdownTypes

Logoff = 0
Shutdown = 1
Reboot = 2
Force = 4
PowerOff = 8

End Enum

Private Type LUID

UsedPart As Long
IgnoredForNowHigh32BitPart As Long

End Type

Private Type TOKEN_PRIVILEGES

PrivilegeCount As Long
TheLuid As LUID
Attributes As Long

End Type


‘The function used to actually send the request to shutdown windows. Set the ‘shutdownTypes’
‘parameter to whether you want windows to “shutdown, reboot, logOff, ect…”
Private Declare Function ExitWindowsEx Lib “user32″ (ByVal shutdownType As Long, ByVal dwReserved As _
Long) As Long

‘Will get a handle to the process this function is called.
Private Declare Function GetCurrentProcess Lib “kernel32″ () As Long


‘The functions below are all used to give the application that the library is bound to the proper privilege so
‘the OS will allow the app to Shutdown Windows.


Private Declare Function OpenProcessToken Lib “advapi32″ (ByVal ProcessHandle As Long, ByVal _
DesiredAccess As Long, ByRef TokenHandle As Long) As Long

Private Declare Function LookupPrivilegeValue Lib “advapi32″ Alias “LookupPrivilegeValueA” (ByVal _
lpSystemName As String, ByVal lpName As String, ByRef lpLuid As LUID) As Long

Private Declare Function AdjustTokenPrivileges Lib “advapi32″ (ByVal TokenHandle As Long, ByVal _
DisableAllPrivileges As Boolean, ByRef NewState As TOKEN_PRIVILEGES, ByVal BufferLength As _
Long, ByRef PreviousState As TOKEN_PRIVILEGES, ByRef ReturnLength As Long) As Long

Private Sub cmdStart_Click()
‘ moved below  2 to formm load now
‘Log “Starting timer…”
‘Timer1.Enabled = True

‘In my case I started Active Webcam using the windows startup options – if you want this healthchecker to start the app, uncomment this line and also the one cmdStop_Click()
‘actcamShellID = Shell(“C:\Program Files\Active WebCam\WebCam.exe”, vbMinimizedNoFocus)
End Sub

Private Sub cmdStop_Click()
Timer1.Enabled = False
Log “Stopped timer.”

‘Debug.Print EndShelledProcess(actcamShellID)
End Sub

Private Sub Form_Load()
Set WinHttpReq = New WinHttpRequest
Log “Application started…”, 1

Log “Starting timer…”
Timer1.Enabled = True

nwErrorCounter = 0
End Sub

Private Sub Form_Terminate()
Log “Application terminated.”, 1
End Sub

Private Sub Timer1_Timer()
DoEvents
Dim nwTrulyBad As Integer

If (nwErrorCounter > nwErrorThreshold) Then
‘ too many times nw error – just restart network
Log “Timer off…”
Timer1.Enabled = False
Log “restarting network”

nwTrulyBad = 0
While (nwTrulyBad < 3)
Log “… restart attempt ” & (nwTrulyBad + 1)
restartModem
If (InternetCheckConnection(“http://web1219.ixwebhosting.com”, FLAG_ICC_FORCE_CONNECTION, 0&) <> 0) Then
Log “… restart attempt succeeded ”
nwTrulyBad = 0
‘Exit Do
Else
nwTrulyBad = nwTrulyBad + 1
Log “… restart attempt failed.”
End If
Wend

If (nwTrulyBad >= 3) Then
Log “… Modem restart failed. Need to restart system”
‘ Network did nost cmoe up even after restarting modem 3 times. Should restart system now.
‘ however do not restart if last system reboot time was less than 15 mins ago
If ((Now – LastLogon2()) > 0.0104) Then
shutdownWindowsOS shutdownTypes.Reboot Or Force
Log “PC RESTARTING”
Else
Log “TOO SOON TO RESTART”
End If
End If

nwErrorCounter = 0
End If

Timer1.Enabled = True

If InternetCheckConnection(“http://web1219.ixwebhosting.com”, FLAG_ICC_FORCE_CONNECTION, 0&) = 0 Then
nwErrorCounter = nwErrorCounter + 1
Timer1.Interval = 15000
Log “No internet connection detected…nw counter: ” & nwErrorCounter
Else
nwErrorCounter = 0
Timer1.Interval = 10000
Log “Internet connection detected…”
End If

Log “Battery status: ” & GetBatteryStatus()
If (InStr(1, GetBatteryStatus(), “Low”)) Then
Log “BatteryRed” & GetBatteryStatus(), 1
End If
End Sub

Private Sub restartModem()

DoEvents

‘ Assemble an HTTP request.s
WinHttpReq.Open “POST”, “http://192.168.1.1/cgi-bin/webcm”, False

‘ Set the user name and password.
WinHttpReq.SetCredentials “admin”, “admin”, HTTPREQUEST_SETCREDENTIALS_FOR_SERVER

‘Set Content-Type header
WinHttpReq.SetRequestHeader “Content-Type”, “application/x-www-form-urlencoded”

On Error GoTo nextpt
‘Send the form data To URL As POST binary request
WinHttpReq.Send “getpage=”"http://192.168.1.1/cgi-bin/html/tools/restartmodem.htm”"&var:com=”"restart”"&var:ip=”"”"&var:restart=”"1″”&logic:command/ppp_disconnect=”"”"”

‘ Display the status code and response headers.
Debug.Print WinHttpReq.Status & ” ” & WinHttpReq.StatusText
Debug.Print WinHttpReq.GetAllResponseHeaders & “  ” & WinHttpReq.ResponseText

nextpt:
End Sub

Public Sub Log(txt As String, Optional priority As Integer)
‘txtLog.Text = txtLog.Text & vbNewLine & txt

‘Open “c:\hclog.txt” For Append As #2
‘Print #2, Now
‘Print #2, txt
‘Print #2, String(91, “*”)
‘Close #2

If (priority = 1) Then
WinHttpReq.Open “GET”, “http://www.YOURSITE.com/log.php?txtlog=” & Now & “, ” & txt, True
WinHttpReq.Send
On Error Resume Next
End If
End Sub
Public Function EndShelledProcess(ShellReturnValue As Long) _
As Boolean

‘PURPOSE: End a process started with VB’s Shell Statement
‘INPUT: Task ID returned by Shell
‘RETURNS: True if succesful, false otherwise

On Error Resume Next

Dim hInst As Long
Dim hProcess As Long
Dim lExitCode As Long
Dim lRet As Long

hInst = ShellReturnValue
If hInst = 0 Then Exit Function

‘Get handle to process
hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0&, hInst)
If hProcess <> 0 Then
‘get exit code
GetExitCodeProcess hProcess, lExitCode
If lExitCode <> 0 Then
‘bye-bye
lRet = TerminateProcess(hProcess, lExitCode)
EndShelledProcess = lRet > 0
End If
End If

End Function

Private Sub AdjustToken()
Const TOKEN_ADJUST_PRIVILEGES = &H20
Const TOKEN_QUERY = &H8
Const SE_PRIVILEGE_ENABLED = &H2
Dim hdlProcessHandle As Long
Dim hdlTokenHandle As Long
Dim tmpLuid As LUID
Dim tkp As TOKEN_PRIVILEGES
Dim tkpNewButIgnored As TOKEN_PRIVILEGES
Dim lBufferNeeded As Long

hdlProcessHandle = GetCurrentProcess()
OpenProcessToken hdlProcessHandle, (TOKEN_ADJUST_PRIVILEGES Or _
TOKEN_QUERY), hdlTokenHandle

‘ Get the LUID for shutdown privilege.
LookupPrivilegeValue “”, “SeShutdownPrivilege”, tmpLuid

tkp.PrivilegeCount = 1    ‘ One privilege to set
tkp.TheLuid = tmpLuid
tkp.Attributes = SE_PRIVILEGE_ENABLED

‘ Enable the shutdown privilege in the access token of this process.
AdjustTokenPrivileges hdlTokenHandle, False, _
tkp, Len(tkpNewButIgnored), tkpNewButIgnored, lBufferNeeded

End Sub

Public Function LastLogon2() As Date
Dim nRet As Long
Dim Server As String
Dim User As String
Dim ui3(1 To 29) As Long
Dim lpBuffer As Long
Const evServer = “LOGONSERVER”
‘ Retrieve current user and logon server names.
User = CurrentUserName()
Server = Environ$(evServer)
If Len(Server) = 0 Then Server = CurrentMachineName()
If InStr(Server, “\\”) <> 1 Then Server = “\\” & Server
‘ Retrieve Level3 information on current user.
nRet = NetUserGetInfo(ByVal StrPtr(Server), ByVal StrPtr(User), 3, lpBuffer)
If nRet = NERR_Success Then
‘ Results are returned as a pointer to buffer.
‘ Copy 29 dwords/pointers into array of Longs.
CopyMemory ui3(1), ByVal lpBuffer, UBound(ui3) * 4&
‘ Return last logon date/time, which is 14th element.
LastLogon2 = NetTimeToVbTime(ui3(14))
End If
End Function

Private Function CurrentUserName() As String
Dim Buffer As String
Dim nLen As Long
Const NameLength = UNLEN + 1
‘ ANSI method.
nLen = NameLength
Buffer = Space$(nLen)
Call GetUserName(Buffer, nLen)
‘ Trim results and return.
If nLen > 1 Then CurrentUserName = Left$(Buffer, nLen – 1)
End Function

Private Function NetTimeToVbTime(NetDate As Long) As Double
Const BaseDate# = 25569   ‘DateSerial(1970, 1, 1)
Const SecsPerDay# = 86400
NetTimeToVbTime = BaseDate + (CDbl(NetDate) / SecsPerDay)
End Function

Private Function CurrentMachineName() As String
Dim Buffer As String
Dim nLen As Long
Const NameLength = CNLEN + 1
‘ Fall back to the ANSI method.
nLen = NameLength
Buffer = Space$(nLen)
Call GetComputerName(Buffer, nLen)
‘ Trim results and return.
If nLen > 0 Then CurrentMachineName = Left$(Buffer, nLen)
End Function

Function shutdownWindowsOS(ByVal shutdownType As shutdownTypes) As Integer

‘This function will call the ExitWindowsEx function to request the system to shutdown/reboot or
‘whatever is specified in the “shutdownType” parameter. It of course, will call the “AdjustToken”
‘sub to give your app the privilege to use that function first.

AdjustToken

‘Calls the function to begin executing.
shutdownWindowsOS = ExitWindowsEx(shutdownType, 0)

End Function

————————————————————————————————————

Module1.bas

ByRef lpSystemPowerStatus As SYSTEM_POWER_STATUS) As Long

Public Function GetBatteryStatus() As String ‘ Get the status of the laptop’s battery
Dim btFlag As Byte
Dim SPS As SYSTEM_POWER_STATUS
Dim lReturn As Long
Dim sRet As String
Dim lFlag As Long

lReturn = GetSystemPowerStatus(SPS)
btFlag = SPS.BatteryFlag

lFlag = CLng(btFlag)

Select Case lFlag
Case BATTERY_FLAG_CHARGING
sRet = “Now Charging…”
Case BATTERY_FLAG_CRITICAL
sRet = “Critically Low !!”
Case BATTERY_FLAG_HIGH
sRet = “High Charged!”
Case BATTERY_FLAG_LOW
sRet = “Low Charged!”
Case BATTERY_FLAG_NO_BATTERY
sRet = “(No Battery)”
Case BATTERY_FLAG_UNKNOWN
sRet = “Unknown”
End Select

If (SPS.ACLineStatus = 1) Then
sRet = “[On AC] ” & sRet
Else
sRet = “[On Battery] ” & sRet

End If

GetBatteryStatus = sRet
End Function

————————————————————————————————————