Monthly Archives: October 2014

You are here: Home . Archive

Adding screen options to a WordPress plugin

In WordPress, adding screen options during plugin development is not one of those things with a lot of documentation. There’s a great tutorial on this by Chris Marslender. There’s one here too by someone I’m a fan of, Pippin Williamson. Both went a long way to get me started. I differ from these approaches in 2 things:

  1. I use OO
  2. I use a less expensive approach in retrieving the screen option

Now, on to the good stuff….

First, pick the hook that’s returned when your options page is created:

$my_plugin_hook = add_menu_page( $page_title, $menu_title, $capability, $slug, $function );

Add an action based on that hook:

add_action( "load-$my_plugin_hook", array ( $this, 'add_option' ) );

My assumption here is that add_screen_option is in the same class that the action above is defined.

Then, onto our add_screen_option function:

class My_Plugin_Class {
     private $tickets_per_page_options_key = "myplugin_tickets_per_page";
     private $default_tickets_per_page     = 20;

     public function __construct() {
        $this->add_menu_pages();
       add_filter('set-screen-option', array ( $this, 'set_screen_option' ), 10, 3);
     }
     public add_menu_pages(){
     //Add your page(s), use the hook(s) returned to add screen options as explained above
    }

//The other cool stuff your plugin does 

public function add_option() {

$option = 'per_page';

$args = array(
    'label' => __('Tickets', 'my-plugin'),//The second parameter is your text domain. It is used in 'Internalization', the fancy word to mean 'Translate your plugin into other languages'
    'default' => $this->default_tickets_per_page,
    'option' => $this->tickets_per_page_options_key
);

add_screen_option( $option, $args );

}
//Now we set the screen option. This is called by the filter we defined in our constructor
public function set_screen_option($status, $option, $value) {

    if ( $this->tickets_per_page_options_key == $option ) return $value;

    return $status;

}
}

Now, on to that less expensive approach for retrieving your saved screen option that I spoke of earlier. The other tutorials require that you first get_current_screen() and use it in your retrieval. I believe all you need is this:

$per_page = get_user_meta(get_current_user_id(), $this->tickets_per_page_options_key, true);
//To have a fall-back in case the option isn't defined, all you need is this:
if ( empty ( $per_page) || $per_page < 1 ) {

    $per_page = $this->$default_tickets_per_page;

}
//NB: All this is in your class My_Plugin_Class

From my tests, screen options are stored in the WP usermeta table; all you need to retrieve them is the key and the user’s ID. Then, to fallback to a default value, use your default variable; there’s no need to go back to the Db for that

On making an honest shilling

Some men were arrested last week for making money. It would not have been a crime if they’d chosen to go about it the way you and I do – waking up every morning and beating the odds to get to work, with the odds getting creative everyday-one day it’s rain, the other it’s an ailing car, then it’s an ailing body, or fatigue, or it’s that voice in your head pleading for you to sleep “5 more minutes”. We all know that “5 minutes” in morning sleep lingua means 45 minutes that’ll be followed by you running around in a state of panic. We beat all those odds and go out to exchange hours of hard work for Shillings.

money_bagSometimes the work is rewarding. ‘Sometimes’ because the rest of the time, you and I are earning our bread through sacrifice. And sweat. And frustration. From those selling tomatoes, to those riding a boda boda, to the guys shouting dusk till dawn for people to enter their taxi, to the man carrying the heaviest of loads on his back in the taxi park, to the lady sitting all day in a shop waiting for yet another undecided customer, to those racking their brain for a solution to a challenge with an impending deadline, we are all in this. Very few of us do it because, “Oh, it’s my passion. I was born to do this!” For most of us, we must. And it’s the right thing to do. There are mouths to feed, fees to pay, dreams to be facilitated, backs to clothe and while I still have breath in these lungs and the gift of the ability to do some work, I’m going to try and do something about it. You see it in the guy selling handkerchiefs and sweets in the taxi park. You see it in the mother, baby on her back, selling bananas. You see it in the fuel pump attendant. “This isn’t fun but I’m here. It isn’t where I want to be but I’m here. I showed up”

Then you hear of young men arrested for making money. These guys, sure that the rest of us are dumb, set up a machine to print counterfeit money. One Billion dollars’ worth of it. They looked at that guy who sells umbrellas in the rain and thought to themselves, “You fool. All you need to do to make money is hit print”. One Billion dollars. At the rate they were going, they’d probably soon ask Honorable Maria Kiwanuka for the nation’s budget so they can finance it.

Shout out to you going about making an honest Shilling- It isn’t easy but it’s the right thing to do and that counts for something. If not to you, then it will for the people that depend on you.

Interview with cloud architect Bas Moussa

Bas Moussa is the Chief Architect at Nuvole Computing LLC, a cloud consulting firm in San Francisco. He designed the firm’s reference architecture that implements cloud architecture in a way that fulfills the promises of cloud computing with maximum portability of components. He has been programming since he was 8 and has worked in Internet software development and operations since 1996. He was in Uganda this year to chill; I had a chat with him and sneaked in some serious questions on what he does.

You’ve heard the saying that the early bird catches the worm. Do you agree?

*hesitates* <Loading screen shows>

Yeah

Wouldn’t the worm have to be early to be caught?

The assumption is that the worms are early; earlier than any of us and the first one there gets it. I would say it is important to figure out if the worm is worth catching. Some people want to sleep-in and it’s more important that they sleep-in than catch the worm. Other people REALLY want the worm so they go get it.

And if I don’t like worms, then why would I get up early?

Bas explaining something about the early worm…

‘Cloud’ is a buzz word these days. “I had my coffee in the cloud this morning”, “The cloud should make it rain”, “My house is in the cloud,” what does the word mean in your context?

Most generally, it means the black-boxing of things that used to be very messy. There are a number of ways of talking about it but the example I try and give a lot of lay men (stares pointedly at interviewer) is that of a Word Processor. That’s a product you buy, you put it on your computer and it doesn’t go away. As long as your computer works, it works. If your computer breaks down, you are in trouble. You have to go get another computer, download the software again and then set it up.

If you make that cloudy, you remove the software from the computer so you no longer have to download it. You just access it on some set of servers in the ‘cloud’ and it takes care of everything for you. So when you are offering a service, it can be very machine-oriented, very non-cloudy but if you offer your software as a service, then that is the cloud, in one sphere of things.

Ok. Is that the one you deal with?

My business [Ed: Nuvole Computing] caters for anybody who wants to design software that operates like that; software that you don’t download but that you provide as a service. In the old model, the resources required to run 100 copies of a Word Processor are 100 different machines. When you are doing it as a service, all of those machines are now on you, the service provider’s, machines. That presents particular difficulties. You have to stay up all the time. People can’t have a Word Processor going down. So yeah, we specialize in design of software as a service.

In the old model, the resources required to run 100 copies of a Word Processor are 100 different machines. When you are doing it (in the cloud) as a service, all of those machines are now on you, the service provider’s, machines.

What’s the biggest challenge you run into doing this?

Far and away the most challenging thing I run into, not just once but repeatedly, is getting the client to believe in the model. There are two types of clients; one kind comes to me and says, “We have an idea. We have a program, it’s mobilized and we want to do this but we want to do it right”. So I sit down, design it with them, show them how to do it, they have a go at it and we make the thing right from the start. That’s always a wonderful, rewarding experience.

But very often, people with enterprise products, software that they designed for download, the kind that follows the old model, say, “I want to make this a service”. So, they have a product that’s already making a lot of money, they are looking toward the future and they want to change but we don’t have the luxury of imposing architectural constraints on them. So there’s a big, not a mean fight, but a struggle. On one side they want to maintain what works and makes money and on the other side, we want to take advantage of everything that this cloud offers. You need to virtualize everything. You have to change the way you do things. Before it makes money though, it is a very difficult argument to make. So  we run into that and what ends up happening is we meet somewhere in-between. We make certain aspects of it work in the cloud and others we maintain as before. It’s difficult but it’s a great first step. Once they see it working, their eyes light up.

Given that challenge, do you ever have to carry boxing gloves to meetings?

Never. These are clients; they always win. There’s no fighting with clients. <Interviewer expresses his disappointment>

Have there been any heavy technical challenges?

There is dealing with those elements that cannot be made stateless. Certain clients have come with the old model relational databases, like MySQL and they want to make that internationally replicated. I simply say no to that. I don’t know how to do that and I would question those who say they can do it. It doesn’t work very well, that much I know.  So that’s one of those architectural changes.

Certain clients have come with the old model relational databases, like MySQL and they want to make that internationally replicated. I simply say no to that.

If you want to do this, you are going to have to change the back-end database which is a HUGE deal. That affects everything. What I’ve found is that a lot of people in that circumstance are abusing MySQL. They don’t need all of that power. They just need a subset that does a very specific thing and there are many tools out there: from the NoSQL databases to a simple key-value store, you can even leverage caches that way. Yeah, but technically speaking that’s a huge challenge and one that I cannot meet

If there is a startup out there planning to do stuff right, at a global level, from the get-go, what do you have to say to them?

Most generally, I would say whenever possible, use Open Source software because the quality can be very high. If it doesn’t meet your requirements, then certainly go find and pay for what you need but very often, there’s no need. The quality of software out there is tremendous so start there.

Most generally, I would say whenever possible, use Open Source software because the quality can be very high.

Number two, try not to rely on special hardware. Or very fast connections. Design your product so that it can work in any environment, even the cheapest, slowest environment. That way you can scale endlessly and you can work in any context.

What do you have to say to someone with his or her hopes set on going to Silicon Valley someday?

Silicon Valley is very much, a little less so these days, but more so than most places in the US and probably the world, a meritocracy.  If you come and you bring something to the table that nobody else has brought, somebody will listen to you. You can usually find a way in. The organizations are usually flat.

Again, there’s always who you know and so on and so forth but you can make great headway. I would say from all the way over here, it is so far away, use the online forums. Make a presence for yourself online so that anyone who wants to can see exactly what you are up-to and what your context is. One great thing, if you are going for technical stuff, there are some websites out there like stackexchange. Everybody uses it and if you get on there and make a presence for yourself and you get listed as a guru, it doesn’t matter where you are from. That’s like “Oh, that guy knows a lot and his peers approve.” If I were looking at that, that would be tremendously valuable.

And of course make connections. Reach out wherever appropriate, make those connections and run things by people. They are generally pretty nice.

What’s been your impression of the developer here?

I’ve essentially only had one day of interaction with Developers here. The projects seem heavily SMS-oriented whereas in the States we don’t have any of that. We have SMS but we barely use it. We use it just for “Hi, I’m downstairs”, that sorta thing. We were late, even Europe was years ahead of us-we started using it late. In the US, the web has taken hold as the main interface for the client-server architecture of the web at large so I think that transition introduces a bit more complexity but from what I saw, it’s the same stuff.

Bas giving a talk at The OutBox Hub, a co-working space and platform for developers in Uganda. All photos by The Outbox team

One thing I’d hope and wish for tech workers here and that I’d love to help in any way possible is for them to skip a lot of the mistakes that we made and just jump straight into the other stuff. For example using Mongo instead of MySQL would free you tremendously in the future when you have to grow and it would build the expertise that a lot of people now in the US are scrambling to learn. It is still a rare skill but there’s no reason it needs to be.

…skip a lot of the mistakes that we made and just jump straight into the other stuff. For example using Mongo instead of MySQL would free you tremendously in the future when you have to grow…

I did get the feel that the motivation level was tremendous; that was really great. Geeks unite all over the world!

What’s the most common challenge you find that people run into?

A few things. Performance-wise, if people grow quickly, that’s always difficult. When that happens, almost always, and this is going back 20 years, the relational database, just the database in general, is the choke point. Not only that, very often their database is overloaded and they don’t know what to do. Sharding is the best answer or just build a bigger DB box which is what most people do and it ends up costing a lot of money.

At first, you can have everything running on one machine and it is fine but if things go down then you move to a virtualized setup. Then if things go down more then you have to start using HA; more boxes for each layer and if you do not write your stuff correctly or at least leave room to switch quickly you can be locked into some very painful stuff. So, one example is each layer, for example the front-end, display layer or the API layer, you want those layers to be stateless. This is very important and it is something that if you need you’d have to go back to the beginning to change

What’s the future of cloud computing? Will we carry the cloud in our minds? Will our brains be computers and to establish a TCP connection with someone else you rub noses?

*laughs*

I would love it if we’d rub our noses to establish a TCP connection- that would be great. Short of that, I do see the future as entirely virtualized. Dealing with hardware and machines and all of that is still done at some level but as developers and business people and people trying to put out products, we should not be thinking about that at all. I think in future, everything is going to be entirely service-oriented. Everything is going to be an API. Everything can talk to everything and your entire infrastructure should be code. To the extent it’s not, it should be a simple trade that somebody without a lot of training can do. Red light goes bad on a machine, replace it. Behind the scenes, the virtualization people write everything in such a way that it can shift a virtual machine from one machine to another just like we write our applications.

I do see the future as entirely virtualized.

Take the abstractions that have been happening over the course of computer history; we started out writing very basic languages –C and managing memory and all that stuff and now we are at the point where we aren’t doing that. There are virtual machines and there are scripting languages and these are very high level things and they are just getting higher. Now we are at the point where your entire infrastructure can be code- including the machines. It is one of those things where every layer of abstraction imposes constraints and the only question is are those constraints worth the effort? There are always people who cling and say, “No it’s not worth it. We need to do things this way” but it is almost always not the case so always look at the next layer of abstraction to make things easier and easier and hopefully computers work better and better because right now, you almost need to work in the industry to make a computer function and that shouldn’t be the case.

A movement in the right direction

The grapevine, after quite a number of pleasantries, lengthy small talk and a lot of prodding, mentioned that there are rival camps in the ruling party, the National Resistance Movement (NRM). “I tell you Kakoma, there are shakes in the Movement,” as though thinking it could sneak that pun past me. Reacting to my unsure smile, it went on, “That Movement is on a mazina maganda thing, at that part where the guys on the ngalabi are fully worked up. One camp is for our beloved leader and the other for, you know, (voice lowers to a whisper) the ex-Premier. “

I wasn’t entirely sure I could believe the grapevine; you know how they be – getting inebriated on their own grapes and then becoming too creative. However, later, the State Minister for Investment and Arua Municipality MP, Dr Gabriel Aridru Ajedra emphatically put an end to the rumor by confirming it. He also pointed out which side he’s on – he’s fully behind our beloved leader’s faction. He reasoned that you cannot bite the hand that feeds you. In all fairness though, if you have teeth and the ability to draw the hand sufficiently close to them, you can bite the hand that feeds you. Whether you should is another thing altogether.

The news of a divided ruling party is very disturbing. It’s the kind of terrible news that makes you want to be like those people on TV who break out in fits of rage and hurl cups, plates and everything in sight at the wall. Being third world, we cannot afford such expensive acts of fury. Here, when angry, you have to first examine the cup before hurling it at the wall. How do we bring some semblance of harmony back into the mighty party? To answer this, we can look through history and look at the ways differences have been settled.

There’s the option of us as a nation cramming into an amphitheater and shouting ourselves hoarse as the two individuals battle it out with only wild courage, swords and shields. The loser would then be fed to the lions. I’m not sure the lions would like this option so moving on…

Arm wrestle maybe? Broadcast live and with international judges and eloquent commentators, some with foreign accents and others using the various languages of the land.

It would be amazing though if our leaders would demonstrate the strength of character and humility we all need to initiate reconciliation when faced with diverging views.

On doing the write thing

There’s a Social Media Summit taking place in Kampala next month; the people behind it asked me to write something on why I blog. Also, there’s been an ongoing challenge this week, the UG bloggers challenge, to write something every day for 7 days. This is me hitting two roaches with one stone. Why I write….

I fell in love with words when I was in diapers-my mum testifies to how my first word was ambiguous. Mama and papa came later. My growth in expression hit a stalemate when I discovered “feed me”. That’s all I said for a while. That’s till one day, there I was, crying my voice hoarse because a piece of cassava I was eating had fallen and the 3-seconds to pick it up had elapsed. In my misery, I crawled upon a pencil and a paper.

Ok, for real, I enjoyed reading quite early. Peter and Jane, Mills and Boon {in Primary school, only one book, truth}, Hardy Boys, Animorphs.

animorphs

The animorphs were these kids who could turn into animals and run around saving the world. Loved the stories Photo by Tim Trueman

To try and craft my own stories, I took to writing just as early. I did it through school and in S.6 vacation, in response to something I’d read, I tried to write something every day. At the time, I shared the stories with a buddy of mine. He offered as much criticism as one can give to a former rugby player. You know how rugby players, what with visible veins on their foreheads, aren’t an easy bunch to criticize.

Buoyed by that (positive) feedback and this attractive lady who was doing it, I started blogging. The things we do for beautiful ladies. (Can I get an “I know bro, I know!”?)

That was 8 years ago. Back then, we met every month for a Bloggers Happy Hour (BHH). We were an alive, engaged, fun community. Some of my closest buddies today are from those gifted people because you know, if I stick around them long enough, it’ll rub off. S.t.i.l.l….w.a.i.t.i.n.g…..

With 4 of these buddies, we started a humor and satire website, urbanlegendkampala.com. It’s a fun place. Through it, I was approached by The Sunday Monitor which, 3 years on, I still write for.

I feel my voice has grown steadier over the years. More discipline has also kicked in along the way. Today, I blog mainly for two reasons.

  1. As a writer, I have things to say about the things going on around us. Corruption, service delivery, governance, dust, potholes, attitudes, silver linings, hope.
  2. I’m a developer. Writing code does present challenges every day; many times, overcoming some of these issues isn’t well documented. I share what I believe are well-documented solutions, hopefully to help someone get over similar hurdles faster. I also share a few things on programming in general-where to start, how to grow, etc as I learn some of this stuff myself

Why you must watch Big Brother Hotshots

The Big Brother Africa (BBA) house went up in flames last month because at that instant, millions of minds around the continent were thinking “BBA is hot! Sooo hot!” The official statement released said some nonsense about there being “investigations to get to the bottom of the matter” but we all know that our collective excitement at the impending launch did it. Mind over matter is real. If you are among the tiny group of people who didn’t contribute to the fire, you probably don’t think much of the reality show. Let me let you in on what we were thinking while you were standing at the water dispenser willing the report at your desk to write itself. BBA is hot because:

It encourages open dialogue between well-fed, well-able youth from across the continent. The dialogue is so open, at certain points you need to let go of certain inhibitions like some of your garments. You know how clothes make it hard to express yourself articulately. See, the percentage of youth in Africa is so big, the debates started in the house instantly affect economies as the contestants’ peers respond to the deep stuff being said. We are a few seasons away from seeing our economies make a ninja leap forward….any season now, things are going to change. Think of it like a United Nations conference…but of young, excited people.

It showcases the athleticism, eloquence and stamina of youth across the continent. You go dizzy wondering, “How do you drink so much and only throw up thrice? Do you have a blog somewhere so you can share your tips?” “Your Kung Fu is strong my brother! Oh wait, you were dancing. Ahh. Proceed”

With unemployment rates being what they are, the show is a breath of fresh air. Like a true big brother looking out for his own, full-time employment is provided for several people. Left to their own devices, who knows, they might be out there writing sarcastic articles about TV shows-but they are employed and that load is taken off society’s shoulders. In the future, as the show grows, we can look forward to, with joy that’s hard to hide, the day when we’d have a Big Brother nation, not a house. An entire nation being broadcast live for our entertainment. At that point, there’d probably be many shower hours because, you know, an entire nation can’t quite use one shower.

All hail BBA; it gives food to these people. And alcohol. You’d argue that they have alcohol back home but I’d counter and point out that they drink like they don’t.

It encourages tourism. When one sees what, for example, a Ghanaian looks, talks, showers and has sex like, they are encouraged to immediately visit that country.

Can’t you also see how these people are setting the bar high? All our starry-eyed toddlers watching are forming opinions on how to carry themselves around.

Here’s today’s pig story

One of the challenges of writing a weekly column on serious social issues is that many times, the “social” has moved on by the time the loud gong that signals that newspapers should be printed is sounded. When Sunday shows up, all chirpy and smartly-dressed, she finds that the hottest news isn’t so hot anymore. Talking about certain stories is like trying to re-heat an omelet-it just isn’t the same.

That said, when you hear of colored pigs being dropped off in the middle of the city, in the middle of the day, there are so many ways to skin that story. You might even want to poke fun at it, as serious an issue as it is. Reactions to the story varied from being infuriated at how poorly the animals were being treated, to how, by unlawfully assembling in the city center without express permission from our 100-year-old police, the pigs were violating the Public Order Management Act, to wondering what kind of well-meaning citizen would let potential stew roam around unsupervised, to placing bets on how the people behind the protest got some of the pigs to wear hats-some swore that they were tricked into believing that they were being taken for a photoshoot. The protest though does make you hungry…for answers.

whats_the_pig_deal

Like what happened to the pigs after the arrests? Are they still being held as evidence to be presented in court? What’s to stop a renegade policeman from going gung-ho and barbecuing the evidence? If said renegade policeman does carry off the evidence, would the paint need to be washed off first? In their colored glory, are they still stew-friendly? Maybe this one should be addressed to the chefs who read this column; what’s the best way to stew a painted pig? Is bacon de couleur a real thing?

But does the color of the pig matter? Yellow, red or blue, if it’s snorting, playing in the mud, slinging mud and eating everything in sight, does it rank lower in the genuine pig index?

Very importantly though, has the pig problem squealed enough to get the powers that be to squarely address the big unemployment issue?

Kidnapped computer’s location revealed

In the work I do away from this column, I work very closely with computers. I’m that bespectacled guy with heavy eyebrows who sits so close to the PC, you’d think it’s whispering something to him. Through this close relationship, I’ve learnt a thing or two about this electronic beast. We get along quite well, when I’m not being passive aggressive at it for taking too long to open a document. I usually ask it, “If you aren’t faithful doing something as simple as quickly opening a Word document, how can I trust you with checking my bank balance online?” It never gets round to answering. It’s this bond though that drew me to a story last week that said that one of the computers at the Uganda National Roads Authority (UNRA) had been kidnapped, or ‘stolen’ as the newspaper put it. I could feel my keyboard quiver as my PC monitor flickered, displaying the story of its colleague’s unfortunate demise. Computers everywhere deserve justice! The perpetrators of this unjust act must be brought to book, I told my now sobbing PC. I gave it a moment then got to work to unearth some of the possible places the ‘stolen’ computer might be. Because my skilling is in writing and not chasing and tackling computer thieves, I’ll share non-anonymous tipoffs with the police here.

It received a Facebook message saying “Hi my dear. I like your profile pic. I have a thing to share with you,” and it fell in love with the sender. It’s on its way to Nigeria to meet them

It was tired of autocorrecting typos. No amount of training had prepared it for all those typos. It’s on leave in Ssese

It’d heard of this thing called Twitter and it wanted to visit it. It’s trying to get a visa

It didn’t see its career prospects improving at UNRA. Whenever the computers of one of the bosses crashed, it was always passed over for the promotion. A shiny new computer was always wheeled in. Enough was enough. It’s in the village trying its hand at agriculture

It wanted to see the world. Answering Google searches for correct bitumen levels in a road and local music wasn’t quite what it’s dreamed of doing with its life. It’s on a retreat doing some hard-drive searching

Those people in IT hadn’t cleaned it in a while. It needed a decent shower. It’s somewhere waiting on rain

IT needed to try its RAM at sports betting. It’s in Kabalagala, making bets with everything in it

How to update your local yum repo

There are a number of  great resources on how to set-up a local yum repo. This one from Digital Ocean is particularly good:
https://www.digitalocean.com/community/tutorials/how-to-set-up-and-use-yum-repositories-on-a-centos-6-vps

How though do you update the said yum repo? I needed to upgrade bash on some hosts to protect them against being ShellShock-ed. This required an upgrade to the local repo from which all these hosts retrieve their updates. Here’s what worked for me:

  1. Download the rpm for the package you’d like to update in your repo
  2. Place the rpm in your repo’s Packages folder
  3. Then
    cd /the/repo/dir
    createrepo . #{Don't leave out the .}
    yum clean expire-cache
    yum list --showduplicates package 
  4. The package you’ve added should appear under Available Packages. If it does, on the clients you can now run
    yum update package