Category: Coding

Writing my first iPhone app – Day 6 – Its all coming together

Finally managed to unpack everything after moving flats so no more boxes, yey! Unfortunately somehow managed to lose the box with my socks and underwear tho. Oh well, you win some you lose some. Anyway, had some time today to work on this app of mine.

First of all I wanted to pretty it up a little bit. I have no sense of style at all (don’t think any coder does) but I do not like working with anything too messy. So here are a couple of things I did to make me feel more comfortable:

I’ve reordered my tabs in my TabBarController to make the “Play” item to be in the center. For much of my surprise the storyboard editor doesn’t let me select the default tab. I realized that I have to extend the TabBarController. So after much research I found a code snippet that did the trick

I’ve also made the tab bar’s color scheme inverse so the above code takes care of the font colors as well. I also wanted to display a heading on all pages with a title so dragged in a Navigation Controller and connected it to my Tab Bar Controller. It displayed the heading placeholder but I couldn’t find a way in the storyboard editor to set the text for each tab element. Clever people of stack overflow said that i can set the title from the ViewDidAppear method of each controller. Here is an example of how:

Since I really don’t like the UIColor API (coming from web development background I think it’s understandable) I was looking for an easy to use alternative. Thats how i found UIColorExtension. Its a simple extension that allows me to use RGB(a) hex codes in my color definitions. So I can write stuff like this:

Winning (except for the 15 minutes it took me how to do # on a mac keyboard)

Also replaced my label that was used for the countdown with a Progress View. Progress View’s are really straight forward to use:

All right. I think I’m done with prettying stuff up. It is still ugly as fuck but bit easier on the eye:

Screen Shot 2015-06-14 at 15.49.32

I hooked it up with the question API I made in my previous post and it worked like a charm. Except one thing: Since the API was using random sometimes it gave me the same question twice. In order to avoid that I needed to log the user’s answers. So created a new table:

And a new class:

The PHP API has been modified a little as well to able to record answers + avoid sending the same question to the same user again:

Great, now the only thing left to do is to make the app send home the user’s answer for logging. In my PlayViewController I modified the logic that happens when the user clicks one of the answer buttons:

When the user hits the button it just checks against self.currentCorrectAnswer and depending on the result it sends home the questionId, userId and 0 or 1 for logging.

Finally I decided to make this project fully open source. Please feel free to fork / do a pull request / whatever, but keep in mind it is very much a work in progress and I have literally no idea what am I doing in Swift

Repo for the app | Repo for the PHP Api and scraper(s)

The game is actually playable now and it is moderately entertaining. Will need to find a new source of questions because the current ones are way too British.

What is next? The gameplay is pretty much ready now. It needs some refactoring and some security on the API but its ok for now. Next time I’m going to work on the leaderboard view. Deal with some TableViews in xcode and probably implement Facebook friend list somehow.

Be Sociable, Share!

Writing my first iPhone app – Day 5

Ok, I’m cheating a little bit here. I did not work on the app during the past two weeks or so but I have very good reasons. First of all I moved to a new flat (which I absolutely love btw) and as you know moving is hard. Secondly the Macbook I borrowed from work pretty much died under me. It kept presenting the so called “black screen of death” 9 out of 10 times I tried to boot. Tried to do all the PRAM resets and mental keyboard combos I could find online but no joy. Anyway, bought the new generation Macbook Pro now (force touch trackpad rulez btw) so I’m back in business.

That being said yesterday I only worked on the back-end of the app. In order to go forward with the actual iOS development I needed some questions and answers in my database so I decided to look around to find a site which I can scrape. I’m really surprised that there are no good quiz sites around with 4 answers for each question and the correct answer included. Found some databases for sale that would fit my needs but the sales page were either crappy or the database was ridiculously overpriced. The only site I could find that met all my requirements is PubQuizArea, which ticks all the boxes, however it is really British. Oh well, it should do for now.

First of all I need a table structure:

The model for this is written with my No-BS Framework. It does not need to modify the base model at all, just need to define the table fields and some validation rules (question needs to be unique:

The main part of the job is writing a simple scraper. Luckily the site’s structure is pretty well thought out so it makes it easy to scrape:

I know I know. Heard it million times: my scraping style is really old school. Guess what? I tried all those hipster libraries for scraping which promise you bells and whistles, none of those worked for me. Every once in a while they stop working and it is really hard to find the actual issue under the hood. As always I’m using my trusty curl class to fetch the data.

The script is just looping through the subpages of the category url from the command line argument and get the question / answer data from them. Luckily the correct answer is highlighted with a separate class (“blue”) so it is easy to recognize. $question->validate($db_data); takes care of removing dupes too.

That site gave me about ~1,800 questions. Obviously not enough, but will do for testing.

Last thing was to add an endpoint to my api. My __construct became:

And the implementation is:

Obviously this logic will change as I hook it up with the app (rand() doesn’t exactly prevents the user from getting the same question over and over again) but again, its ok for testing. If you fancy trying it out, click here

Be Sociable, Share!

Crappy Fizz-Buzz

Read this article today on HN about 5 alternatives for fizzbuzz for coding interviews. The last one was to write the worst fizzbuzz program you can come up with. It sounded like something i should do before my morning coffee so here is my entry:

Can you do worse?

PS: No movement on my iPhone app today since I decided to get drunk yesterday

Be Sociable, Share!

Writing my first iPhone app – Day 2

I have to say so far I’m liking Swift a lot. It is a nice, straight forward language with some awesome feature like conditionals.

Ok so what I did today? (well yesterday, but whatever)

First of all I added some new views to my interface. I realized that i will need to record the user’s activity on the server so I will need some sort of identifier to them. Of course I could just use the device’s ID but its better to make them create an account and use their login name / user id as the identifier. Anyway, I needed to add a login view as the first responder of my app. For now I will just add a simple button to redirect the flow to the “play” view, will deal with the actual registration later. Also added a new view to my tab controller for editing the user profile / view activity. Here is how my storyboard looks like at the moment:

Screen Shot 2015-05-23 at 21.12.25

The code for my LoginViewController is really just a placeholder now

loginOverride just redirects the user to my tabController where the game code kicks off.

Made some good progress with the game itself as well. Actually pretty much the whole game logic is done. I did set up a fake API for getting the questions. Here is the not so interesting PHP code

Turns out implementing async requests in Swift is fairly simple. Just have to call NSURLConnection.sendAsynchronousRequest and parse the response. 

One thing I’ve learned about this and it is very important: never ever (EVER) try to update UI elements directly from the async request’s callback because it won’t take effect. It took me like half an hour to recognize that my code in fact works, but the UI elements are not updated. Clever people on stackoverflow told me that I should use dispatch_async to with dispatch_get_main_queue() to tell the main execution thread to update the UI.

As for rendering the question, it is pretty straight forward:

I want to allow the user 30 seconds to answer each question. I really hoped that the SDK has some sort of built in timer object, otherwise I should have implemented my own recursive async thing which I really didn’t want to do. Fortunately the SDK in fact has an NSTimer class so implementing the countdown was easy:

The only thing left to do is to hook up the answer buttons and check if the answer is correct. I simply added a tag to each button 0,1,2,3 and linked the touch up event to a new custom action:

Simples. If the clicked button’s tag equals to the one got from the (fake) API display a big green message, otherwise a red one. In the future the app will report the result to the server for logging purposes and of course to move the player on the global board but that is for the future.

Tomorrow I’m gonna start building the server side a little bit and try to make the registration / login view and hopefully add Facebook login too

Be Sociable, Share!

Writing my first iPhone app – Day 1

So I decided to step a little bit out of my comfort zone professionally and try myself outside the scope of web development. I took a beginner course on Udemy about developing iPhone apps using Swift, but up until today I didn’t write a single line of Swift code. I hereby challenge myself to write my first app in 14 days. Now the app itself most probably won’t be ready for the app store straight away since I’m mostly focusing on functionality and not usability / design but it will be a good learning experience for me.

The app: The app will be a very simple game. Imagine a massive, 1 billion step board game with one single player. Everyone who is using the app will move the same player by answering trivia questions. If a given user answers the question correctly the player moves forward 1 step, otherwise it moves backwards one. I know, not the most original idea but it really is just for learning.

So here is what I did today (keep in mind I have literally no idea what I’m doing so probably I’m doing it all wrong)

I started off building a basic interface. What really surprised me, coming from web development, is how un-intuitive xcode’s interface (storyboard) builder is when it comes to “responsive” design. It took me ages to figure out how to make a single button stretch when I switch the emulator from iPhone 5s mode to iPhone 6. Basically you have to define the relative distance between the elements and the main view and the buttons will stretch to fill the space. I mean it kinda makes sense but how hard would it be for to allow defining sizes in %? Anyway my lame interface looks like this at the moment:

Screen Shot 2015-05-23 at 17.17.33

I know, it looks fugly but it renders properly in the simulator (still fugly but at least symmetric)

Screen Shot 2015-05-23 at 17.19.06

I can’t believe I spent like 3 hours on this, but at least I learnt something. Besides the interface I defined my outlets and set up a base controller which will handle my interaction with the (so far non-existent API) and update the interface elements as needed.

Screen Shot 2015-05-23 at 17.22.55

It really is a frustrating yet very fulfilling experience to code for iOS. I mean it is one thing to switch from PHP to Python but it is completely different when you are switching from web dev to desktop / mobile dev. I think the last time I had to deal with pointers and complex types was when I was like 14 coding in Borland Pascal.

Tomorrow I’m gonna hook up my class with a stub API and do some actual work on the logic. Will keep you posted (not like anyone is reading this)

Be Sociable, Share!

Facebook Hacker Cup 2013: My solutions

Task 1: Beautiful strings

When John was a little kid he didn’t have much to do. There was no internet, no Facebook, and no programs to hack on. So he did the only thing he could… he evaluated the beauty of strings in a quest to discover the most beautiful string in the world.

Given a string s, little Johnny defined the beauty of the string as the sum of the beauty of the letters in it.

The beauty of each letter is an integer between 1 and 26, inclusive, and no two letters have the same beauty. Johnny doesn’t care about whether letters are uppercase or lowercase, so that doesn’t affect the beauty of a letter. (Uppercase ‘F’ is exactly as beautiful as lowercase ‘f’, for example.)

You’re a student writing a report on the youth of this famous hacker. You found the string that Johnny considered most beautiful. What is the maximum possible beauty of this string?

The input file consists of a single integer m followed by m lines.

Your output should consist of, for each test case, a line containing the string “Case #x: y” where x is the case number (with 1 being the first case in the input file, 2 being the second, etc.) and y is the maximum beauty for that test case.

5 ≤ m ≤ 50
2 ≤ length of s ≤ 500

My solution for this problem was fairly straight forward. Not the fastest solution I guess, but it works: get the string, count the unique alpha characters in it and add up the “beauty”

Task 2: Balanced Smileys

Your friend John uses a lot of emoticons when you talk to him on Messenger. In addition to being a person who likes to express himself through emoticons, he hates unbalanced parenthesis so much that it makes him go :(

Sometimes he puts emoticons within parentheses, and you find it hard to tell if a parenthesis really is a parenthesis or part of an emoticon.

A message has balanced parentheses if it consists of one of the following:
– An empty string “”
– One or more of the following characters: ‘a’ to ‘z’, ‘ ‘ (a space) or ‘:’ (a colon)
– An open parenthesis ‘(‘, followed by a message with balanced parentheses, followed by a close parenthesis ‘)’.
– A message with balanced parentheses followed by another message with balanced parentheses.
– A smiley face “:)” or a frowny face “:(”

Write a program that determines if there is a way to interpret his message while leaving the parentheses balanced.

The first line of the input contains a number T (1 ≤ T ≤ 50), the number of test cases.
The following T lines each contain a message of length s that you got from John.

For each of the test cases numbered in order from 1 to T, output “Case #i: ” followed by a string stating whether or not it is possible that the message had balanced parentheses. If it is, the string should be “YES”, else it should be “NO” (all quotes for clarity only)
1 ≤ length of s ≤ 100

I spent quite a lot of time, about 40 minutes on this one. I ended up with a recursive function which relies on a regular expression: “/(\(.*)(:\))?(:\()?(\))/U”. This regex will match the parts of the string which are in brackets even if the parts are containing a smiley. Then it is just a loop for counting the opening and closing parentheses.

Task 3: Find the min

After sending smileys, John decided to play with arrays. Did you know that hackers enjoy playing with arrays? John has a zero-based index array, m, which contains n non-negative integers. However, only the first k values of the array are known to him, and he wants to figure out the rest.

John knows the following: for each index i, where k <= i < n, m[i] is the minimum non-negative integer which is *not* contained in the previous *k* values of m. For example, if k = 3, n = 4 and the known values of m are [2, 3, 0], he can figure out that m[3] = 1. John is very busy making the world more open and connected, as such, he doesn't have time to figure out the rest of the array. It is your task to help him. Given the first k values of m, calculate the nth value of this array. (i.e. m[n - 1]). Because the values of n and k can be very large, we use a pseudo-random number generator to calculate the first k values of m. Given positive integers a, b, c and r, the known values of m can be calculated as follows: m[0] = a m[i] = (b * m[i - 1] + c) % r, 0 < i < k Input The first line contains an integer T (T <= 20), the number of test cases. This is followed by T test cases, consisting of 2 lines each. The first line of each test case contains 2 space separated integers, n, k (1 <= k <= 10^5, k < n <= 10^9). The second line of each test case contains 4 space separated integers a, b, c, r (0 <= a, b, c <= 10^9, 1 <= r <= 10^9). Output For each test case, output a single line containing the case number and the nth element of m.

Well, I failed this task. Not because my solution wasn’t working. It wasn’t fast enough in some cases. I considered seed (it is not my first time on the Hacker cup) and tested it with large arrays but I missed a case when my script fails. The key speed up was when I realized that the analyzed array slices are repeating. They are repeating after every Kth element, therefor:

It gave me a huge speed up, but apparently not enough. I tried to run my script with the test cases provided by Facebook’s system and it didn’t finish in the 6 minutes limit even on the high-compute Amazon EC2 instances. Epic fail. Well next time. Anyway, my solution for task #3:

Be Sociable, Share!

PHP header(“location”); vulnerability

Every documentation and every code piece you can find about PHP’s header(“location: ….”); function recommends using die(); after the statement, but I never realized why until a couple of days ago. Most of the times I use die(); or exit(); after redirect statements, but for some reason I forgot to do so in one of my script. I learned the hard way why is it important: someone gained partial access to my site’s admin area. Turns out you can turn off redirects in your browser and in that case the rest of the script will execute without problems. Rookie mistake, I know, but I thought it’s worth sharing

Be Sociable, Share!

Some cool and little known PHP functions / features

  1. register_shutdown_function
    Recently I was building a PHP based load balancer for handling long running (video streams, sometimes up to 1 hour) processes. My biggest problem were if the user closed the page the load balancer had to react. This handy function is the best solution for the problem. Basically it calls the callback function when the script’s execution finishes or the user closes the browser window
  2. scandir
    If you are tired of using opendir, readdir and closedir, this function is for you
  3. glob
    Even better than scandir. It will only list the files matching the pattern passed in as an argument
    This is a fairly new feature of the curl library. You can specify a callback function which will be executed every time a chunk of data comes back from the remote host. Usually I’m using it to create progress bars for long running curl processes
  5. escapeshellcmd
    I’m dealing with loads of user generated files in many different languages. As you may know the golden rule: “Users are idiots” so they put spaces, quotes and many many random characters in the file names. escapeshellcmd is a really handy function to escape a command before you call exec
Be Sociable, Share!