PostgreSQL, the Poor Man's Oracle

Via HN. Good to hear that ARIN have successfully migrated their database from Oracle to PostgreSQL. Not sure if they are using the plain vanilla or commercialized version.

PostgreSQL is the most under-appreciated and unknown open-source database. While more features were added, they've lost the popularity game to MySQL for two main reasons. Lack of Windows support in the earlier version and availability from web hosting provider. I wish more people would add PostgreSQL into their technology stack consideration instead of just MySQL.

Be Helpful

"One day I was talking with one of our best engineers, an employee I’ll call John. Before the layoffs, he’d managed three engineers, but now he was a one-man department working very long hours. I told John I hoped to hire some help for him soon. His response surprised me. “There’s no rush—I’m happier now,” he said. It turned out that the engineers we’d laid off weren’t spectacular—they were merely adequate. John realized that he’d spent too much time riding herd on them and fixing their mistakes. “I’ve learned that I’d rather work by myself than with subpar performers,” he said. His words echo in my mind whenever I describe the most basic element of Netflix’s talent philosophy: The best thing you can do for employees—a perk better than foosball or free sushi—is hire only “A” players to work alongside them. Excellent colleagues trump everything else."
-- Patty McCord, How Netflix Reinvented HR, emphasis added
One of the best read this weekend. Excellent write up on Netflix's, (the company that provides on-demand Internet streaming media), human resource policies. So many gems from the slides on how they define their company culture but not all are applicable as different countries have different labour laws.

While you can't always get excellent employees, but at least find those with good attitude and nurture their aptitude. Everyone want to find a good employee but nobody want to train them up. As for employee, if you're falling behind, re-educate yourself to stay competitive or just move on to do something else.

Discussion at Slashdot has an opposite point of view.

Daily Working Routine

As a person who want to best use of his time, I am always curious about other people productivity hacks. Semih Yagcioglu recently wrote about his daily working routine which is something everyone can learn a few tricks from. Notable activities from his working style.

1. Break your day into morning, afternoon, and night routine. If possible try to slot in 10 to 15 minutes of exercises. Unfortunately I lost my Pedometer (walking steps counter) and now currently saving money to buy Fibit Force.

2. Similarly, I also work in a Timeboxing way or to be specify, using Pomodoro technique. Unfortunately, I do not prioritize my tasks to my liking and occasionally need to "fire fighting", where you caught up in many unexpected, urgent, and sometimes, not important tasks.

His Inbox Zero proach make senses. Any tasks or emails should be acted upon by replying it, delete it, or just delegate it. The 1-3-5 Rule can be handy in setting your daily goals. The Bullet Journal approach its something new for list-maker like me.

3. ZenPen is also something that's new to me. A cleaner version compare to Writer, the online writing tool I currently use.

In short, be aware and keep tracking of your to-do list and make adjustment accordingly. Don't dwell on the technique, focus on your tasks. In coming 2014, going to get myself a smart phone to complement my current pen-and-paper approach, let's see how this goes.

Decomposition Technique

Decomposition is one of the important skills for a programmer as we need to break any problems into smaller and manageable chunk. Bumped into this top-down approach on achieving that. Step as follows:
  1. Describe an overview of the problem in your head, with words.
  2. Try to write code that is the closest to those words
  3. For every unimplemented thing, repeat until done.
Pay attention to step 1 and 2. If you can conceptualize the problem and solution in your head and describe it in most layman term, surely the code produced will be easily understandable. As they said, good programmer are good writer or rather good communicator, they can convey their ideas across.

Similarly, another approach is to use reference pattern or application architecture. But this is at different scale, more of the overall architecture. Example is Command Query Responsibility Segregation (CQRS) which is an alternative model to CRUD model. Still reading and try to learn other approach than CRUD.

Teaching Subversion ?

After many years of using, encouraging, and observing developers using Subversion led me to a conclusion, it was never a technical issue but a people issue. Some lessons learned:

Management support
Unless the management, especially those without technical background, support the use of any source control to be the integral part of development process. Otherwise, you will be wasting your time and your breath.

Can anyone still practice software development without source control? Yes, you can. Short term project, especially those can be handled by single developer. Or one developer per module or folder approach where source code are shared through one centralized file server. Hence, you will encounter files in project that looks like this:
index.php
index_20131213.php
index_20131010.php

Yup, the developer is cooking his own source control. I cringes every time I see anyone does this. The saddest part is such practice is still so prevalent.

Company that don't value the importance of source control does not realize the benefit of safeguarding their intellectual property and other assorted gains in using it.

Use source control properly
Troy Hunt's 10 commandments lay down the rules on how to use it correctly. I will like to focus on two major difficulties I observed especially for those (me as well) who just starting to explore source control.

Write a meaningful and better commit message. You should explain the why and not really the how. Occasionally you will read empty commit, repeated (e.g. "latest update"), or just plain wrong commit message. These are useless and not helpful for anyone to review back any previous changes. Why so ? Because writing good commit message is hard, especially those whose mother tongue is not English. To solve this, set a standard log message format and encourage the developer to break each task into smaller chunk.

Commit early, often, and small / atomic. Break a large task into smaller sub-tasks. Unless the developer is stuck at something, there should be multiple commits per day. Also, this is to prevent those developers who like to commit everything in one shot.

In short, having the right tool and convention are not sufficient enough unless the developers are willing to use it correctly.

Programmer Productivity

"I would submit that the appearance of hard work is often an indication of failure. Software development often isn’t done well in a pressurised, interrupt driven, environment. It’s often not a good idea to work long hours. Sometimes the best way of solving a difficult problem is to stop thinking about it, go for a walk, or even better, get a good night’s sleep and let your subconscious solve it. One of my favourite books is A Mathematician’s Apology by G. H. Hardy, one of the leading British mathematicians of the 20th century. In it he describes his daily routine: four hours work in the morning followed by an afternoon of watching cricket. He says that it’s pointless and unproductive to do hard mental work for more than four hours a day."
-- Mike Hadlow, emphasis added
In other word, pretending to be busy is cheating and constant fire fighting indicating a repayment of technical debt. Long working hours? The lack of proper project management and client expectation.

Fuggit, just do it

"I'dropped out' of my life of making video games this summer, got rid of everything I own and set off on a journey across the US by bicycle. Every day I wake up in my tent and make a conscious decision to climb on the bike, with an awareness that something amazingly bad might happen, however something amazingly good might also happen. I so far have been fortunate for I have enjoyed lots of amazingly good moments, and have learned it is an acceptance of the prospect of very bad things that makes the trip more remarkable."
-- cmos, emphasis added
Share the same sentiment as well especially after I slipped on my motorcycle recently. We sometimes forget that we're not the exception and invisible. You should be always aware of the danger when riding a motorcycle.

Maybe in coming 2014 I should look into game or graphic development. Something that drew me into the field of development in my younger years. Is time to revisit the long lost love of mine.

Breaking into Programming

"From time to time, I run into people who are interested in breaking into programming. Last night at the company holiday party a guy (we’ll call him Sam) walked up and introduced himself, asking for advice on how to move from his current role over to development. Sam’s attitude impressed me – guys with a genuine desire to learn go places quickly. And on many occasions I’ve hired someone very green simply because I could sense a genuine interest in the craft and a hunger for knowledge. I’ll take attitude over aptitude."
-- Cory House, emphasis added
Same opinion here. Genuine interest and hunger for knowledge are the first two of out of four (more on that later) important qualities for newcomer in programming profession. Why so? Simply because all programming is generally maintenance programming, you will read more than writing code, especially by others, and you're going to hate what you've encounter. Unless you've genuine interest to sustain your motivation, otherwise it will be mundane, stressful, and soul-crushing.

Why all the negativity towards software maintenance? When you're taking over a legacy software project, you're going inherit all the unfortunate consequences that come with it. Undocumented business rules, inconsistency coding style, lack of or the abused of version control, no testing, no database referential integrity, big table (not the NoSQL storage but one table with > 50 columns), disgruntled stakeholders, and more are the typical encountered situations. *The most painful part is you're enduring all these due to the management or technical decisions made previously which you've no part of making and influenced.*

Which is why, as I observed, there exists a special group of developers or freelancers that focus on hacking the stuff up fast and move on to other projects and companies without doing any or minimum maintenance. These people know they're hacking stuff up and they know the happiest way is not to maintain it. Honestly, I don't blame them. Most stakeholders deserved what they're requesting for, something that is developed fast and cheap. Later, they will hire another bunch of people to maintain it. Off course, they will keep asking why is it so slow and expensive to churn out another feature. How can you move fast forward when you're paying technical debt? Nothing against this approach, fast and cheap works well for a startup which want to test the market with a Minimum Viable Product (MVP).

Back to the two other desirable developer traits. First, humility or as what what Edsger Dijkstra argued, accept your brain limitation, be a humble programmer. Let go of your ego, someone out there is worse or better than you, no need to be smug and insecure. Embrace and improve upon your incompetence, learn from them, let them inspired you. Find the gap and fill the void. Furthermore, can-do attitude doesn't means say yes to everything. Is okay to admit your cannot-do anything.

Second, empathy, the feeling of being in others' shoe. Keith Wesolowski recently stressed that "empathy is a core engineering value" which I believe, is something to be instilled into every developer. Understand your user pain, optimize and automate their works. Follow the coding convention, write proper documentation (the business rules or the whys), and be helpful to your fellow programmer.

In short, ask yourself, are you genuine passionate about software development, love learning, humble, and empathy person? If so, maybe this profession is right for you.

Learning and Earning Equally?

"You're always on one side or another of the learn vs. earn. Given the nature of equity and corporations, always know that owners reap the rewards and workers are transacting their time for money. But unless where you work is a co-op where profits are evenly distributed, you'll never extract the full amount of value that you create for the company. Always know whether at that moment you're learning or earning. If you're learning, then it's worth it. If you're not, you better be earning (e.g. being a founder, being a share holder). Otherwise you're just wasting time. "
-- Lessons from 2^5 that I wish I knew at 2^4, Garry Tan, emphasis added
How can you juggle equally between earning and learning? That is something I realized the hard way in my career life as a code monkey. As you age, time without interruption is a limited precious resource. There are always constant interruption from every part of your life.

What kind of adjustment I need to make for me to increase both my learning and earning? Note that earning more does not means gaining more money, but to save more through less spending.

Modernize Your Legacy PHP Application

How? Code base restructuring. As suggested by the video presentation below, these are the recommended 2 steps.

1. Consolidate classes for autoloading.
Just implement autoloading according to PSR-0 specification. Move php script around and remove all the require or include statement. Do make sure is one class per file.

Also, group all your helper functions into classes and call these global functions through static or instance method. Example of static method.
xxx_get() to XXX::get()
xxx_set() to XXX:set()

Some of you may argue this does not bring any sort of benefits except more typing. I do agree as occasionally we sometimes have a few orphaned global functions which hard to be grouped in any class. Surely we're not going to put these helper functions in a class called Miscellaneous or Common class.

2. Convert global to injected dependencies
Those dreadful global variables (those using global keyword) which sometimes accidentally which values may reassigned half way through your script.

Invalid UTF-8 Sequence in Subversion Again

I remembered I encountered this issue before few months back in March. But yet, I can't remember how to solve it. My previous solution to detect the culprit filename with invalid encoding was using strace but this post recommended a better, more accurate approach to detect it. The detection is straight forward, just convert the hexadecimal code to ASCII.

Let's look at my previous example
$ svn up

svn: Valid UTF-8 data
(hex: 49 50 )
followed by invalid UTF-8 sequence
(hex: a0 2d 56 69)

My issue last time I did not fully grok the error message. What the svn client tried to tell me is there is a filename in hexadecimal sequence of 49 50 a0 2d 56 69 that is causing the corruption.

Convert this hexadecimal sequence to ASCII and the full culprit filename known as shown below.
$ echo "\x49\x50\xa0\x2d\x56\x69" | xargs -0 printf
IP�-Vi

What you can do right now is find any file that contains this sequence of characters of IP�-Vi and remove it.
$ ls IP�-Vi*
$ rm -rf IP�-Vi*

Whoala ! There you have it.

Switch to Gnome 3.10

Regardless all negative experiences vented by numerous people on Gnome 3.x, I have the opposite and surprised experiences after switching to it from Unity Desktop. Everything seemed fall into place and far more stable and pleasant looking than the Unity. Commands to upgrade as follows:
$ sudo add-apt-repository ppa:gnome3-team/gnome3-next
$ sudo apt-get update
$ sudo apt-get install gnome-shell ubuntu-gnome-desktop

$ sudo add-apt-repository ppa:gnome3-team/gnome3-staging
$ sudo add-apt-repository ppa:gnome3-team/gnome3
$ sudo apt-get update && sudo apt-get dist-upgrade

$ sudo apt-get install gnome-weather gnome-music gnome-maps cheese gnome-documents

No More Excuses

"Many of them have skills but neglect to even attempt to put their skills to work. And when you ask them why, all they have for you is excuses. My race this, my gender that. We are living in an age when it is easier than ever before in human history to use your skills and ideas to positively impact your world."
-- Jon Doe
The quote above really resonate with me. As you age, time seems go faster and you've used up all your excuses of not doing something worthy with our life. How about those long lost dreams of doing something that change the world in the positive manner? Time to think hard on this matter and act on it. Get out of your comfort zone and take the first step. Reach for your next milestone. Make that decision.

Relearning Photography

Stumbled upon this photo (see screenshot below) of children playing near the village of Baudrémont by Alex Webb which reminds me about my loves for photography a few years back. Similarly to Sam Abell, both photographers works are known for its serenity qualities. However, most Alex's compositions are aesthetically more complex and brilliant compare to Sam's simple and direct approach. A lot of planning, pre-composition, patience, and waiting to achieve any of his shots.


All these talks about photography reignite my interest in photography again. While some may argue that you should use the right camera for the right job. But, as I've learned all these years, always pick the camera that match your personality and your wallet. As I am currently striving to live a minimalist and healthy lifestyle, hence, no more burdensome DSLR system but instead, a plain old point-and-shot camera, with one extra battery. Additionally, this setup will also complement the journalling habit that I'm trying to cultivate. Expect more photography post in coming 2014.

Can you survive KL on RM10/day?

Someone posted this question in Reddit. Short answer, it depends, maybe is possible. But for me, not possible unless I eat instant noodle everyday, sacrifice lots of convenience, and discipline enough to be constantly aware and track my spending religiously.

Breakdown of the compulsory basic expenses of mine daily needs. Note the scenario excludes all other expenses like rental, entertainment, mobile phone, and others.

1. Transportation from and to workplace
Being a avid bike rider, my weekly petrol consumption is around RM12. That is like RM48 per month. Mind you, my bike is around 14-plus years old, hence fuel efficiency is not that great. In short, it will costs me around RM1.6 per day.

2. Breakfast
A tin of Milo (a very common morning drink around here) and Hup Seng Cream Crackers. 2kg Milo is around RM36 and the cream cracker is around RM 12. Both items can feed you for a month which will cost around RM1.6 per day.

3. Lunch
My co-worker told me there is a mixed rice or economy rice stall which sell 3 dishes and one bowl of rice for a price of RM3.5.

4. Dinner
Normally, mixed rice again at my place or mamak stall. Average price is around RM5.

To sum up, the calculated daily spending is roughly RM11.7 which is, RM351 per month. Unfortunately, still RM1.7 more than the expected daily RM10.

Even so, is so hard to limit yourself to this daily figure of RM11.7. Is best to limit the amount to RM600 per month or RM20 per day. There are so many unexpected influences of better half, stress, boredom, and myriad other reasons.

Best way so far for me is always keep and track your spending. Use paper money and pay everything with cash. The moment you pay anything, jot it down in your little notebook. You will feel the pain when you're aware of paying something with cash. This was proven to be scientifically true.

At least that should be a good start for me to try again to live within a monthly budget of RM600 and continue my journey for a more minimalist lifestyle.

How to design a class?

"Start with the simplest thing that works. That thing will probably be just a function. Grow it from there. If it gets too big, split it. If you find that you pass the same 12 parameters to a bunch of functions - factor out a class. If you do the same thing in a bunch of classes - abstract it out. Keep it DRY. Keep it SOLID. Rinse and repeat. This way you end up with a useful class hierarchy - and OOP won't be awful."
-- azov, emphasis added
I like his approach, build working stuff incrementally, from procedural towards Object-Oriented (OO) design when needed compare to the more theoretical and classical way on how to design a class. Way more pragmatic for those coming from more procedural experiences. Based on my observation, some programmers still struggle on adapting an OO mindset. There is nothing wrong with procedural approach but if you're using a framework, at least try to understand and follow the underlying OO structure.

Don't Be a Sheep

"Most Americans, for example, are deep in unnecessary debt, overweight and poorly nourished, inactive and stressed out, and self-sentenced to a mandatory career of unsatisfying work just to stay afloat. We constantly buy things we can’t afford and don’t need, and the majority of the trading we do does not increase our net happiness. And all of this is done with virtually no awareness of how we are affecting our own ecosystem – the tiny veneer of air and plants that is the only thing between us and the lifeless vacuum of space. In fact, it would be difficult to imagine a less efficient way to maximize “Utility” than what the modern consumer does."
-- Mr. Money Mustache, emphasis added
Not just America, but other part of the world as well. One way to reduce this insanity is to apply these age old golden rules of stop effing compare yourself to others, compare yourself to you from yesterday. Stop following the herd, the message the author tried to convey. To quote (emphasis by me):
" We design our entire lifestyles by looking around us to see what everyone else is doing. Most of us position ourselves in the middle of the herd, and start feeling deprived if we sense we are near the bottom. The problem arises when the herd is comprised mostly of sheep, responding blindly to their own irrational instincts. So as a society we have a tendency to automatically run ourselves straight off of the nearest cliff."
One thing I learned from the post is when buying something. Rather than comparing the relative prices of the item you want, check your intention with your needs and budget. Want that elegant watch? Ask yourself, do you need it and do you have the extra budget for it rather than wasting time looking for the best offer.

The 555 Notebook

"What is interesting, in these few weeks since I started using the notebook, is that I can immediately see how productive I have been and also the urgency I attach to the items that get written into this notebook."
-- Soo Ewe Jin, emphasis added
Similarly, I am still stick to the archaic way to manage my information, especially my to-do list. All these years of trying Palm, desktop computer, and mobile phone as my organizer, I still revert back my the traditional paper notepad. Maybe is just me, but I always feels more more personal and satisfying to write things down manually and cross them out when done. Furthermore, scribble down your thoughts forces you to slow down and thinks things thoroughly without worry about any battery life.

Open-office Plan

Mind you, we're not talking about the the office suite but rather about the workplace layout.  Good discussion at HN on supporting and against such arrangement. For me, Pvnick's description of a hybrid environment of open layout and private space is the best combination. You need an open layout to create bonding and increase communication and use private space to get work done without interruption.

Some recommended noise reduction, substitution, or cancellation audo devices from the discussion are:


Will try to look into ATH-M50. reddit/r/headphone has been raving non-stop about this headphone. Is time to start another fund to buy this baby.

Still Doing Cat Picture Project ?!

"For everyone reading this: if you are tired of making websites and iPhone apps for people to share their cat photos, and want to do something more consequential, consider going into computational genomics. Although Sanger sequencing was/still is used sometimes, the "next-gen" sequencing methods that have become centrally important over the last decade generate massive amounts of data that require a lot of computational analysis, something that most scientists in the field could use assistance with."
-- w1ntermute, emphasis added
Interesting. Should look into this Computational genomics. Two years ago, I made a note to myself not to work on any cat picture project anymore. Yet, I still stuck doing something similar as well in corporate world. In other words, I have not been aggressive in exploring the domain of Bioinformatics and make the best use of my skill set (what ever left of it) to anything (non-political or religious) with social impact. (I know, sounds very cheesy).

Fellow HN reader, scottalpert asked a similar question few days ago on finding a software job that help society. Numerous great answers were given but sadly, mostly are oversea positions.

There will be a lot of self-reflection in coming months, especially we're at the end of the year. What will happen in coming 2014 ? Only time will tell. Stay tuned.

Getting Into the Zone

"I'm pretty happy with them. I'm fairly easily distracted by noises: Heavy walking noises, talking, laughing, phones ringing, folks rustling potato chip bags... It can all mess up my concentration if it comes at an inopportune moment. I'm the only programmer here so most of the folks here do not understand how easy it can be to derail someone that's coding when you catch them in the middle of a thought."-- robflynn, emphasis added
Programming is a task that required a lot of cognitive processing. Hence you need to be totally immersed when coding. Any distraction will break your flow and is hard to go back to that state again. This is especially true if your're working in an open-plan office.

Rather than shifting the blame on your surrounding, why not make some adjustment to yourself ? I have been asking the same question for many years. How do you get back into the zone before or after any distraction? I've been trying two ways these days. Pomodoro time management technique and noise isolation devices.

First, Pomodoro technique. Seemed to work for me for the past one year. I always can get back to my last task safely without any issue even I may lost track of things while fire fighting.

Second. Headphone or earmuff. Decided to ditch the headphone approach as you just can't listen to music non-stop. Furthermore, wearing a headphone is not noise cancellation, is noise substitution. I am currently testing earmuff approach but experienced mixed results. There is some form noise isolation but the noise cancellation still a lot to be desired. Compare to a headphone, earmuffs felt tighter, less noisy, and you looks like a flight deck crew on one of those aircraft carriers. Also, is quite difficulty to carry a conversation with other.

In short, will still testing different kind of earmuffs and find the right one that can help me get into the zone as quick as possible.

Am I a Software Engineer ?

"I was with you until you got to this line. Let's be brutally honest: *the limiting factor for most of today's software projects (i.e. CRUD websites and iPhone apps) is not technology. It's developer competency, experience and self-discipline. I'd go so far to say that *most working software developers don't even understand the fundamentals of the technologies they're using -- it's why you see people replacing their relational databases for key-value stores, then trying to re-invent database join algorithms from scratch in the application layer. Or why every new generation of "engineers" re-discovers asynchronous programming in a new language (then promptly writes a framework in Blub...because Blub is so much better than last year's Blub.)" 
I have to concur with what fellow HN reader, timr said above (emphasis added) regarding the limiting factor of software projects. Sad but true, history keep repeating itself.

Compare to last time, we face less challenging technical issues as most of these have been solved before. Furthermore, these technical problems are googable anyway. Software development, especially web application development is nothing fancy. Once you settled down on a framework, standard conventions, version control, and bug or issue tracking. Everyday challenges are merely mundane SCRUD (Search, Create, Retrieve, Update, and Delete) implementation according to the business requirements.

So, what are the more challenging tasks these days? People, mostly relates to people issues. Especially trying to get everybody (management, product owners, and developers) to work together towards a concrete direction. Which or whose way and direction? Not sure? Yup, the problem still remains and it's damn tiring you have to focus on this bullcrap issue everyday rather than technical stuff.

I used to call myself Software Engineer but not anymore. What we are doing are not really related to engineering, as in classical engineering at all. These days, it just Application Developer or to be exact, Web Application Developer regardless what other kind of title given to me. But after reading Chris Aitchison's post, might as well start calling myself Software Gardener. or more derogatory name like Code Monkey, or Cowboy Coder.

Ubuntu 13.10 Cannot Shutdown

It had been a few days since I upgraded to Ubuntu 13.10 where I still cannot shutdown my lappy properly, the shutdown dialog was missing. Main cause seemed to be all those dock app (I am using Plank) was auto-started. Temporary solution is to delay your dock app from auto-starting as shown by command and screenshot below.
sh -c "sleep 5 && /usr/bin/plank"

Weird but it did solved my issue.


svn mergeinfo

We've slowly started to utilize Subversion branching and merging. Previously, due to some policy beyond my control, the project was branched, merged, and reviewed manually through me. But luckily these days, we've slowly started to truly utilize actual Subversion branching and merging. It will take a while for all of us to familiarize and settle down on such development style.

Several commands regarding branching and merging.

1. To create a branch
$ svn cp ^/trunk ^/branch/feature-x

2. To visualize the history of branching
$ svn mergeinfo ^/trunk ^/branch/feature-x

    youngest common ancestor
    |         last full merge
    |         |        tip of branch
    |         |        |         repository path

    100               120   
    |                  |      
  -------| |------------         trunk
     \                        
      \                       
       --| |------------         branches/feature_x
                       |      
                       120 

3. To merge from trunk to feature branch
$ svn merge ^/trunk ^/branches/feature-x

4. To check what have been merged into your branch
$ svn mergeinfo ^/trunk ^/branches/feature-x --show-revs merged

5. To check what have NOT been merged into your branch
$ svn mergeinfo ^/trunk ^/branches/feature-x --show-revs eligible

Is what I am doing actually important?

Via HN. Yes. If you're doing it only for the sake of making a living. If not, I doubt most of us are doing anything actually important. Define important. Something that creates values, improve people live, and you feels that you're doing the right thing. Something like what Mac Senour felt where the game he created let his cousin and her daughter spent more time together and his niece became an avid reader because of that. Certainly not what fellow HN reader, fit2rule experienced when the game he created actually made a 12 years old kid addicted to it in a bad way.

I once felt the same way few years back. Yes, indeed the software project was important and it did reduce corruption a bit. But in the end, I moved on. It turned out what I perceived to be important was not that actually important. My health and career took a toll (mostly myself to be blamed). If you kept doing the same thing over and over again, your technical progress will comes to a standstill. You will most likely hit a plateau. As what they said, if you're in a hole (comfort zone), stop digging, and crawl out. Hence, the best and only way is to move on. Pick your problem wisely as some problems are not worth solving or resolving again.

In short, do the right stuff, and do the actual important right stuff (I am still looking). But remember, never at the expense of your health and your family.

Upgrading to Mercurial 2.8 in Ubuntu 13.10

Update: A far more direct installation method using pip
$ sudo pip install http://mercurial.selenic.com/release/mercurial-2.8.tar.gz

Mercurial, the distributed version control tool was recently released to version 2.8. Decided to give it a try after all these while. However, the default installed version in Ubuntu 13.10 is still stuck at version 2.6.3. Hence, try to upgrade it to this latest version. Installation procedure as follows.

1. Just to confirm, find the installed version using different methods. I didn't realize there are so many alternative ways to find a version for a installed packages.
$ hg --version | grep version
Mercurial Distributed SCM (version 2.6.3)

Or
$ dpkg -s mercurial | grep Version
Version: 2.6.3-1

Or
$ sudo apt-get install apt-show-versions
$ apt-show-versions mercurial                                                                                                                        
mercurial:amd64/saucy 2.6.3-1 uptodate

Or
$ apt-cache policy mercurial | grep Installed
  Installed: 2.6.3-1
2. Add the Mercurial's PPA repository. Update and upgrade your packages.
$ sudo apt-add-repository ppa:mercurial-ppa/snapshots
$ sudo apt-get update
$ sudo apt-get dist-upgrade

3. Check the version again. Nope still at version 2.7.2. Have to do an installation by source code compilation.
$ hg --version | grep version
Mercurial Distributed SCM (version 2.7.2+48-5b327880a660)

4. Download the latest source code (currently 2.8) from the official website. Extract the source code and try to compile the source code.
$ wget http://mercurial.selenic.com/downloads
$ tar zxvf mercurial-2.8.tar.gz
$ cd mercurial-2.8
$ make

5. You will encounter some missing Python library. Install all the necessary packages in order to compile the source again. Before that, please make sure you have uninstall existing old Mercurial installation.
$ sudo apt-get remove --purge mercurial
$ sudo apt-get build-dep mercurial

6. Compile the source and create a deb package using checkinstall so we can remove it later.
$ make install && sudo checkinstall
$ hg version | grep version
Mercurial Distributed SCM (version 2.8)

How An Expert And Beginner Code Fizz Buzz in Go

This complex solution for Fizz Buzz in Go caught my attention. Decided to write a simpler version for comparison. Still trying my to grok the former code which uses Go's channel to implement concurrency. It has been a while since I last read Go's code, let alone such complex one (for me). Still a lot to catch up.

On a related note, Fizz buzz, which I always thought the typical common way to filter programmer who can or can't code, is actually a children game that teach them about division.

Replacing MySQL with MongoDB ?!

Within this month, four persons have told about migrating to MongoDB from MySQL. When asked why they need to migrate ? Only one person justified it correctly. They need to store a lot of schemaless documents while the other three just use it for the sake of using it. In other words, chasing fads.

Disclaimer time. I have installed and tried MongoDB locally but never use it thoroughly in any live production system. Hence, I have limited experience using it.

But after reading all these comments, it does make you wonder about the the stability of the system. Judging by their heavy marketing push which reminded me of MySQL when they first started out. It seems MongoDB is market ready but "almost" production ready. Instead of totally replacing your MySQL database. Why not look into HandlerSocket, a NoSQL plugin for MySQL.

MongoDB has become the latest buzzword, especially around local .my tech scene. Web scale FTW !

PHP 5.4 and MySQL 5.5 in CentOS 6.4

Due to some shenanigans in office, unfortunate miscommunication, and effing messed up provisioning, have to redo the LAMP installation again in CentOS 6.4. Installation steps as root shown below.

1. Install the Remi third party repository.
$ rpm -ivh http://rpms.famillecollet.com/enterprise/6/remi/x86_64/remi-release-6.4-1.el6.remi.noarch.rpm

2. Enable the Remi Repository and update.
$ vim /etc/yum.repos.d/remi.repo
$ yum update

3. Install the Apache Web Server, Mysql Database Server, and PHP. Configure and set the MySQL's password as well.
$ yum install httpd php php-mysql mysql-server
$ mysql_secure_installation

4. Enable both web and database server start upon reboot.
$ chkconfig httpd on
$ chkconfig mysql on
$ reboot

On Object-Relationanl Mapping (ORM)

"ORM's are for basic CRUD crap.SQL is for queries that matter. My ORM usage is almost entirely limited to: get this record, change these values, save it. Anything involving complex joins/ unions gets thrown to raw SQL. Better yet, stored functions on the DB side. Postgres is awesome for this."-- fein, emphasis added
This is even so true if you're inheriting old legacy system with one of the most common database table design issues, table with many columns. Not like 10-plus columns but more like 50-plus to 100-plus columns per table. What worse, new columns were still added to these tables.

Why so many columns per table? Three reasons, lack of database normalization knowledge, weak in writing SQL join or support was poor for the chosen database system, and you're optimizing for convenient.
The last reason is the root cause of this design error.

Let me elaborate this. If you're pressing for time, you will start with a simple table design for any CRUD operations. Writing SQL queries were simple and straight forward without any speed penalty. Or you may start with proper database normalized design but with extra SQL queries and speed penalty due to weak SQL JOIN support (I am looking at you, MySQL). Hence, which one would you prefer? Off course the former choice.

To be fair, under certain circumstances, big table with many columns is the preferred design choice. This is even truer if referential integrity was not needed and you want to denormalize the table design to optimize for reading speed. In other word, you don't mind redundant data and trading speed for storage size.

For those tables with lots of columns, ORM really helps a lot during refactoring. We can slowly remove all those raw CRUD SQL without making any changes to database schema. Hence, application code was shorter, readable, and more maintainable. Is always harder and more dangerous to refactor database schema where you haven't really grok the business rules involved.

Based on experiences, setting relationship between tables using an ORM was painful and troublesome. Most ORM libraries follows a certain rigid rules of connection the relationship. Suitable for new database schema but not legacy database schema which first, does not follows standard convention, and second, contains more complex many-to-many relationships.

In summary, use ORM for refactoring legacy system, but only for simple CRUD operations. But use raw SQL for more complex SQL query like JOINs or multiple rows update or deletion.

Free and Clean Up Hard Disc Space in Your Ubuntu System

My lappy seemed overly sluggish. Upon checking the disk space (shown below), some clean up or packages removal was seriously needed.
$ df -h
Filesystem   Size  Used Avail Use% Mounted on
/dev/sda5     232G  211G  9.8G  96% /

1. Clean the downloaded debian package files.
$ sudo apt-get clean

2. Using deborphan to remove unused orphaned packages.
$ sudo apt-get remove --purge $(deborphan)

3. Clear Google Chrome cache files.
$ cd ~/.cache/google-chrome
$ du -h .
32M     ./Default/Media Cache
274M    ./Default/Cache
305M    ./Default
305M    .

$ rm -rf Cache/* Media\ Cache/*

4. Remove unused packages using software-center, unfortunately, there was some issue with SSO authentication. Fixed it by reinstalling oauthlib package.
$ sudo pip install --upgrade oauthlib
$ sudo software-center

Ubuntu Laptop Power Management Using TLP

If you remember in my previous post, my Thinkpad Edge E420 does not support battery charge thresholds. Although disappointing, I stumbled upon this console tool, TLP, which help to optimize your laptop battery life through toggling on and off different devices such as bluetooth, wifi, and others.

1. Installation is pretty much very straight forward, which is also one of the main reason I like to use Ubuntu.
$ sudo add-apt-repository ppa:linrunner/tlp
$ sudo apt-get update
$ sudo apt-get install tlp tlp-rdw

2. Start the program immediately and see the battery status.
$ sudo tlp start
$ sudo tlp-stat -b

3. Applying either in battery or ac power mode.
$ sudo tlp bat
TLP started in battery mode.

$ sudo tlp ac
TLP started in ac mode.

REPL for PHP - Part 1 : Built-in Interative Shell

A Read-eval-print loop (REPL) is a simple and quick programming environment for testing short code snippet or debugging. In PHP, there are five REPLs namely PHP's native interactive shell, Boris, Tiny PHP REPL, PHPSH, and Wigwam. Let's go through each one of them.

First, let's start with the default built-in REPL environment which was available since PHP 5.1. For interactive mode (you can scroll back each line of code through history logging in ~/.php_history), just make sure the readline extension is enabled.
$ php -m | grep readline
readline

$ php -a
Interactive shell
php >

One of the nicest feature is auto-completion (just type the tab key), extremely useful if you can't remember the exact functions or classes name.
php > print easter_da
easter_days  easter_date

Another useful feature is setting your viewing pager. Useful when you're expecting long result that spans multiple screens. Unfortunately, this setting is only available from PHP 5.4 onwards.
php > .pager=less
php > phpinfo();

Unfortunately, there are two limitations. First, there is no syntax highlighting support thus making reading the code or result a bit difficulty. Second, you have to manually print out result of every evaluated expression, which is repetitious and troublesome.
php > print_r(new DateTime());
DateTime Object
(
    [date] => 2013-10-13 01:49:44
    [timezone_type] => 3
    [timezone] => Asia/Kuala_Lumpur
)

Changing Soft Link Ownership

Soft link [1] is a special file that points to another file or folder, as in, an alias to another file or folder. Let's illustrate this in Ubuntu 13.04.

1. Go to the /tmp folder and create a sample dummy file called a.
$ cd /tmp
$ touch a
$ ls -l a
-rw-rw-r-- 1 kianmeng kianmeng 0 Oct 12 12:37 a

/tmp is the global temporary folder in most Unix or GNU/Linux. As the name implied, most applications use this folder to store temporary files and these files are removed after each reboot. The touch command, which is supposed to update the timestamp of a file can be used to create a empty file quickly.

2. Great. Now, let's create a soft link using the ln command, call b, to the file a we've just created.
$ ln -s a b                                     
$ ls -l a b
-rw-rw-r-- 1 kianmeng kianmeng 0 Oct 17 02:12 a
lrwxrwxrwx 1 kianmeng kianmeng 1 Oct 17 02:12 b -> a

I always have a hard time remember the exact order of the link command especially when creating a soft link. The best way is to
$ ln -s filename linkname

3. To change the ownership of the soft link, we will use the chown command. Type these commands at the console as shown below.
$ sudo chown root.root b
chown: cannot dereference ‘b’: Permission denied

4. Solve this using the -h option which only affect the soft link instead of the actual file.
$ sudo chown root.root -h b
$ ls -l a b
-rw-rw-r-- 1 kianmeng kianmeng 0 Oct 17 02:12 a
lrwxrwxrwx 1 root  root  1 Oct 17 02:12 b -> a

On array_slice and array_shift Functions

public function query($query) {
    $stmt = $this->pdo->prepare($query);
    $stmt->execute(array_slice(func_get_args(), 1));
    return $stmt;
}
Interesting piece of PHP code shown above. Didn't realize you can use array_slice function to extract portion of an array from func_get_args function. My typical way is just using array_shift function to remove the first element.

Instead of
array_slice(func_get_args(), 1);

you can also obtain the same result (a bit longer) by
$args = func_get_args();
array_shift($args);

However, you just can't simply write in such way show below (the interpreter will throw fatal error) which I am going to elaborate more.
array_shift(func_get_args());

Run your PHP in interactive mode and type the sample code. As shown.
$ php -a
php > print_r(array_shift(array('a', 'b', 'c')));
PHP Fatal error:  Only variables can be passed by reference in php shell code on line 1

Let's assign a temporay variable to the array. Howevery, we only obtain the first element as array_shift function is a modifier function which modify the argument and expect is to be a reference.
php > print_r(array_shift($temp = array('a', 'b', 'c')));
aphp >

The only way is to first assign your array to a variable and modify it.
php > $temp = array('a', 'b', 'c');
php > array_shift($temp);
php > print_r($temp);
Array
(
    [0] => b
    [1] => c
)

Conclusion is if you want a portion of an array, just use array_slice function.

Visualizing Wifi Signal Strength

Due to additional headcount around the house, there are currently more devices connecting to the wireless access point. Thus, affecting the Wifi connectivity, especially mine.

AskUbuntu's answer recommended that this console app called wavemon to check your Wifi adapter signal strength. Basically, this app "is an ncurses-based monitoring application for wireless network devices." Installation is plain straightforward in Ubuntu 13.04. Just type these two lines.
$ sudo apt-get install wavemon
$ sudo wavemon

Screenshot below shown the movement of the signal level of my lappy wifi connection, which was quite poor. Went to Low Yat and bought two antennas to boost the signal from 5dBi to 8dBi. Still, nothing much changed. In the end, switch to plain old cable and ethernet, specifically ethernet over power lines.


What next ? There are three other possibility to restore back my Wifi speed. First, replace and upgrade my wireless router with some other brand like Asus RTAC66U which support thousand assorted features and most importantly, Quality of Service (QoS). You cannot prevent people from watching or downloading movies 24x7, but at least you control their usage. As to be fair for everyone else. Second, buy a high gain wireless USB adapter to replace my lappy internal Wifi adapter. Third, add a few wireless repeaters around several strategic points in the house.

Let's see how this goes.

System Freeze When Using Google Chrome in Ubuntu 13.04

Is seemed I am not the only one having this issues, especially if you've opened quite a few Ajax-intensive apps or sites at the same time. Can't seemed to track down the root cause. Is it my Chrome extensions, plugins, or just video driver issue? Nevertheless, found two waysto restart the desktop.

1. To restart X by using Ctrl-Alt-Backspace, but first you must enable this key combination. Why was this disable in the first place ?  See screenshot below.

System Settings -> Keyboard -> Layout Settings -> Options -> Key sequence to kill the X Server


2. Switch to terminal by Ctrl-Alt-F1 and login again to restart Unity.
$ unity --replace

Original and Non-Original Battery

Is it just me or some Placebo weird crap ? After switching to an original Lenovo   , application in Ubuntu seemed to run faster, especially the dreadful slow Chrome browser.

Checking the battery status from the terminal using UPower tool.
$ upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep -E "state|to\ full|percentage"

    state:               charging
    time to full:        4.2 hours
    percentage:          28.1695%

As shown above, the new battery need 4.2 hours for a full charged. Rather long compare to the non-original battery which only need 1.5 hours. Why the difference? No idea what so ever.

To extend your battery life, it best not to hold full charge for a long period of time and keep the battery in 40% to 80% charged range. Unfortunately, my beloved  E420, sadly is not a real Thinkpad does not (shown below) has Tp smapi support which can regulate battery charging within the threshold range.
$ sudo apt-get install tp-smapi-dkms
$ sudo modprobe tp_smapi
ERROR: could not insert 'tp_smapi': No such device or address

How then ? The only best way to extend the battery life is remove it when not using and keep your laptop temperature cool. Or alternative, write a script to monitor your battery charging within this range and notify you when to start and stop charging.

Business Card Raytracer and POV-Ray Installation in Ubuntu 13.04

Via HN. A step-by-step decipher  of the Raytracer source code that fit a business card. A Raytracer is a program that generate an image through ray tracing technique. Hard to imagine me ever getting close to what he, Andrew Kensler managed to achieve.


The post somehow reignite my love for computer-generated imagery. That also reminds me of the classic raytracer, POV-Ray that I used to play and waited hours to generate one tiny small image. Unfortunately, due to licensing issue, the program was dropped from Ubuntu since 12.04. No worry, we still can install it using source code compilation. Installation steps for Ubuntu 13.04 as follows:

1. Download and extract the latest greatest version, I am using the 3.7 RC7 beta.
$ wget http://www.povray.org/beta/source/povray-3.7.0.RC7.tar.bz2
$ tar jxvf povray-3.7.0.RC7.tar.bz2

2. Configure the software before compilation. You should encounter quit a few warnings of missing required libraries. Note the COMPILED_BY flag is compulsory.
$ cd povray-3.7.0.RC7
$ ./configure COMPILED_BY="foobar baz "

3. Install the prerequisite packages. Note that I choose to install all the Boost-related packages but some are optional.
$ sudo apt-get install libboost1.53* zlib1g-dev libpng12-dev libjpeg-dev libtiff5-dev libopenexr-dev libsdl1.2-dev

4. Run the configure script again. You will still encounter the dreadful 'cannot link with boost thread library' (see below). Took me a while of googling to find the exact solution.
$ ./configure COMPILED_BY="foobar baz "
...
checking whether the boost thread library is usable... no
configure: error: in `/home/kmang/project/povray-3.7.0.RC7':
configure: error: cannot link with the boost thread library
See `config.log' for more details
...

5. Based on the solution proposed, append the LIBS="-lboost_system" option to the configure script to make compilation works. Compile and create the .deb package using checkinstall program (easy for uninstallation later). Note that compilation is quite long, roughly around 49 minutes.
$ ./configure COMPILED_BY="foobar baz " LIBS="-lboost_system"
$ time make
...
real    49m43.344s
user    47m11.508s
sys     2m15.908s

$ sudo make install && sudo checkinstall

6. To test the application, let's render Utah teapot, the famous standard reference object in the computer graphics community. See below for the sample rendered output.
$ cp -rv /usr/local/share/povray-3.7/scenes/advanced/teapot/ /tmp
$ cd /tmp/teapot
$ povray -w320 -h240 teapot.pov

Create a .deb Package from Source Code

Due to the Subversion PPA still stuck at version 1.7.9. In order to use Subversion client version 1.8.3, I need to upgrade by source code compilation. As I mentioned before, I really don't like this installation method. Fortunately, I've found this tool called checkinstall, which let you create a software packages (deb or rpm compatible) so you can remove it later.

We will illustrate by compile and install the latest version of SQLite, a lightweight database management system.

1. First, download the latest SQLite source code. We're using the autoconf version. Later, extract the tarball.
$ wget https://www.sqlite.org/2013/sqlite-autoconf-3080002.tar.gz
$ tar zxvf sqlite-autoconf-3080002.tar.gz

2. After that, we need to install all the necessary software or libraries in order to compile it. apt-get has a wonderful option call build-dep which will install all these dependencies so you can build the software.
$ sudo apt-get build-dep sqlite3

3. Go into the source code folder and generate the Makefile.
$ cd sqlite-autoconf-3080002
$ ./configure

4. Before we compile the source code, let's install the checkinstall package.
$ sudo apt-get install checkinstall

5. Compile the source code and create a .deb package. Make sure you pass -j option [5] to   to speed up the compilation time. Rules of thumb is twice the number of your CPU cores. For my case, my lappy has 4 CPU cores using the nproc command. Hence, we should use -j8 option.
$ make -j8 && sudo checkinstall

6. Please take note that checkinstall will create a package and install it immediately. Buy you can remove it.
$ sudo dpkg -r sqlite-autoconf

7. Check the content the the deb package file. It will show you a list of files to be installed.
$ dpkg --contents sqlite-autoconf_3080002-1_amd64.deb

150 Minutes Per Week

"The study found that 150 minutes of vigorous physical activity per week added two to three years to the lives of the men during the 13-year study."
-- The University of Western Australia, emphasis added
Found via Reddit. 150 minutes per week is roughly around 21.43 minutes per day. Before that, what is vigorous physical activity? According to World Health Organization (WHO), any high intensity activity that increases heart rate is considered vigorously. Examples are running, brisk walking, fast cycling, aerobics, and others.

It seems daily walking of 10,000 steps (which I still fail to do so) merely enough for fitness or weight loss but not enough to extend your life expectancy. Is time to include the Scientific 7-Minutes Workout in my daily as I don't suffered any foot pains anymore.

GNU/Linux Performance Analysis Tools

Where one slide (#16) says a thousand words. An overview of all the tools available in GNU/Linux for performance analysis by Brendan Gregg of Joyent, cloud infrastructure company.


Out of all the mentioned tools in the diagram, never try or heard of these four. Installation are done in Ubuntu 13.04.

1. perf, GNU/Linux profiling with performance counters.
$ sudo apt-get install linux-tools-3.8.0-30
$ sudo perf top

2. blktrace, kernel layer block I/O tracing.
$ sudo apt-get install blktrace
$ sudo blktrace -d /dev/sda -o - | blkparse -i -

3. slabtop, display kernel slab (amount of cache) information.
$ sudo apt-get install procps
$ sudo slabtop -o -s c | less

4. nicstat, network monitoring tool.
$ wget http://jaist.dl.sourceforge.net/project/nicstat/nicstat-1.92.tar.gz
$ tar zxvf nicstat-1.92.tar.gz
$ cd nicstat-src-1.92
$ mv Makefile.Linux Makefile
$ sudo apt-get install gcc

Edit the Makefile and change below line from 32 to 64
CFLAGS =        $(COPT) -m64

$ make
$ ./nicstat.sh 1

An Integer is Not an Integer

Another day, another unexpected behaviour encountered in  wonderland. Funny that a number returned from a function that looks like an integer is actually not an integer. Let's illustrate this with a simple example.

1. Start the interactive mode.
$ php -a

2. Let's find the square root of number 9, using sqrt function.
php > echo sqrt(9), "\n";
3

3. Obviously 3 is an integer right? Just to confirm, let's use is_int function to check it. Nope, is not.
php > echo is_int(sqrt(9)), "\n";

4. Checking the sqrt function documentation again. It seemed that sqrt will return float data type even though the decimal point is not shown. Let's try with is_float or gettype function.
php > echo is_float(sqrt(9)), "\n";
1
php > echo gettype(sqrt(9)), "\n";
double

Double ? Isn't it supposed to return float ? According to documentation [4], double was used instead of float due to historical reason. Why ? No effing idea what so ever.

5. Still, how we going to check for integer, is this case, to find out which number is the perfect square (an integer is a square of another integer) ? Type casting. See example below.
php > $root = sqrt(9); echo $root == (int)$root, "\n";
1

Another day, another gotcha in PHP world.

Simulate fail2ban Using Iptables (for SSH only)

Fellow HN reader, spindritf shared a tip to simulate something similar to fail2ban, a tool to ban certain IP address with malicious intent. Useful when you don't want to install fail2ban. My main issue with fail2ban is I sometimes accidentally ban myself after several login failure.

-A INPUT -p tcp -m tcp --dport 22 -m recent --update --seconds 180 --hitcount 4 
--rttl --name SSH --rsource -j LOG --log-prefix "ssh brute force: "

-A INPUT -p tcp -m tcp --dport 22 -m recent --update --seconds 180 --hitcount 4 
--rttl --name SSH --rsource -j DROP

-A INPUT -p tcp -m tcp --dport 22 -m state --state NEW -m recent --set --name SSH --rsource -j ACCEPT

Till today, I still can't read and use the Iptables properly, even with the explainshell tool, and still try my best to avoid it. Maybe one day, I still really force myself to really learn it.

Oh crap ! I shouldn't have done that?!

Don't multitask. Seriously, don't multitask while handling important stuff. As usual, I was busy coding and monitoring the Apache web server log at the same time. Due to my wonky laptop battery, I've decided to switch to another backup battery and rebooted the machine. Exit from my remote connection and type this command at my console to reboot my lappy.
$ sudo reboot

Weird. Nothing happens. No programs was closed at my desktop environment. Nothing was shutdown. Checked again at my terminal. To my horror, I just realized that I didn't log out properly from the live production server and I had rebooted the live production server instead !

Sh*t! Holy double sh*t!

Rushed out to tell my boss about it. He laughed about it in a cool as cucumber way. Not surprised. He and those long serving employees had experienced far worse scenarios before. (They have enough war stories for generations) Not for me, this is so effing embarrassing stupid. Server rebooted, double checked everything again. Thank goodness, everything seemed okay and back to normal.

Post mortem analysis. Can we prevent accidental reboot in operational critical server ? Yes, you can. Just use Molly-guard.

In a non-IT term, Molly-guard is actually a cover (normall in red) of a button to prevent accidentally triggering of unwanted event like firing nuclear missiles. As a software, Molly-guard is a shell-script that check for existing SSH session and if any of these shutdown, reboot, halt, or poweroff commands were invoked. The script will prompt you to key in the hostname to confirm before proceeding with the intended critical action.

How do set this up and get it to work? In Ubuntu/Debian-based distros, is effing easy. Just apt-get it.

1. Install the package
$ sudo apt-get install molly-guard

2. Run a simulation. Note default configuration only works over a SSH session.
$ ssh localhost
$ sudo reboot
W: molly-guard: SSH session detected!
Please type in hostname of the machine to reboot:
Good thing I asked; I won't reboot servername ...
W: aborting reboot due to 30-query-hostname exiting with code 1.

3. What if you also want this program to work on non-SSH session ? Just edit the config file (/etc/molly-guard/rc) and set ALWAYS_QUERY_HOSTNAME to true.
# ALWAYS_QUERY_HOSTNAME
# when set, causes the 30-query-hostname script to always ask for the
# hostname, even if no SSH session was detected.
ALWAYS_QUERY_HOSTNAME=true

How about Centos/Redhat-based distros? Not in the official repositories. (Now you know why I dislikes rpm-based distros, limited softwares selection). You can download packages from these sites. Installation and setup should be the same.

Fun and exciting times these days. I blamed it all on the bloody wonky battery.

What is setsid ?

From my last post, I encountered this foreign new console command setsid. What the heck is setsid ? Manual page said this program let you "run a program in a new session". Why we need it? Because you want any program (e.g. daemon) that started from a terminal emulator (e.g. xterm), to stay running even after you close the terminal emulator.

Let's illustrate this using two simple examples.

1. Start xterm and later gedit editor.
$ xterm
$ gedit

2. Open up another terminal session and see the process tree. Notice that the xterm is the parent process of gedit. If we kill the parent process (xterm), all subsequent child processes will be terminated as well.
$ pstree | grep xterm
     |-xterm---bash---gedit---3*[{gedit}]

3. Close the xterm program. You will notice the gedit editor program will be shutdown as well.

Let's repeat step 1 - 3 but using setsid instead.

1. Again, start your xterm and later gedit editor using setsid. You will notice after the second command, you can proceed with other command as well.
$ xterm
$ setsid gedit

2. Let's find the process tree again. Notice gedit is not attached to the xterm parent process but instead a new process or a new session.
$ pstree | grep xterm
     |-xterm---bash

$ pstree | grep gedit
     |-gedit---4*[{gedit}]

3. Close the xterm program. You'll notice gedit will still running.

Note that is not the same as forking a process using ampersand (&), running command below does not create a new session but a subshell child process
$ xterm
$ gedit &
$ pstree | grep xterm
     |-xterm---bash---gedit---4*[{gedit}]

Today I realized that after using GNU/Linux for so long, there are still a lot to be learned and explored. But yet so little time.

Restoration of Missing Unity Launcher and Panels

Supposed to rush home for some errands after work but accidentally remove certain common library package in my Ubuntu desktop. In the end, the Unity launcher, panels, and status indicator were removed. Frustrated (this is the nth times), gave up, and went straight home. After replenished my glucose, googled around and tried again.

Steps to recover it in  Ubuntu 13.04.

1. Re-install the Ubuntu desktop.
$ sudo apt-get update
$ sudo apt-get install --reinstall ubuntu-desktop
$ sudo apt-get install unity

2. Logout from the command line, since the top panel was gone and no where I can find the logout menu item.
$ gnome-session-quit

3. Login again. But still, not Unity launcher or top panel to be seen. Reset the Compiz settings and whoala!
$ sudo dconf reset -f /org/compiz/
$ setsid unity

Endless PHP Internal Drama

Via HN. Sigh. Endless drama in the PHP  internals. I applaud their efforts (both Anthony and Nikita) to bring more useful and typical programming languages features like generators, function autoloading, and password hashing. to PHP. However, the language itself is slowly morph from a simple procedural web template language into a poor imitation of Java with none of its benefits. The hacked solution of namespace separator. More inconsistency and complexity. Yes, some may argue is a Bikeshed [8] issue and you can choose not to use it. But seriously, backslah (\) ?

The language itself feels like a ship sailing aimlessly in the sea and go where ever the sea wind direct it. Both Rasmus together with Zend should step in and be the Benevolent Dictator for Life (BDFL) instead of letting the community votes decides. Sometimes, unfortunately, decisions are made by those who made the most noise.

Imperative and Dclarative Programming

Imperative. Think PHP programming language. You give command and tell the computer how to do things step-by-step. Is like a driving instructor teaching a person how to drive.

Declarative. Think SQL. You tell the database what you kind of result you want and don't care how the system do it. Is like asking a taxi driver to drive you to your destination.

Variadic Function

Few years ago, I was introduced to this PHP function func_get_args() by my senior while reading his code (can't remember what or why he used it for). This function allows you to create a function that can take multiple arguments and no argument list declaration in your function signature. Code shown below is an example of a helper function to find the maximum value from a set of number.
function max() {
   $max = -PHP_INT_MAX;
   foreach(func_get_args() as $arg) {
      if ($arg > $max) {
          $max = $arg;
      }
   }
   return $max;
}

echo max(1,5,7,3);
7

Why I brought this up ? I didn't realize that the term "variadic function" is used to describe function that support multiple arguments until I read the Request For Comment (RFC) on the proposal of a new syntax for variadic function for PHP. Historically, variadic function is an old concept that long implemented in C programming language, especially for printf() and scanf() function. Not surprisingly, these two functions also existed in PHP , since it's a C-based programming language.

Back to the RPC. Reading through the discussion in Reddit and the RFC itself. I think is a good idea since we can now enforce type hints and enforcing consistency on interface. However, a feature that is nice to have but only useful for those framework or library writer and not mere library consumer like us.

Revisit Subversion Branching and Merging Again

Was reading this presentation on version control in #Subversion . Relearning the whole branching and merging flow again. Due to some constraints (access right, data sensitivity, and my pure laziness as well), our flow is a bit effed up. No one but myself to blame since I am responsible for syncing all the works by different developers.

According to the slide, the flow is as follows:

1. Create a branch from trunk and commit.
$ svn cp ^/trunk ^/branches/mybranch
$ svn co ^/branches/mybranch

2. Inside your own branch, mybranch in this case, you need to keep in sync with the trunk.
$ svn merge ^/trunk
$ svn co

3. Later, once the features in mybranch is completed, you will need to reintegrate to the trunk. Inside a clean copy of trunk, run these commands.
$ svn merge --reintegrate ^/branch/mybranch
$ svn co

Once integrated, the branch is basically end-of-life. No more modification to it. This is one step which I did differently, basically we have a stable branch which actually act like trunk. Why ? I spend most of my time in stable branch and hardly touch trunk. That why.

However, the --reintegrate option has deprecated in version 1.8. Subversion will automatically decide a reintegration merge or not.

4. One integration is done you'll need to tag it.
$ svn cp ^/trunk@12345^/tags/mytag
$ svn co

5. Rinse and repeat.

There is still one question lingering in my head right now. How do I prevent certain files from being modified during merging ? More on this in next post perhaps.

Back to the slides. One particular slide echo my sentiment about the practice of using Subversion or any version control. You need to commit small, commit early, and commit often for each small task. It keeps the momentum going and motivate the team to move forward. This was further enhanced by our practice of Kanban scheduling methodology and Podomoro time management technique. Our development process is getting better but there still room for improvement.

One thing for sure, I need to move the Subversion to a new server. The installation (by yours truly) is seriously way effed up. Should I just migrate to Mercurial or Git? Or maybe I should just use hgsvn or git-svn instead?

MUMPS

Via HN. If my memory serves me correctly, few years back, someone (a sales dude) used to come to #myoss  meetup and talked about Multi-User Multi-Programming System (MUMPS), a programming language with embedded data storage. A very old (since 1966) programming language within a niche domain, mostly in healthcare. Suspect some of the healthcare system in .my are still using it.

I am wondering, what are the other exotic programming languages still being used in here ? For banking industry, I think Cobol and RPG are still quite common. What else?
"I really wanted to learn AngularJS since the day it was introduced, but I never had the time. I always envied other developers using it and I just kept bookmarking new AngularJS resources and articles. But then I thought maybe I should define a weekend project and do it with AngularJS, so I can learn it."
-- Sallar Kaboli, emphasis added.
HN reader, zerr also wrote something similar about the lack of time in keeping with your learning and pursuing your own weekend projects. Is going to be harder if you are getting older, have family with kids, or all sort of stupid, annoying, out of your control distraction over the  weekend.

The only time I can do something useful at home is after midnight where everything has quiet down. Is where you find solitude to read, to learn, and to think. Thus, helping you to spark your creativity and self-development.

Unfortunately, being a night owl is slowly taking a toll of my body especially you don't have sufficient sleep the next day. Lack of quality rest going to wreck your body somehow, slowly but surely. The symptoms are all there.

I didn't realize how stupid not to have a good rest until yesterday morning. Tried to upgrade the Subversion server at 4am and sent someone to KLIA at 5am. At the same time, tried my very best not to accidentally hit any of those "Mat Rempit" doing superman stunt along the Maju Expressway. As a biker, if you can, avoid Maju Expresway. I have saw three damaged bikes long the journey. Same goes to MRR2. These two driveways are way too dangerous for biker.

Dizziness

"The inflammation of the lining of the stomach is called gastritis. Dizziness and fatigue after eating meals are common symptoms of gastritis. This condition may be caused by irregularity in eating meals, consuming improperly cooked food, excessive eating of oily foods, overeating, alcohol intake, and drinking strong coffee or tea."
-- MD-Health, emphasis added
Be wary of any health-related information found online. The site itself has no disclaimer, no source of information, and furthermore, not HONCode certified. The best next course of action is to check with a doctor.

There are two symptoms of dizziness. One is light-headedness where you feels like fainting. Second is vertigo (which I always thought not a word but a unique name of the imprint of DC Comics, silly me), where you feels the spinning sensation. You can sense the sensation from three sources, objective (world is moving), subjective (the person him/herself is moving), and pseudovertigo (rotation inside your head).