Flaviu Simihaian's Blog - Entrepreneur and Developer

How to Write a Multi-line NSString in Objective-C

Say you have some HTML you need to cram into a WebView in iOS. You can create a .html file but then you can’t pass variables from your code.

So, you try inlining it. Except you find out that Objective-C does not have like a triple quote or some other multi-line escaping.

You need to end every line with a backslash. So, this code:

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
  <head>
    <title>U.S. Population</title>
    <script type="text/javascript" src="../../d3.v2.js"></script>
    <link type="text/css" rel="stylesheet" href="population.css"/>
  </head>
  <body>
    <div id="chart"></div>
    <script type="text/javascript" src="population.js"></script>
  </body>
</html>

needs to become this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@" \
<!DOCTYPE html> \
<html> \
<head> \
<title>U.S. Population</title> \
<script type=\"text/javascript\" src=\"d3.v2.min.js\"></script> \
<link type=\"text/css\" rel=\"stylesheet\" href=\"population.css\"/> \
</head> \
<body> \
<div id=\"chart\"></div> \
<script type=\"text/javascript\" src=\"population.js\"></script> \
</body> \
</html> \
"

You don’t want to do that manually. So I made a little tool that converts one to the other. Check it out at MultiLineObjC.herokuapp.com.

Hope this saves you some time.

Architecture Saturday Part 5: Neoclassical

Sometime in the 18th century, architects reacted against the Rococo (previous blog post) and turned towards the classic Greek and Roman styles with a touch of Renaissance (Andrea Palladio).

Andrea Palladio is the most influential architect ever, with an architects fanclub started long after his death called “The Palladians.”

Actually, one could say that the official architecture style of the United States is “Andrea Palladio”. Thomas Jefferson got a crush on it when he was an ambassador in France. Snobs call it “Classicism.”

Here’s Palladio’s “Villa Rotunda”:

Here’s Jefferson’s home (Monticello) near Charlottesville, VA, which he architected:

Jefferson also designed University of Virginia’s Library after the Roman Pantheon:

Hell, even the White House, Lincoln Memorial, and the Capitol were greatly influenced by Andrea Palladio (not to mention every upscale neighborhood).

Neoclassical also made some advances in garden design, from the stodgy, perfect-looking Versailles garden, to the English Garden designed by Charles Bridgeman:

Bridgeman invented the “ha-ha” which, besides being the coolest Architectural term ever, serves as a trench that you do not notice from a distance, but that keeps neighbors’ animals from wandering in your really expensive garden:

The Neoclassical era was also a time of Napoleonic grandeur and aspirations of taking over the world. No wonder Etienne Louis Boulle designed this thing:

St. Pancras in London even made caryatids as columns coppying the Caryatid Porch of the Erechtheion on the Acropolis at Athens:

Of course, no one really knows what purpose these maidens served in the original architecture. But they look cool.

The Germans stepped up their game during the Neoclassical period by building things such as the Brandenburg Gate in Berlin, built originally as a sign of peace, but came in handy during Berlin’s devided political struggles:

Karl Friedrich Shinkel designed the gate and many other museums in Berlin that look like the Parthenon.

Perhaps the most innovation in the Neoclassical period came from Russia, where Catherine the Great began the Hermitage as her personal art collection:

Despite “hosting” Napoleon in Moscow for a little while, the Russian elite spoke French and their imperial architecture was greatly influenced by the French gentleness:

The Value of a College Education

A few weeks ago 60 minutes did a segment on Peter Thiel, the Paypal/Facebook billionaire that gives $100,000 to kids under 20 to quit college and build startups.

Thiel, I should mention, is a graduate of Stanford Undergrad and Stanford Law School.

Glenn Beck, the eternally hallucinating talk show host, provides a simple solution for the $1 trillion of student debt in this country: Kids who can’t afford college shouldn’t go. Instead, they should “go to the free public library.” He gives himself as an example.

Also, student loans are a big presidential campaign issue that, oddly enough, the two candidates agree on a solution to: “we must do something to lower the cost of going to college.”

Meanwhile, NPR publishes the infogram below showing that the Net Cost of College (sticker price - grants and scholarships) has remained more or less the same over the years.

Ok, I get it. The cost of college is what we’re willing to pay for it. As long as people pay $62k to go to Harvard, Harvard will keep increasing its tuition. Basic Supply & Demand.

But what about Peter Thiel’s claim that education is a bubble and we are greatly overestimating the value of a college degree?

I know several people in their 60s that had a successful career without a college degree. Yet they all wished they had gone to college.

Take T. Banks, a friend who worked for BellSouth his entire life. He is a stellar electrician and had security clearance to work in the White House. However, when he is around “people with college degrees”, he feels inferior, and refuses to voice his opinions on anything, as though they were somehow less valuable that his Bachelors-holding friends’.

My point is that going to college is a decision that will haunt you for the rest of your life.

It’s not just a certificate or a piece of paper in order to get a job. For many, college provides the confidence and social skills to succeed in building relationships with others and pursue success in any profession.

While college may not have been greatly beenficial to Bill Gates and Mark Zuckerberg, think twice before you recommend that no one should go to college.

It’s often the ones who have gone to college (like Peter Thiel) or that were accepted in the top institutions and left to pursue their dreams (like Bill Gates or Mark Zuckerberg) that inspire kids to skip college.

The vast majority of 18-year-olds are not like Peter Thiel, Bill Gates, nor Mark Zuckerberg. They have much more in common with T. Banks.

Architecture Saturday Part IV: Asia

Everyone is special. The Mayans were the only literate people in Mesoamerica. They had the wheel, but did not use it to pull stuff. Instead, they literally broke their backs building this:

The Chinese had access to stone and the ability to build arches. However, they chose to use timber and perfect the carpenter’s art (part of the reason why “The Great Plains” are not “The Great Forest”).

Interestingly, they invented the Modular System, which specifies exactly how to space columns in Chinese Architecture.

Mean time, the Dalai Lama was chilling in this little home:

I think it’s really interesting the Japan shuts itself in for a century, and comes out with Noh Theatre (which is not related to NoSQL) and some of the most pristine architecture of all time. Meet the Himeji Castle:

It’s easy to judge China for their lukewarm support of human rights. It’s much harder to understand the isolationism and culture their beliefs are grounded in. However, architecture can provide a bathroom window into their collective psyche.

For instance, while the Romans protected their empire by building a top-knotch army and patrolling distant lands, China surrounded its empire with a wall you can see from space:

The good news is while we all have our bad apples, most people are like the Fonzie. Cool.

Take the Indian emperor Shah Jahan, who built the Taj Mahal in the memory of his dead wife:

I’ll end this spiritual blog post with a quote by Ashoka the Great:

It is forbidden to descry other sects; the true believer gives honor to
whatever in them is worthy of honor.

Create New Records With Bootstrap Modal and Rails Unobtrusive Javascript

I wanted the quickest way to get a nice looking modal popover, in which to create a new record, and after the modal dismisses, the new record to show up. All without the page refreshing.

And let’s throw in validations in the modal as well.

Say you have a simple model (Post) with some fields.

1
2
3
rails new flapp
cd flapp
rails g scaffold Post title content

Add client_side_validations to take care of validations for us (only gem we’re going to use, I promise…except haml-rails so you can actually read HTML)

Gemfile
1
gem 'client_side_validations'

Run the install generator for client_side_validations

1
rails g client_side_validations:install

Add the rails.validations.js to your layout

app/assets/javascripts/application.js
1
//= require rails.validations

Now, we need to download Bootstrap. I recommend customizing it with the cool things you want on this page. If that fails, the minified full version is only 48k. Make sure you copy the javascripts, css, and images into your assets directory accordingly.

We’ll just edit ‘app/views/posts/index.html.haml’ for this example so that it’s all in one file. However, it’s good practice to render each modal in a different file.

Change your ‘Add Post’ button to this:

posts/index.html.haml
1
%a{'href' => '#new-post-modal', 'data-toggle' => 'modal'}

The data-toggle tells Bootstrap this link toggles the modal. The href tells it the ID of the modal element it toggles.

Here’s our modal:

app/views/posts/index.html.haml
1
2
3
4
5
6
7
8
9
10
11
12
#new-post-modal{'class' => 'modal hide fade'}
  = form_for(Post.new, validate: true, remote: true, html: {"data-type" => :json}) do |f|
    %ul.errors
      %li
    .field
      = f.label :title
      = f.text_field :title
    .field
      = f.label :content
      = f.text_field :content
    .actions
      = f.submit 'Save'

The validate: true makes sure we use the client_side_validations we added earlier. remote: true tells it to use Rails’ Unobtrusive Javascript.

The html: {"data-type" => :json}) specifies that we want the controller to return JSON back to the view.

The classes (modal, hide, fade) declare it as a modal that is hidden at first, and then fades in.

With the latest Rails, we don’t need to change anything in the controller. Here’s what my create action looks like:

app/controllers/posts_controller.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
def create
  @post = Post.new(params[:post])

  respond_to do |format|
    if @post.save
      format.html { redirect_to @post, notice: 'Post was successfully created.' }
      format.json { render json: @post, status: :created, location: @post }
    else
      format.html { render action: "new" }
      format.json { render json: @post.errors, status: :unprocessable_entity }
    end
  end
end

The only thing we need to do is to make sure we are listening for when the JSON comes back, so that we can dismiss the modal, and show the new data.

app/assets/javascripts/posts.js.coffee
1
2
3
4
$ ()->
  $("form.new_post").on "ajax:success", (event, data, status, xhr) ->
    $('#new-post-modal').modal('hide')
    $('table tbody').append('<tr><td>' + data.title + '</td><td>' + data.content + '</td></tr>')

In the case above, we dismiss the modal and then insert a new row in a table with the title and content of the post we just added.

I tried to keep this as simple as possible. Hope it helps.

Architecture Saturday Part III: Renaissance

  • 1425 - The dude above (Filippo Brunelleschi) discovers perspective drawing
  • 1450 - Gutenberg invents movable type
  • 2010 - Adobe releases Illustrator CS5 with the Perspective Grid

Two of the events above made the Renaissance possible.

Renaissance is when architects changed from unnoticed hardworking ants to egomaniacs like Howard Roark. Why? Because they realized man is at the center of everything (see DaVinci’s Vitruvian Man below), especially the interpretation of the divine.

Pope Julius II really liked art, so he kept Bramante, Raphael, Michelangelo, and others on the payroll. Michelangelo never got to see his St. Peter Cathedral built.

None of DaVinci’s plans ever got built before or after he died. I guess it could be worse.

Interesting fact is that this guy named Andrea Palladio is the most copied architect ever. He started making villas, expensive homes for rich people to chill in for the summer. Now, pretty much every upscale neighborhood in the U.S., England, or Russia mirrors his designs.

"Thomas's Jefferson's Monticello"

"Andrea Palladio's Volla Rotunda"

Then came Baroque, which tried get away from all straight lines. Architects started using cinema (Quentin Tarantino?) for their inspiration. I mean, look at this:

"Borromini's Church of San Carlo alle Quattro Fontane"

So, naturally, the Germans and French thought it was a race towards decadence, so Louis XIV (Insane) built Versailles and even coined the word Rococo at his court. It basically means “tons of gilded plaster and mirrors.”

"Munich's Catholic Church of St. Johann Nepomuk"

That’s it for this week. Hope you enjoyed it.

iOS Chart and Plotting Library Comparison

tl;dr:

Use core-plot, roll your own CoreGraphics implementation, or use a WebView with a JavaScript plotting library, such as Highcharts or FusionCharts

I needed to chart some data for an iPad app. Here’s some options I’ve found in my research:

I looked on StackOverflow but there was no clear winner: http://stackoverflow.com/questions/7254882/line-graphs-on-ios

Some suggest writing your own with CoreGraphics; some mention ShinobiControls (see screenshot above), which costs like $1,000 and that was a deterrent for me trying it. EDIT: They do seem on top of their customer support though. ;) http://www.shinobicontrols.com/shinobicharts/price-plans/

Core Plot

This is what most people suggest. It does apparently anything you want. But it’s on Google Code and the documentation is awful.

http://code.google.com/p/core-plot/

Unofficial Github Mirror: https://github.com/djw/core-plot

Sencha

If you’re not doing native work, I should mention Sencha has some pretty nice looking stuff: http://dev.sencha.com/deploy/touch-charts-1.0.0/examples/

However, I am only building native apps, so it doesn’t help me that much.

Lameness

Then there’s tons of lame sites last updated in 2010 that you should stay away from: http://www.keepedge.com/products/iphone_charting/ http://www.iphonechart.com/company/

JavaScript

I ended up using a JavaScript framework instead and build a WebView locally using that library. It’s worked out pretty well:

I used FusionCharts, but I’ve also used Highcharts before and liked it even more. However, FusionCharts has a nice tutorial for how to embed it inside an iOS app.

Or you could use Google Charts.

That ended up working great for the quick nice chart I needed. Hope this helps you. If you’ve used other tools, please let me know by commenting below.

Architecture Saturday Part II : Gothic

Goethe once said: “Architecture is frozen music.” Of course, being a writer, he knew little about either.

This is the second (and maybe last) post in my Architecture Saturday series. Go read the first here.

Here’s the architecture words of the day:

boss : Ornamental knob found at the intersection of ribs in a ceiling vault.

fornication : refers to curved roof coverings and arches (fornix)

In the High Middle Ages, Europe managed to get some temporary peace and started building large, high, ornate cathedrals, such as the one in Ulm, Germany (below).

But what makes a building gothic?

Flying Buttresses. A buttress is a structure built against a wall to serve as support and take off some pressure. Remember this was before steel, so building tall thngs required a linearly larger support.

But a flying buttress (depicted in the top image of this post) is different because it is not in contact with the wall all the way to the ground; so that the lateral forces are transmitted across an intervening space.

Tracery. That’s the complicated stonework that allows those ridiculously large windows to not break and stay in place. Example below.

Interesting fact, the Doge’s Palace in Venice (picture below) is also a gothic building. Probably the most photographed one.

Notice that little dome at the top, the one that looks like the top of a mosque? Don’t tell anyone about it!!!

Speaking of Islamophobia, the Seville Cathedral is about the size of two football fields. I mean, the nave is flanked by 2 isles and the stair to the tower was designed for people riding horses. Why? Because there was a huge mosque there before and they wanted to erase all traces of it.

Meanwhile, in England (where news of the Renaissance arrived a couple of hundred years late) they were building awesome stuff with wood. Like timber, man.

They have these hammer-beam roofs, decorated with angels holding shields. The reason they’re remarkable is that instead of using the full beams, they would use these shorter ones (see below) and build further structure on top of them.

Building with wood was typically a bad idea though because their buildings would burn down all the time.

That’s all for this Saturday.

Deploying Flask With Nginx

The Flask docs for this take you 80% of the way there.

Basically, we need uWSGI to create a UNIX socket, which nginx can route requests to as they come in.

First, let’s make sure uWSGI runs independent of nginx.

The docs tell us to write this:

1
uwsgi -s /tmp/uwsgi.sock -w myapp:app

There’s two problems with this:

First, you may get some error that it doesn’t find flask if you are using a virtual environment (which you should).

Second, nginx may not be able to read the file later if the permissions don’t let it.

So I had to adapt it to this:

1
uwsgi -s /tmp/uwsgi.sock -w flask_file_name:app -H /path/to/virtual/env --chmod-socket=666

Now, install nginx with apt-get install nginx. Change the /etc/nginx/sites-available/default to read:

1
2
3
4
5
6
7
8
9
server {
    listen       80;
    server_name  _;
    location / { try_files $uri @yourapplication; }
    location @yourapplication {
      include uwsgi_params;
      uwsgi_pass unix:/tmp/uwsgi.sock;
    }
}

Now symlink the file above to the enabled one, because that’s how nginx works:

1
ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/default

Start nginx with ‘/etc/init.d/nginx restart’

Go to a browser and try it out. Yay!

But what if you want to restart the server? nginx will restart, but your uWSGI will not. We’ll use supervisord for that.

1
apt-get install supervisor

We need to set up the /etc/supervisord.conf to tell supervisor what to do:

Now, kill your supervisor, start it again, and your Flask app be running ad infinitum.

1
2
3
ps -A | grep supervisor
kill <id>
sudo supervisord -c /etc/supervisord.conf

Here’s another supervisor sample config file to get you inspired.

Hope this helps.

Fork Flaviu on GitHub