Code Reading #1: Slick callback registration in MonoDevelop

I’m starting a new category of blog posts called ”Code Reading” where I’ll talk about something interesting I saw during my week of coding, with some code snippets of course.

Just today, this caught my eye when I was trying to figure out how to hook into an event in the Vim addin that I was trying to package up. So there is a global preferences window where the user checks boxes to enable certain things, and one of them is vim input mode in the text editor. Basically, there’s a global PropertyService that exposes these selections, as well as fires an event when something is updated.

I found an example of how this event can be registered/unregistered in the SourceEditorOptions class. Registration happens in the constructor:

        DefaultSourceEditorOptions (MonoDevelop.Ide.Gui.Content.TextStylePolicy currentPolicy)
            LoadAllPrefs (); 
            UpdateStylePolicy (currentPolicy);
            PropertyService.PropertyChanged += UpdatePreferences;

And unregistration happens in the destructor:

        public override void Dispose()
            PropertyService.PropertyChanged -= UpdatePreferences;
            FontService.RemoveCallback (UpdateFont);

So PropertyChanged shows up in PropertyService on line 270:

public static event EventHandler<PropertyChangedEventArgs> PropertyChanged;

The interesting thing to me is the event keyword, which means there’s language-level support for event handling.

It’s really slick syntax to just add or subtract your event handler to the event as the highlighted lines above show. Let’s just peek at what that event handler looks like:

        void UpdatePreferences (object sender, PropertyChangedEventArgs args)
            try {
                switch (args.Key) {
                    case "TabIsReindent":
                    this.TabIsReindent = (bool)args.NewValue;
                    case "EnableSemanticHighlighting":
                    this.EnableSemanticHighlighting = (bool)args.NewValue;

So it’s interesting that you can just pass the member function around. There’s magic that happens inferring the type of that thing, but the point is that it is a first-class object. Here’s another more explicit example elsewhere:

            properties.PropertyChanged += delegate(object sender, PropertyChangedEventArgs args) {
                if (PropertyChanged != null)
                    PropertyChanged (sender, args);

I guess it’s a lambda function, but not quite, because they call it a delegate. But it has the signature and the body, all the same.

Well, I was really impressed when I tried to plug my own function in and got a compiler error indicating what the signature should have been. I wonder where it is specified and also where the event is generated. It’s a mystery to me, but I know that it’s a lot more heavyweight to achieve in C++.


Diary #21: Knee deep in templates, long compiles

So CGAL makes pretty use of C++ templates, and the Summer of Code project that I am working on builds a Qt4 visualization of 2D arrangements, one of these CGAL data structures for building collections of 2D curves. I decided to make the individual UI and event handling components templated by the type of arrangement and specialize as needed, and I think it ended up saving me a lot of typing. The problem is the compilation time for the full demo is pretty substantial.


A clean actually took 5 minutes using a parallel build on a 4-core system. What’s hard to see is that actually one core gets stuck compiling a certain few files, for example, ArrangementDemoWindow.cpp is a major culprit. This bad boy is responsible for instantiating ArrangementDemoTab, which is templated by currently six different types of arrangements. Each of these tabs instantiate another level of at least six callback components that handle various operations on arrangements. There is a Qt GraphicsItem subclass for visualizing the actual arrangement that is also templated based on the arrangements. Finally, each of the components make use of little utility classes that are templated based on types provided by the arrangement type.

Now, C++ has no choice but to generate code for implicitly instantiated classes on the spot. so it’s probably no surprise that the memory usage spikes up to 4.1 GB when it hits a “fat” class like ArrangementDemoWindow. Sure, ArrangementDemoWindow.cpp is 1200 lines of code, but that shouldn’t cause such a massive effect. Unless you are a compiler that needs to instantiate a wide swath of template classes on demand to do type checking and such. So the silent console fails to convey the chaos that is happening behind the scenes, and the point is that there is a lot of redundant compilation happening.

So, it’s become an absolute pain to try to do any debugging with the full demo. It means that a single line change in a fat class like ArrangementDemoWindow means you have no choice but to sit through the deep compilation of all those templated classes, even if none of them changed at all. I’m fed up with it. Currently, I have to write a smaller UI example that instantiates only one type at a time so that recompilation is not so ridiculous.

But all this really makes me ask, is all this really unavoidable? Couldn’t I explicitly instantiate a certain set of template classes, precompile them once, and save them to a library for linking later on? How can I indicate this to the compiler?

Actually, if we could make use of C++11 features, we can use the extern templates feature to introduce some modularity. For example, suppose you wanted to precompile a vector of ints type. You can put this in your IntVector.h:

    #include <vector>
    extern template class std::vector<int>;
    typedef std::vector<int> IntVector;

and this in your IntVector.cpp:

    #include "IntVector.h"
    // instantiates the entire class from the default template
    template class std::vector<int>;

Then you can include the header file whenever you want to use IntVector. Wherever you use it, the compiler will not generate any code like it normally does, but you will need to compile IntVector.cpp and link its object. Now imagine if you have a lot of templated classes that are tied together with dependent parameter types and collaborate closely. Then this can save a ton of compilation time.

Clang will do it, and I guess g++ should do it if you set it to c++11 mode. But as always, I need to support the older compilers, so that’s right out.

Diary #20: The final year is coming

I had my last face-to-face meeting with my advisor last Friday, who will be relocating to his new post in Louisiana state. In our meeting, we hashed out some rough plans about how I will be finishing out my graduate studies and moving on. The month of April of next year got labelled with the big red X to signify the point in time where I should have my research finished and should dedicate fully to writing my thesis and ultimately graduating.

The end is in sight.

But getting a Ph.D. isn’t the final step: as one of my committee members indicated, it is the beginning. Unfortunately, I don’t have the intent to set out on the track to becoming a professor like he is. However, I intend to put the skills that I’ve picked up to good use as a research/software engineer.

Much like at the end of high school and college, I’m being told to do some soul-searching and to talk to people about what it’s like. I think, though, that I have largely made up my mind, and I really just want to focus on successful execution of the things that have to happen with the rest of my time here so that I can move on.

I don’t really regret getting into graduate school. I knew it was something that I wanted to do by taking up a double major as an undergraduate, and I followed through with it. As a graduate student, you end up doing a little bit of everything out of necessity, and I’m glad to have applied myself and accomplished what I have up to this point. Having done all of this, I feel like I am clear now on what I like to do, what my skills are, and how I will use/develop them to contribute to society and fulfill myself from here on out.

I am really looking forward to getting out, but there’s still a lot to be done, both to get out, and to get to the next step.

For one, I’m going to need to get started on interview preparation. As ashamed as I am to admit it, I have never gone through the process of interview to employment with any company. I’ve spent most of my life working through school. The closest thing I’ve had to an internship was this thing with Summer of Code, but it’s mainly facilitated online. So it’s not a matter of brushing up on something I haven’t done in a while, but this is going to be a brand new experience for me. I’ve ordered the Cracking the Coding Interview book that was recommended by the CS club and will use it to review algorithms as well as learn how to conduct myself.

Another thing is I need to do some additional research. At this point, I officially feel like I’m stuck in a rut. There’s certainly a roadmap and a direction to go, but (1) code is pretty unreliable, if not broken, and (2) I need to another way to compare results with other methods. Also (3) I need to figure out the details of the next and final method I will be working on.

I think I need to be careful and pace myself. This is the last summer that I will have, and it is going by really fast. There’s a lot that I want to do and also things that I have to do.

As long as I stay focused, I can do this.

Japan travel 2

Last time, I talked a little bit about Japan travel, and this time, I’ll talk about my experience using some of the internet cafes while I was over there.

The hostel that we stayed at provided complementary wifi access, but as with most complementary wifi, it wasn’t reliable. We also rented a Softbank wifi hotspot at the airport, but it was not very reliable, either. I needed to get some work done, so I figured I would go for an internet cafe.

A quick net search revealed one in the area we were staying called Comic Buster. As a general note, I think these stores usually serve Japanese residents, because you need to register in order to use the computers. The first shop clerk asked me if I lived around here and ended up taking my hotel address and number. I think that she thought it was a one-time thing, so she didn’t take my $3 membership fee, but I had to come back later because I didn’t finish my work, and I had to go through that with a different shop clerk…

Now that I’m actually reading the page that I linked, doesn’t it say that I get free registration if I mention that I saw the note on the home page? Damn, I lost 300 yen…


Well, I was set up with a private booth, which is the standard setup. The walls are probably as tall as a typical fence, and there’s a clear door that you slide closed and can cast a blanket over to secure your privacy. You get a Windows 7 PC. The JP keyboard layout is pretty funky, I had trouble finding certain special symbols for some reason:


I don’t think I was supposed to, but I ended up hijacking the ethernet cable from the desktop for my own laptop. It was a lot harder in the booth that I got during the evening because of how little space there was in the booth and how the chair was completely not adjustable.

When we went to Tokyo, we also needed another place to hide out from the rain and have internet until we could check in with the person we were staying at in the evening, so asking around, we found a Gera Gera tucked away on the 3rd floor of a building. In hindsight, It’s pretty easy to find if I knew to look up and pay attention to the signs. We had to go through the same registration process, and it was kind of awkward to agree to all the things the shop clerk was telling me in spite of not following most of it — well, we got service, so I guess that it was a success, and it was kind of interesting. I felt sorry for the guests who had to wait until we were done with, though.

There seems to be a lot of different internet cafe chains throughout Japan. While transferring stations, I was handed a pack of tissues, complements of the nearby Space Create. I checked out their website and was surprised to find that they actually put some effort into catering to their female guests. I gotta say, those look like pretty nice booths, and I wonder if they actually see some patronage.

In conclusion, the net cafes are not what I imagined them to be. They really emphasize privacy, and there’s really not a lot of open space. There were “open” booths rather than “private” booths in the Comic Buster that I saw, which amounted to a lounge chair facing out of the window, but there were only a few of those compared to the dozens of booths there were. I guess it’s no big surprise, given the lack of space in general, and you probably don’t need or want an open space for the stuff you’d come to a net cafe to do.

I’m a little scared to think that it really seems like a great place to hang out in Japan: there’s great internet, there’s shelves and shelves of manga, there’s unlimited drinks from the fountain, and you can even order cheap food. I think I saw a shower room in the back as well. It really seems like an ideal setup to sink all of your time there if you wanted to. I feel like the novelty of traveling in Japan was the only thing that made me think of it as a waste of time to hang out there for too long, but it that kind of place really appeals to me…

Diary #19: Back to the grind; things on the mind

I’m pretty relieved to be back at my apartment where I have a stable internet connection and easy access to food, water, bathroom, and bed. It’s pretty scary how ideal of a setting that is, considering that this is exactly what you pay for when you go to a net cafe in Japan (coming in the next blog post). But still, when I sit down for a day of coding, I can’t get some things off of my mind.

One of them is graduate school work. I really want to shut it out for the entire summer, but I know that it’s not possible if I want to make steady progress towards graduation. At least, I will shut it out completely until next week when I clear midterm evaluations for Summer of Code.

I am feeling anxious about the future. I’m feeling like I’m not so well equipped for where I am going. I’m definitely not going any further into academia. However pleasant the rare occasion I get to talk to fellow academicians is, I really don’t feel like I should be in such a place, and I feel like I’ll be happier and more productive as an engineer. That being said, I feel like I’m missing the cold hard technical skills that I need to step into the place I want to work in when I get out. So I’m pursuing that, which kind of drags on the things I need to do to get out in the first place. It’s a deadly cycle.

I look at the past few days and think of the cool things that I’ve learned and done. Learning about how to select an optimal interval to uniformly sample a parameterized curve so that the polyline approximation is sufficiently accurate was really cool. Figuring out the API changes for MonoDevelop addins and updating addin code to keep up with the latest release was cool, too. I like this stuff.

Basically, I need to give more thought to how I am going to finish, because it feels like I’m getting stuck. At the same time, I need to keep it up, because I feel like I don’t quite have a next step.

Japan travel 1

I’ve returned from a 10-day trip to Kyoto, which included a 4-day attendance at a computational geometry conference. There’s a lot to write about, so I’ll break it out over multiple posts.

First sight of the islands.

First sight of the islands.

I’ll start by talking about the place we stayed and the surroundings. We stayed at the Kyoto branch of the Khaosan Guest House, which Carlos found online. It was very luxurious in my mental expectation of what a hostel should have, and the staff were really nice and helpful. I would say it is comfortable enough to be able to take a family to (mature kids, ideally, since the walls are thin).

You leave your shoes off before going to your room in Khaosan Guest House.

You leave your shoes off before going to your room in Khaosan Guest House.

A shot down the hall of the private twin rooms in Khaosan Guest House.

A shot down the hall of the private twin rooms in Khaosan Guest House.

The rooms are Japanese-sized, with the doorways offering just slightly over six feet clearance, but it’s plenty accommodating, and the amenities are great. You can go upstairs to the lounge to do laundry, store your leftovers in a fridge, meet other travelers, or check out information about the surroundings. This place really is ideal for travelers.

A shot of the shared bathrooms, with toilets along the right, and showers further down the hall.

A shot of the shared bathrooms, with toilets along the right, and showers further down the hall.

Here is authentic Japanese culture/hospitality in the form of a fancy toilet!

Here is authentic Japanese culture/hospitality in the form of a fancy toilet!

Here's a close-up of the controls for the toilet seat.

Here’s a close-up of the controls for the toilet seat.

Unfortunately, we didn’t have a reservation through the weekend and was off in Tokyo, so we weren’t around for the language exchange or walking tour events that they put on, but it sounded like awesome events that I would join in on in a heartbeat.

Next, I’ll talk a bit about some of the surroundings of where we stayed.

Diary #18: Thoughts on using Pelican, making gifs on Linux

Making GIFs is fun

I needed to make some GIFs for slides/web presentation of work at an upcoming conference, and I came across this useful post. It seems like he goes overboard with the script, so I made a simpler version that just prompts for a box with xrectsel and records with byzans-record.


function usage
    echo "Usage: $0 [-h] [-d duration in seconds] [output_file (Default: /tmp/capture.gif)]"
    exit 1


while getopts ":hnd:" opt; do
    case "${opt}" in

if [[ $# == 1 ]]; then

COMMAND=byzanz-record --verbose --delay=0 $(xrectsel "--x=%x --y=%y --width=%w --height=%h") --duration=${DURATION} ${OUTPUT}
if $DRY_RUN; then
    echo ${COMMAND}

As a note, byzanz was pretty easy to build from source — I just needed


At the end of it all, I realized that GIFs are really worth a tens/hundreds of thousands of words, and I need to make more of them. I imagine this will be super useful for GUI-intensive tutorials — for example, every damn Blender tutorial starts off by telling you to go to a particular menu option and doesn’t offer any keyboard shortcuts or even any description of how to get there. A single GIF can clear this up.

Also, it’s just cool to show off something that looks nice. I guess this is what the cool kids on Tumblr and Reddit have been doing ages ago but whatever.

Broken gif here

It’s broken because I believe the WordPress theme is somehow injecting a “?640” at the end of the GIF URL, which causes a 404 error. I am too sleepy to figure this out.

Actually, I did figure it out with the help of some awesome WordPress support, and strangely enough it had to do with an error in the .gif file that I’d uploaded. After re-uploading it, the dimensions that get appended to the end of the image links don’t prevent it from displaying.


I also got Pelican to work, and it’s pretty fun. I’m too sleepy to finish this journal.

I’ll write it up in another blog.