This is my second post in a series of 52 (yes, yes I've delayed a lot but I would prefer later, better posts than useless, on-time posts).
Forms are something that I end up coding on almost every website I make (without using a CMS, that is). Essentially, while making a form I have to:
- Write HTML code for the forms giving appropriate names and ids.
- Write PHP code that reads in these names from POST or GET and then filter them.
- Create appropriate error messages in PHP based on incorrect data provided in forms, and repopulate correctly filled fields in the form for the sanity of users.
- Write Javascript (or use a plugin from jQuery) to validate the fields inline using the exact same rules and show messages to users before submitting the form.
- Debug because I missed a character or capitalized something I shouldn't have.
- And then I realize I missed something, and then repeat.
This is also known as web developer hell. Somewhere near the inner circles.
Ideally, what would I want to do to get a form ready?
Specify what I want at one single place with some convenient format (— did anyone say JSON?)
So essentially, this post covers:
- Specifying a (modifiable) JSON format for forms.
- Generating HTML using PHP for those forms.
- Generating rules in PHP using this format.
- Generating javascript for validation using this format.
Building the specification:
Call it a whim or a fancy — I want to use JSON for my specifications. I cannot think of any other more convenient format for specifying data to be used in PHP and Javascript.
Let's take a look at all available form elements:
- input tags:
- button
- checkbox
- file
- hidden
- image
- password
- radio
- reset
- text
- submit
I'll only be taking a look at the types highlighted in bold text.
- textarea
- select
- option
- optgroup
- button
The specification as it is now
[{
'name' : '[form-name]' //Name and id of the form to be created.
'class' : '[ '[class1]', ... ]'
}, ...]
What do I need to specify for the form?
- The form structure — the JSON spec must follow the structure that the form will take. Specifying a contents array seems to be the best possible solution to that, allowing and defining fieldsets for forms nested inside forms.
[{ 'name' : '[form-name]', 'contents' : [ { 'name' : '[fieldset-name]', 'legend' : '[fieldset-legend]', 'class' : '[ '[class1]', ... ]' 'contents' : [ ... ] } ] }, ...] - So now we get down to the meaty part. Defining elements. Each element is an object with a type, name, label, an array each for attributes and classes, and an array for validation data.
[{ 'name' : '[form-name]', 'caption' : '[form-caption]', 'class' : '[ '[class1]', ... ]' 'contents' : [ { 'name' : '[fieldset-name]', 'legend' : '[fieldset-legend]', 'contents' : [ { 'type' : 'input-text', 'name' : '[name and id of the object]', 'label': '[its label. duh.]', 'attr' : [ '[attr-name]' : '[value]' , ... ], 'class': [ '[class1]', '[class2]' ], 'rules': [ ... ] } ] } ] }, ...]
To be continued.
Back to Basics: Forms
30/01/2010 The Windy Hostel, Indian Institute of Consultancy, Delhi: At 11.05 a.m. today morning a horrifying accident occurred because of gross negligence by engineers at Windy Hostel, IICd. The hostel had been undergoing renovation for over a year and work had recently started on a new block today. Students were still residing in the 4-story hostel on the top 2 floors while the bottom floors had been vacated.
In order to complete his work on time, the contractor had allegedly told the workers to demolish the lower portion of the building and start renovation work on it, without considering whether the already considerably weakened, 40 year old structure could take the weight. The inevitable occurred, with the top two floors crashing down and burying and damaging many laptops.
In the words of one of the surviving students (who has requested to remain unnamed) "They were destroying the doors beneath our room and the balcony start moving wildly, deflecting as much as 1 cm. We ran to stop them, but the [expletive deleted] workers refused to budge."
The maintenance secretary of the hostel was allegedly gallivanting somewhere in East Delhi during the incident, meeting some foreigner. On being contacted he replied that he had an urgent meeting with someone he could not name -- a fact that has been noted by the investigating authorities who have taken him into custody. We managed to get a statement from the Chief Investigator, Mr. M. Adi "We have not ruled out the involvement of the maintenance secretary, and are also considering the foreign angle", obliquely referring to the recent statement by the President of United States of Pakerica, Mr. Obama Bin Bush.
Being a holiday, most of the students were sitting in their rooms during the accident, apparently trying to block their internet access so as to be able to prepare for their upcoming examinations. A quote by one of the IICians from our archives: "Our professors believe that we can obtain everything we need to learn by surfing the internet -- in fact they maintain a check to see that all students download at least 100MB of data every day to ensure they are spending enough time on the internet. We have learnt a lot but it becomes difficult to adhere to this rule during our minor exams so trying to outsmart our professors and blocking our internet access is a favourite pass-time for IICians during the exam season."
Most of the students were taken by surprise as the building came crashing down on them, and more than 50 laptops have been reported missing and are assumed to still be buried under the rubble, while 10 damaged (2 critically) laptops have been recovered. One or 2 lucky laptops survived on their battery life and were discovered as they were playing heavy rock and could be heard through the concrete. Worried students at IIC have kept a candle light vigil outside the laptop repair shop, with the very best technicians of the top laptop manufacturers including Nosy Baio, Sell and Compact working tirelessly to save the laptops. More technicians are expected to arrive from around the world soon. Excavation work to locate the remaining laptops is also underway.
Many IICians are still in shock, with many roaming around in a daze. A particularly sad case is that of a few students, who, being deprived of access to their laptops and the Facebook live feed appear to have devolved to animals -- with one imitating a bull, another squealing in French like a pig and the worst affected keeps trying to fly off the top of the hostel and is constantly restrained by his friends. It is currently not clear whether he has delusions about being a bird or being the Man of Steel (both being able to fly).
What has made this accident even more unique is the fact that there have been various reports of the accident being a complete fabrication and fallacy as people have allegedly communicated with the missing residents of the hostel (using their own laptops). In the public interest, we reiterate that the accident has happened and any such rumours must be disregarded as utter nonsense.
There have been suspicions of paranormal activity at the site of the accident because of these apparent messages and the top investigative news channel in India -- IndiaTV -- has sent its best reporter to find out the truth. The initial findings of the reporter will be presented on tomorrow's primetime show at 8 p.m. -- "IIC ke khooni engineer". Insiders (who wish to remain unnamed) have said that such a tragic parting of nerds with their computers can cause their ghosts to linger on till they manage to complete their last wish: to update their status messages. Only then will they be able to pass on to the afterlife. As always, there are many skeptics who have denounced this theory, claiming that the ghosts need to play one last LAN game of AoE.
In a surprise turn of events, famed teen impersonator and actor Aamir K. and ex-IICian and MBA B. Chetan came together in support of the missing laptops. They said that they has put aside all differences to be able to garner even more publicity for their film/book as people had stopped discussing their recent disagreements.
I get bored very easily.
It may be because I have nothing to do; or I've lost interest in what I was doing for some reason -- it being too repetitive, etc.; I have too little to do; what I'm working on doesn't seem to have any apparent purpose; or even if only some senses are occupied and others left alone.
I try to get over this foible of mine by listening to music -- hence the headphones hanging around my neck or on my ear, 24 by 7 by 4 by 12 by ~20. At least, by keeping my ears occupied I can relax, and possibly not get bored. This has also resulted in my having a 70GB music + video collection on my iPod.
But I digress.
I have come to realize that if I did not get bored so easily -- I would have achieved less than half of what I have today. There would be no reason for me to tread on the fine line of just enough work to do; I could have relaxed a bit more -- and perhaps enjoyed a bit less.
On the other hand, I have abandoned certain projects because I found out that they were no-where near as challenging as I'd imagined and hoped for, and were rather achievable -- and no longer interesting; because I no longer believed that the work I was doing served any purpose.
What pushes me -- and also stops me from working -- is my characteristic of getting bored so quickly. Paradoxically, it makes me give up and move ahead at the same time.
And ever since I've had more to do -- or more that I want to do -- I lose my patience with other things even more quickly. I can no longer comfortably watch a film in a cinema hall -- my hands are unoccupied, and depending on the film -- perhaps even my brain.
Doing only one thing at a time is possible only if it is interesting enough to merit my full concentration. Hence the rabid multi-tasking -- reading a book with lunch while listening to music or maybe watching television. Coding while watching a film or having a conversation. Social Networking while reading a comic. etc. etc.
What about you?
Boredom. My worst nemesis. My best ally.
Looking through the hits on my blog from Search, I noticed a few based on "how to study like an IITian". Frankly speaking -- I'm sure there are a lot of misconceptions floating around out there about how IITians study (further spread by the infamous 5 pointers) -- so in the interests of improving the level of information on the internet and in public interest, allow me to elaborate.
The Golden Rule, The First Commandment and the Code by which every IITian must live by is never do anything before the last minute. If the presentation is due at 13.00, completing it before 12.30 is blasphemy and before 12.00 means that the concerned IITian has been abducted by aliens and replaced by a doppleganger. Lab reports -- even those involving 30 pages of writing, 10 pages of calculations and 20 graphs each with atleast 50 points (all of which must be drawn exclusively by hand) must never be started before the night before it is due. You get my drift, I assume.
Those who actually buy books are an endangered species -- fast dying out. Books are arranged by jugaad, through seniors, not returning books to the insti library, from the hostel library, photocopies, not buying at all. And so on.
Class Notes are an alien concept conceived by the same alien dopplegangers I mentioned earlier. And are photocopied and distributed throughout. Repeatedly.
Reading room is a euphemism for something else involving socializing, ornithology, etc. Ex(hibition) Hall is often mentioned with an extra s appended on the right word. The only way to actually accomplish anything is to sit facing the wall, with a pair of headphones. And maybe blinkers.
Another phenomenon often observed is that group study is extremely popular. I always doubt the efficacy of this method, though people I know are extremely successful in following this method. Including my room-mate and batch-mates. I have failed miserably in earning marks through group study.
And of course -- time devoted to study. If we did devote as much time to studies as the 5(!?) pointers did, we would've been 9 pointers. Without the (excessive) blessings of the Gods and daily devotion periods. Self study is something you fit in between extra-currics, video games, sleep (4 hours or so) and classes. If you do.
Hope that helps. Yours as always.
--Me.
How to study like an IITian
A bit of background first: I joined Yahoo! Bangalore in May for a 10 weeks summer vacation internship. And my first industry experience.
So: what did I work on? Stuff that involved extensive use of a keyboard, monitor (2 in fact) and a touchpad (occasionally even a mouse). Apart from that, I'm not sure what I'm allowed to speak about, so to avoid any unnecessary complications, I'll leave it at that.
Let's start at the beginning, shall we. Day zero: Go and see the Y! building from outside. Getting into the business park was a bit difficult, so didn't try venturing into the building itself. Day one: Arrive at 8.30 in the morning, wondering what I'll be doing. Completely dressed up in formals, of course. I mean, which company doesn't expect shirts, trousers and black shoes? A lot of them, apparently. Including Y!.
9.30: My introduction to Y! . A 2 hour presentation followed by an intro to my team. I am completely amazed by the office -- themes for each floor; Cafe Coffee Day machines on every corner; neat and clean cubicles. Even better than what I'd expected after having seen the Adobe office in Delhi during India's first WordCamp. My computer wasn't quite ready yet, so I was given a quick introduction to search engines, the structure, etc. by my Team Leader and Manager. Which, in itself, was pretty cool. My computer was set up by the end of the day, but getting it to run was a pretty big problem without support.
Finally, near the end of the day -- it was working. I quickly set up/was helped in setting up my email, Cube No., etc etc. And customizing my desktop. So I was set to reading about a lot of stuff maintained by Y!, which I would be working on. And this kind of went on for the first week -- orientation, reading up a lot of stuff, presentations and clarifications by my team leader; and I click my way through to Friday, setting up a dev environment (customizing Vim, etc.) and so on.
Come Friday, and my team's changed. Which was a bit strange -- but there wasn't anything I could have managed to do wrong by then, so I wasn't that worried. And I probably shouldn't have been, from what I've seen of Y!. ( Y! is so much easier to type than any pronouns, or the company name.)
Week 2: I'm introduced to my new Manager and Team Leader -- my computer's still the same till now. And then I start reading up on new stuff that I'll be using/working on. Re-run 1st week, with a different context. Oh, and I also move to a laptop; as the desktop hasn't been removed yet, I start using both the Desktop's huge monitor and my laptop's average one together. The downside to a laptop -- I'm stuck with Windows; the up-side? I can carry it to conferences and all. And finally, near the end of the week, I'm told about what I'll be working on. Something or the other.
Week 3 onwards is kind of a blur -- I walk into office anywhere between 8 and 11, stay till anywhere between 1 and 3 (am), learn a lot -- both related to computers and pool -- annoy my team leader with strange questions related to the environment I'm working in. And have fun. Weekends are spent crawling around malls looking for books (Landmark being my favourite), having iced coffee at Gloria Jeans Coffee -- and wondering about the requirement of weekends in general for certain kinds of jobs. Occasionally I would be bored enough to walk into office, get some work done, play some pool. Also joined the gym during this time, and kept a goatee. And a moustache.
Somewhere around the middle, I gave my first presentation. I even spent half the night photoshopping 2 flickr images to make a nice image for my debugging tool. It was during this time that I started walking into office at around 10 and leaving anywhere between 1 and 3 am.
I distinctly remember the first night I spent at office. I had initially planned to leave at 11, as I needed some help from someone across timezones. By the time I was ready to catch a cab, it was pouring heavily; and the solitary cab that had managed to reach the office was already overcrowded -- I turned, went to the Cafe, bought a Red Bull (my first) and marched back to my cube. And worked till 3 am. Followed by 2 hours of pool with some other insomniacs (and people who had come back from home 'cause of power cuts). And then some more work till 7 am. After which I caught an auto home.
I spent 1 or 2 more nights at office after that day. There always used to be a few people around. The longest I stayed at office was some 30 hours or so -- during the hack day. I brought along a change of clothes, a towel and other toiletries -- stayed up throughout the night, worked on my hack (http://kunal-b.in/Tangent2) and had more concentrated doses of caffeine than I had probably ever had before. I'm sad to say that my hack bombed and didn't even reach the top 40, but it was an interesting experience.
Life went on, office, various malls et al. Landmark, novels and comics being my primary source of entertainment.
Perhaps too soon, I reached the end of my intern. I gave my final presentation -- which was well received (or I hope it was) -- and spent a week adding a bit more stuff to the final part of my project and handing over whatever I had done to a FTE Y!. And then, back.
After such a long, stream of consciousness typish post, a short summary: Went to Y!, set up camp in office, had fun, did some work, made quite a few friends, played pool and came back to college (but didn't want to).
Interning @ Yahoo!
A book is made from a tree. It is an assemblage of flat, flexible parts (still called "leaves") imprinted with dark pigmented squiggles. One glance at it and you hear the voice of another person -- perhaps someone dead for thousands of years. Across the millenia, the author is speaking clearly and silently inside your head directly to you. Writing is perhaps the greatest of human inventions, binding together people, citizens of distant epochs who never knew one another. Books break the shackles of time, proof that humans can do magic.
Passage: Carl Sagan, Cosmos
I have managed to survive two years of life at IIT.
I feel I've always been here.
I feel like I joined yesterday.
Now that that's cleared up let me review what all has been done to me and done by me in IIT. Very frankly, I've changed a lot over the past two years. The first, and biggest change that came around was -- from one month into IIT life -- I've been wishing I had not been selected in JEE.
Other stuff includes losing 18 kg of weight and almost 10 in of waist, becoming extremely adept at putting things off till the last possible moment and still completing (most of them) on time, losing all fear of examinations and tests after being subjected to all sorts imaginable, learning more about site designing and Photoshopping than I ever had, playing in concrete, mud and other stuff, carrying out pages full of calculations without forgetting where I started off, running around a hockey field daily for a year, playing Table Tennis in the dead of the night (3.00 am to be precise) ...
... taking part in Rendezvous, Tryst, Literati and a plethora of other competitions, getting an intern, applying for interns, missing treats, attending treats, giving treats ...
... considering night and day as abstract concepts -- good to think about theoretically -- but not practical ...
... attempting to talk to girls during my socials -- and failing/succeeding ('s a long story), filling my resume with a long list of PORs and going mad doing all the work that requires, surviving for months with exceptionally long hair and beard, giving vivas, interviews, getting blasted and praised by professors ...
... learning to play the guitar, keep time, quizzing, occasionally debating, word games and cryptic crosswords, running a library...
... blogging.
Midpoint.
Galli ka kutta: Crorepati. Yup, that's the title of a film. And unless you've been living under a rock for the past year, roaming out only when the world is dead outside, surviving on a diet of lizards and their relatives -- you'll probably call it the film.
Or, if you, like me, can't understand the hype surrounding it -- will stick with a film.
As a first attempt, let's just try to deconstruct and analyze the film -- you know, understand why it worked; maybe even get a hint of the answer to make a blockbuster, Oscar winner (apparently it's not 42):
- The plot: A guy born and brought up in a slum who has lived an extremely hard and cruel life manages to get selected for Who wants to be a millionaire? and manages to win some large amount of cash. Neat! So how does he know the answers to all the complicated questions that not even extremely learned men do? It is written. My first reaction to seeing the last line at the end of the movie? Not really printable.What, in your opinion stands out apart from other Bollywood films? Hero and heroine fall in love at a absurdly young age. They face various difficulties which keep them apart. Hero doesn't have enough money to elope with his love. He suddenly gets a windfall of cash through some means, things suddenly fall together -- boom! Everything's solved, there's a dance and everyone lives happily ever after. Except, perhaps the villainous/heroic anti-hero who sacrifices himself for the sake of the others. Brilliant, innovative screenplay.
- The director and co-director: We just might have something here. A globalized film? Something crossing nations? Interesting. Lets have a look at the rest of the cast.
- The cast: More or less Indian, with the exception of an Indian born and raised abroad. Who is undoubtely Indian of course. And derives all his acting skills from India. Without ever having lived here. Even his parents were born in Nairobi. But, of course, he's an Indian, and we love him.
- Screenwriter: Simon Beaufoy.
- Music: A. R. Rahman. The only guy who I can really appreciate. However, I don't really consider his music in Slumdog anywhere near the best he's made. Roza, anyone?
- Lyrics: Gulzaar. Fine. Nothing much to say here, really.
- The rest: A sprinkling of Indians in a western dish.
So -- what do we ultimately get here? A global film. Which shows the dark, true, underbelly of India (Shining). The truth behind the glamour. Which could only be exposed and truly depicted, without prejudice, by a foreigner.
Fine. I can even accept all of that at some level. What I cannot accept, however is that you only focus on the underbelly. It's as if you saw only the Dark Side of the Moon and never really understood why everyone else likes it.
To some extent -- the movie is good, and has some good points. The cinematography is excellent -- as far as I can tell as a complete amateur. The performances are excellent. But what I don't get is the awards that the movie is getting. There have been much better and more interesting movies produced in the past; the only thing they lacked and this has is a global cast. So why is it only this one that is getting all the attention?
Let's list out the awards won by Slumdog:
- 8 academy awards.
- 7 BAFTA awards.
- 4 Golden globes.
- Director's guild, Screen actors, etc. etc.
Does it actually deserve these? I think not. At least, not in comparison to its various predecessors. (Anyone remember Lagaan?)
So everything above just kept on bashing the movie. I didn't go into the plot details, because I really couldn't find that many worth spending my time typing out. Let's move on to the reaction to the movie here.
The movie has basically polarized the people, the media -- everyone except the politicians. They, seeing an oppurtunity to garner more votes simply jumped onto the convenient Oscar bandwagon (irrespective of personal opinion). The rest of the thinking society is divided among those who cannot but believe that the movie is completely Indian (with an emphasis on India) because its based on India, has Indian artists and was adapted from an Indian book. Then there are the few, who do not consider it truly Indian.
Frankly speaking, I really don't believe that it matters. At all. It's Indian, and it's not. End of the matter. I care about the fact whether Indians should be actually proud of the movie: you just have two options:
- You adore the movie, and consider it the epitome of cinema today. You accept everything it shows as accurate. Fine -- so why are you proud of an India full of bad schools, gangsters, prostitutes, cranky and eccentric game show hosts, torture? Did the Tehelka episodes make you proud?
- You don't accept everything the movie says. You speak and blog against it. Clearly, you are not really proud of it.
But still, a lot of people can't get the fact that a movie -- let's say, connected to -- India managed to win so many Oscars. And, going along with the sheep / mob -- they can't stop praising the movie, or proclaiming it Indian. I'm still waiting for proof that Danny Boyle's great great grand-Uncle on the maternal side was born in Bombay and brought up in Delhi. Surely, some ancestor of his has be Indian.
What really seems to have achieved the world's attention is that it's a mix of the H/B'wood genres; different actors and directors forming a melting pot. Agreed, that this is real, tangible evidence that the world is flattening and the whole East/West divide is breaking down. That does not mean that the media actually doing so is par excellence -- it's merely the first that is doing so.
Slumdog Millionaire
36 hours. 1 hacker.
His objective: hack his way to saving the earth.
How? by improving IIT Delhi's internet connection.
Well, not really. Yahoo! held it's first Hack-U competition in India at IIT Delhi this year (at least we have some advantage of studying in IITD). We were given all the tools Yahoo! had to offer, some excellent talks by Rasmus (the creator of PHP for those of you who didn't know), Christian and various others on the API's, etc. on offer as well as T-Shirts, bad snacks and pen-drives.
How could I have not participated. I ended up working for around 30 of those alotted 36 hours, having managed to clear my schedule with great difficulty -- I'm still catching up with the back-load -- and finished my hack: Tangent. (Yeah, yeah, I know -- but I couldn't come up with a better name.) I also stayed up for 35 hours at a stretch -- the longest time I've gone without sleep.
I ended up with an honourable mention. I can't prove it, though. You'll have to take my word for it.
So -- the experience of hacking for hours non-stop? Exhilarating. Specially when you end up with something useful (more on tangent later). The guys at Yahoo? Very very helpful -- they stayed up all night with us to help solve our problems: Christian, Rasmus and Subram (in no particular order). I even learnt a lot: JSON, the BOSS API, Twitter Search API, Pipes, getting stuff across domains, etc. etc.: a lot of cool stuff that was available on the net and I didn't know about.
So, the winners? A cricket query natural language parser, an intern finder and an anti-recommendation engine. Descriptions should be up somewhere on the net. If they aren't, ping me and I'll add a few descriptions.
Hack U IIT Delhi
I attended an interesting talk today -- it was a combination of a technical presentation by Mr. Vipul Ahuja followed by a talk on what's closest to every IITian's heart from the day he steps into college: online gaming his (future) job.
He spoke about a lot of topics; why to be a civil engineer or not, etc. etc.
There were three things he said that I really liked:
- You will always be catching up with other people if you go outside your core competency.
- Being a Civil Engineer requires a very high standard of integrity. You cannot mess around with the laws of nature. Whatever bribe/incentive you're offered -- that building will break down if you don't make it properly.
and last, but also my favourite:
- Command a salary; don't demand it.


Recent Comments