Skip navigation

Tag Archives: python vs java

Following up from my previous post, I have decided to use Java for Museic since, ironically, it looks easier to write platform-portable code that plays MP3 files in Java than in Python. And well it is but that is not to say that the road to my goal was bump-free.

First off, the “default” way to play MP3 files in Java would be to use the JavaFX library. However, JavaFX is not at all available in Java 6 (you need to include specific JARs in your class path to use it), only half-included in Java 7 (you still need to be specific with your class path), and fully-included only in Java 8.

The obvious way to stop worrying at all about the version of Java installed in your system is to use a dependency manager, my choice being Maven. Maven has a JavaFX plugin. All you need to do is (1) fix your class path by issuing the command mvn com.zenjava:javafx-maven-plugin:2.0:fix-classpath and (2) add the following in your pom.xml

<plugin>
    <groupId>com.zenjava</groupId>
    <artifactId>javafx-maven-plugin</artifactId>
    <version>2.0</version>
    <configuration>
        <mainClass>[put your application main class here]</mainClass>
    </configuration>
</plugin>

Alas, I wish it was that easy. In my system, it was complaining about some missing JARs. It seemed to me that I was encountering the very problems I hoped to avoid by using Maven.

Then I realized that I was using OpenJDK 7 instead of Oracle JDK 7. Now, I’m aware of the distinction between OpenJDK and Oracle JDK; at Chikka, we’ve made it a point to use Oracle JDK in production. Nonetheless, for my personal projects, I’ve never experienced any significant difference of OpenJDK so I kept using it as it took less effort to install in Ubuntu. Until now.

The moral of the story is: if you are going to use JavaFX, make sure you are using Oracle JDK.

(And yes, Museic is now playing MP3 files with my desired delay, thank you very much. It’s now my practice/jam buddy!)

From my last post, I’m taking a little break from Chess as I turn my attention to a guitar I bought as a Christmas gift to myself. You see, I’m in the process of becoming a Guitar God, ala Jason Mraz, but that story is better reserved for my main blog no?

And well, since I can’t personally jam with Jason Mraz (or Chris Martin), I settle for MP3’s of his songs. The problem is, MP3s play abruptly without warning. There is no sufficient time between my hand pressing play and the song playing!

Jason Mraz Fanboy

And yes, I do have the CDs!

None of the MP3 players I know of is aspiring-musician-friendly as such. So, obviously, this makes it a nice candidate for a quick hack.

My requirements are simple:

  • Have a UI
  • Be able to play an MP3 file after a set countdown. And it has to be in MP3 format, hard requirement. If it is to be of any use with minimal hassles, it has to be MP3.

 

The first requirement makes it a good candidate for a web/JavaScript app. But then, as far as I know, JavaScript is not allowed access to the local filesystem for security purposes. So JavaScript (unfortunately) rules out the more-important requirement of the two I have.

The next obvious choice is Java since I’m quite used to utilizing Swing to develop desktop GUIs; in fact, I created the user interface of our thesis in Swing, from ground up. However, for a quick hack, I think Java might be overkill and there’s this Python library I’ve been wanting to play with for so long…

Kivy!

Kivy can handle my UI requirement, and rather beautifully so, if I may say. Now, searching around, there are multiple ways to play an MP3 file with Python. One of them is even a Kivy library! The other libraries I found are mp3play, musicplayer, and PyGame.

But one by one, problems emerged

  • PyGame’s mp3 support is limited.
  • The sample code in musicplayer’s PyPi page looks too complicated. (Yes, since this is just a quick project, I’m in lazy mode.)
  • mp3play only works for Windows XP.

 

And then the Kivy library. It would’ve been sweet to have a single library for all my project’s requirements. But alas…

Kivy has a SoundLoader class which automagically determines the best way to handle the given sound file’s format. I’m not good with design pattern terminology but, the way I see it, it looks like a combination of Factory and Strategy patterns. However, when I test code given in their documentation, I come across the following logs:

[INFO ] Kivy v1.8.0
[INFO ] [Logger ] Record log in /home/chad/.kivy/logs/kivy_15-01-04_6.txt
[DEBUG ] [Audio ] register SoundPygame
[INFO ] [Audio ] Providers: audio_pygame (audio_pygst, audio_sdl ignored)
[WARNING] [Audio ] Unable to find a loader for <test.mp3>

 

The only provider that loaded is PyGame’s. And, as I’ve noted above, PyGame’s mp3 support is shaky. In fact, Kivy’s code as of presstime only allows PyGame on MP3 files if it is running on Android. audio_pygst would’ve done the trick but then, as the logs indicate, it did not load.

So why did it not load? Looking at audio_pygst’s code, it imports the modules gi, pygst, and gst, in that order, respectively surrounded in try-catch statements should there be problems on the import.

I try to load them manually on Python’s shell and get the following result:

chad@galadriel:kivy$ python
Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import gi
>>> import pygst
>>> import gst
/usr/lib/python2.7/dist-packages/gobject/constants.py:24: Warning: g_boxed_type_register_static: assertion `g_type_from_name (name) == 0' failed
  import gobject._gobject
>>>

 

Looking around, this seems to be an issue with gst 0.10.x. The obvious solution would be to upgrade. Unfortunately, gst updates for Ubuntu 12.04LTS seem to have stopped at 0.10.

So there. Much ado achieving nothing, for a quick hack. Maybe, I’ll look into using Java for this project, moving forward. Stay tuned!

Coldplay Fanboy

I’ve always wanted to discuss algorithm problems here but a quick look over at my posts (even just the tags) reveals that I haven’t really done much of that. Over at Github, I have a repository dedicated to solving Programming Praxis problems1 and I’ve thought of discussing my answers here but I haven’t had the time. My interview with Google is, I think, a good chance to dish out something similar to my intentions.

(Author’s note: Of course, I won’t discuss the specific problems I encountered during my interview. For reasons that will become clear if you think about it for a moment, Google clearly prohibits that.)

There are three stages I encountered during Google’s interview process. The first is a short initial (phone) chat with a recruiting coordinator. Next I had a phone technical interview which, aside from taking a longer amount of time, had me coding on a Google Doc. The third part is where they flew me to Mountain View, an interview which Google terms as “panel interview” but I will forever stubbornly refer to as a “circuit interview”.

My interviews, in general, looked at my problem solving skills. For a company like Google, I expected that they will be more interested in my engineering competence, i.e., questions like “How do you get things done?”, “What frameworks have you used?”, “Why would assembly trump everything?”, “Concurrency, Cloud Computing, Parallelization, Multi-core issues, Efficient Caching Mechanism, High-Throughput Responsive MVC Framework Layer MOAAARRRRR!!!”2 .

Watch this short video featuring Laszlo Block on the type of people Google is after. It may be hard to believe, as it was for me, but based on my experience, this is so true.

Overall, I’d say that my Google interview was 85% algorithms/problem solving and 15% engineering.

I found the second phone interview a bit bumpy that afterwards I did not really expect much. I was just happy that I got a Googler asking me technical questions. My interviewer’s voice wasn’t very clear through the phone (as opposed to the first one). It did not help that I was having coughs that day which later developed into a slight fever.

And, as you may know, Google Docs isn’t really made for coding. I wish Google used a platform more suitable for writing code than a word-processing document. My interviewer wasn’t meticulous about syntax but it was still awkward indenting my lines.

That said, here are some tips:

  1. For this part, do not use Python (or any similar whitespace-based language). I was intending to use Python even though I’ve already expected indentation to be difficult. Thankfully, my interviewer stated at the beginning that he’d prefer me to use Java. With Java, you can skip indentation for small blocks of code. Convenient when your line is getting long or the nesting goes deep3.
  2. Indent using two spaces. This is the indentation style of my first company. Tab is too wide and your lines might easily bleed off the edge, especially if you follow my first tip (new BufferedReader is already 18 characters!).

    Why indent at all? Well, no one’s forcing you but I find it easier to debug if I have indentations. Moreover, code is easier to read.

  3. Don’t hesitate to use the Google Doc for things other than code (like clarifications). Remember I said that my interviewer’s voice through the phone wasn’t very clear? Well, this is exactly what saved me.

As for the onsite, Google will be kind enough to fly its candidates in two days before the actual interview so you can settle down. Due to PyCon Philippines, I was unable to take full advantage of this. Nonetheless, I felt little to no jetlag that I even had time to explore a bit on my first night.

Here’s a little tip though: when coordinating with Google’s recruitment team, be clear and patient when it comes to your travel requirements. Based on my experience, Google’s recruitment team is very accommodating and helpful but that is not to say that they are 100% knowledgeable on the arrangements their applicants have to make for travel. (Cut them some slack as I’m sure they handle applicants from more countries than what you can name off the top of your head.)

In my case, I raised the point of needing a Visa for USA travel early on but it was ignored in the email thread so I assumed it’s okay. Thankfully, the issue came up when I coordinated with their preferred travel agency. This delayed me by almost a month. I should’ve been persistent because I’ve been raised since childhood knowing that Filipinos entering the USA need a USA Visa.

Google would really want you to focus on your interview so there is very little that you need to mind during your stay. They’d have your basics covered (accommodation, reimbursable food allowance, reimbursable transportation allowance) so just keep your receipts.

Here’s the interesting part. The onsite interview itself will last for five hours, lunch included (for comparison, the longest job interview I’ve had lasted for, I think, three hours, and it was more a personality interview; HR was talking to me). The reason why I will forever term it as “circuit interview” is because you will have five sets of interviewers, each of them in turn, as opposed to having all your interviewers in one panel.

As I’ve said, my interview was more algorithmic than engineering. One of my biggest anxieties was if they’d give questions the kind they give at ACM ICPC. I’m pretty sure I’d be tongue-tied had that happened. But fear not. The problems I encountered were less obscure and they won’t require you to provide full implementations for the more complicated ones.

Well, I did not make it so you may want to take the following with some grains of salt. But, hey, some tips:

  1. Use Python, finally. Or, bring your own whiteboard markers, as Steve Yegge advises. I’ve read Steve Yegge’s post prior to my interview but I missed the point on his tip about the whiteboard markers. I thought he was advising it just for the “preparedness” factor but notice that he advises it for the sake of whiteboard space. And yes, whiteboard space can be a real blessing. I want to note that, when I was there, Google’s Mountain View office had those flat-tip markers in stock, the kind like highlighters. In my opinion, that’s worse for an interview than the “fat ones” Yegge refers to in his post.

    Nonetheless, with Python, I was able to squeeze in three functions plus lots of scratch and some illustrations in a whiteboard of standard office size. I cannot imagine how that’d look like with Java (or worse, C/C++), nor can I overstate how good a thing is this.

    For the record, I brought my own whiteboard marker but I did not use it, did not even show or mention it, because I got anxious as to coming across as “too eager”.

  2. Use Python, again. This might vary from programmer to programmer but Python gave the advantage that I can focus on high level stuff. Given the nature of Google’s interview process, I believe this worked to my advantage. It’s really like doing runnable pseudocode.
  3. Use Python, not. I think I know where the weak points of my interview was and I believe I was weakest during the last interview. You see, the interviewer started with “I heard you use Python so just keep using that.” So I did. But then he gave me a problem that would require some low-level manipulation and, as I was using Python, I took time clarifying what am I allowed to do and what am I allowed to assume.
  4. Just keep talking. Remember my anxiety above that I might get tongue-tied? Well, here’s the tip: just keep talking, as long as you’re making relative sense. I’ve been told in a pre-interview email that they want to learn how I think so think out loud. Obviously, I’m not sure if this worked to my advantage or what but at least I managed to avoid that Great Wall of Social Awkwardness Produced by Silence. It might even help you; there was a part in my interview when I was like “Let me try some combinatorics here…so 2 will give this…3 will give that…but 4, oh wait—this is easier to to solve programmatically!”. No kidding.
  5. Relax, this isn’t the ACM ICPC. This comparison might deserve a post on its own but for now, the most obvious difference is the time constraint. I realized that the people interviewing me would like to get a picture of me in just around 45 minutes. So, in contrast to the ACM, they’d give you problems that are solvable in 45 minutes or less. Moreover, your code won’t be ran so (at least I think, and this I did), you are allowed a certain extent of handwaving and just say this function does this and that. At times, high-level descriptions of algorithms will also suffice (read: implementation, with all the debugging that might entail, is not needed).

Finally and most importantly, Prepare with a capital ‘P’. Read the Steve Yegge blog post I linked above and follow his advice on having long-term and short-term preparations. I just said above that Google interview isn’t ACM ICPC but I think ACM ICPC is good standard practice material and not just for Google interviews.

What do you prepare for? In my case, knowledge of data structures like some obscure variants of balanced binary trees and even-rarer forms of trees and forests helped as it gave me some talking points. A good knowledge of textbook algorithms will also help. In one case, repurposing a textbook algorithm allowed me to reduce a naive O(n2) algorithm to just O(n).

That said, even if you’re not planning to take a Google interview anywhere in the foreseeable future, I still find preparations of this kind useful for everyday. So just keep reading up and honing your problem solving knack!

  1. I have a similar private repository for the other algorithm problems I’m solving—ACM ICPC practice, to be specific. As a matter of principle, I’m willing to show my code solution to algorithm problems provided that the problem setters are expressly showing solutions, as with Programming Praxis. []
  2. Okay I’m trying to be funny here. But you get my idea of engineering vs. algorithmic skill. []
  3. Generally, I’d be cautious against getting too deep a nesting. When I encounter this in my code, it’s a sure sign that I’m getting lost and that maybe I need to refactor or re-read the problem []

Okay. I know it’s already February and that it’s kinda late. But it’s in times like this that I say “better late than never!”. But as I’ll show, I’ve already started with my resolutions—I’m just writing about them now.

But since this is my coding blog, the resolution I will mention here will be my technical-life resolution (as opposed to the personal ones everybody makes). So, without further ado…

I resolve to learn a new technology every month. Or, at least, get deeper with one I’m already acquainted with.

Also, I’d go into programming competitions/contests again. Team requirements limit my choices but, hey, there are a lot I can do alone online, not to mention free! (Though if anyone wants to team-up with me, let’s talk.)

And, just so I’ll stick with it, I’ll write a blog post every month about what I’ve been up to. Consider this the one for January.

For my first resolution, I created this sandbox repository at GitHub. And since my GitHub account is, in itself, already my sandbox of sorts, I guess this is some sandbox-ception eh?

January, I did sockets in Python. I didn’t manage to dig as deep as I’d have wanted because the Facebook Hacker Cup kicked in earlier than I expected and that falls under my second resolution. So it had to give way. Besides, I’m already dealing with a few sockets too many at work.

Regarding my second resolution, I don’t really expect much from it. At least, I won’t get rusty from the lack of problem sets in the real world (read: industry). At most, I might score a free trip to some world finals. But that world-finals scenario is still very out of my league. I’ve been doing ACM-ICPC problems since I was in my sophomore year in College and even now I find most of them really tough and tricky. Also, after less than a year out of school, I’m bound to have some rust in my system (not that school is a sure fire way to keep you sharp though). I only decided to start practicing with my algorithms sometime in December so there isn’t really much to expect.

(Note: I started writing this post in the last hour before the first round of Hacker Cup started. It’s now over and everything fell within my expectations. There’s a lot to learn. Maybe, I’ll write about this soon.)


So, what do I think about sockets in Python? (This will be short since, as mentioned, I didn’t have much time to dig deep into this.)

As with all things Python, it looks super neat. I got a client and server up and running in just 41 lines of code combined. The biggest savings comes from the fact that socket I/O is direct in Python; you no longer have to create OutputStream and InputStream objects as the socket objects themselves have methods for sending and receiving. It’s also interesting to note that Python’s socketserver class has a serve_forever method which, as the name implies, handles requests as long as it can (the official phrase is: “until an explicit shutdown signal is received”).

Oddly, this design reminds me how I handled one of the things I did at work. Won’t go into the details but I thought that it’s neat to have one class responsible for managing one whole session: packet numbers, windowing, etc. One instance of a class maps to one client; when client goes away so does this instance (at least, I no longer care if the garbage collector marks it as garbage). Makes OO live more peacefully with concurrency.

Awesome that Python enforces this design by default. Really, the more I discover about Python, the lovelier programming gets.

‘Till I get my February experiments done! ~Chad

It seems that I’m done coding the A* search of my n-puzzle solver. I spent almost all of last week doing it, as I discovered that there are some flaws in my understanding of A*.

The web doesn’t seem to have a lot of resources on A* compare to, say, graph algorithms. Google “a* search” and the only relevant link you’ll get is the first hit, a Wikipedia article at that. The second search hit, remarkably funny (for me, at least), is a search engine for cemetery records. The best search terms seem to be either “a* search algorithm” or “a* searching algorithm“. And even at that, not all the hits in page one have something to do with A*. Compare with, say, googling for “bellman ford” to find resources on the Bellman Ford algorithm. The best A* resource for beginner’s that I found on the the web will be this.

I said that my A* seems to work because I haven’t managed to make it solve randomly generated solvable instances yet; solving time takes too long that my computer heats up so much to the point of auto shut down. I’ve managed to get it to solve an instance with a Manhattan distance of 11 but I haven’t tried anything further than that yet (the randomly generated instances of size n=15 usually take a Manhattan distance of around 30, give or take).

I wonder how things would’ve went if I implemented my search in Java instead of Python. I remember, when I ran a (hopelessly inefficient) Java brute-force Sudoku solver in my old HP Pavilion DV1000 (default specs, i.e., Windows XP Home Edition, 1.5GHz processor, 512MB RAM), I managed to keep it up for hours, though, to make things fair, I did that in an air-conditioned room. For comparison, I ran my A* on a Gateway T-series (can’t give exact model as it is not available on surface inspection, sorry), running Ubuntu 10.04 (Lucid Lynx) with AMD Turion 64 X2 (approx 2GHz) processor and 2GB RAM, room temperature.

Maybe, I’ll look into Iterative Deepening A* next with some time.sleep lines thrown in the code to allow time for my system to cool down. Stay tuned.