home
on exploration, introspection and creation

Archive for September, 2010

The Pencil Curve

Sunday, September 26th, 2010

What is the shape of the curve traced by one tip of a pencil as you roll it up a cylinder (the pencil being tangent to the cylinder at all times)? The pencil starts just touching the cylinder. As the pencil moves closer to the cylinder, the tip first moves away, then quickly moves back, eventually to stop as the pencil becomes vertical.

Below is the diagram of the pencil’s start point, the end point, and an arbitrary point.



The pencil rolling on a cylinder. The tip tracing a curve is marked.

It’ll be easier to parameterize the curve: determine the coordinates of each point as a function of the distance of the bottom tip of the pencil to the bottom of the cylinder (where it is tangent with the table). Initially the pencil’s tip is just touching the cylinder and the distance t is equal to l, the length of the pencil. At the end, as the pencil is vertical, t=r, the radius of the cylinder.

We have, from the arbitrary point, \frac{y}{x+t}=tan 2\alpha = \frac{2tan \alpha}{1-tan^2\alpha} = \frac{2r/t}{1-r^2/t^2} = \frac{2rt}{t^2-r^2}.

\frac{x+t}{l}=\cos 2\alpha = 2\cos^2\alpha-1 = \frac{2t^2}{r^2+t^2}-1 = \frac{t^2-r^2}{t^2+r^2} so x = \frac{l(t^2-r^2)}{t^2+r^2}-t.
Similarly, y = \frac{2rt}{t^2-r^2}\cdot (x+t) = \frac{2rt}{t^2-r^2}\cdot\frac{l(t^2-r^2)}{t^2+r^2} = \frac{2rtl}{t^2+r^2}

We can plot the curve as a function of t:



Plotted pencil curve

Lifehack #31: Hot corners

Saturday, September 25th, 2010

If you have an operating system that allows you to assign functions to corners, take advantage of that feature. I use it to show my desktop, and to show all windows in one view.

The reason I prefer to use the mouse for the operation is that when I want to see my desktop or all windows I’m planning on using the mouse anyway (to open a file on the desktop, or to select the window I want). While using keyboard is in general faster, if you have to switch between the mouse and the keyboard you’ve lost that advantage anyway.

Interchanges

Wednesday, September 22nd, 2010

Here is my version of a stack interchange — a system of two highways intersecting such that cars coming from any direction can either go straight, turn right onto the intersecting highway, or turn left in the opposite direction of the intersecting highway (I didn’t allow U-turns so as not to complicate things too much).



My highway interchange: the red arrows show the paths that drivers going in a particular direction could take. Note that at most two lanes intersect at a point which makes it conceivable to build the interchange with two levels only; in the diagram the broken lane is below the other

And here is a slightly different version that doesn’t suffer from the problem of a center being too dense — if you look very carefully, you’ll see that in the version above, the centers of each of the arcs would meet unless the drop is not uniform.



Addressing the problem of a dense center

It seems to me that it can be built with two levels only — although something makes me think that it’s not that viable to build (since existing stack interchanges require four or more levels), plus to ensure a practical speed it would either have to have a rather large surface area, or only allow passenger cars driving with reduced speed. Here it is in three dimensions



My stack interchange in three dimensions



My stack interchange, zoomed in. The lane splits into three lanes and each separate lane takes you into one of the three directions.

You can download my Google SketchUp file here.

The structure of elevenseconds.com

Tuesday, September 21st, 2010

I tend to favor building to buying when I want to learn something, so when I first started constructing the main site elevenseconds.com I thought of building myself a small Rails-like framework. The main difference would be that it would apply to a simple principle of just-enough abstraction layers, that is, I would introduce a new abstraction layer when I left that the cost of maintaining the current code was too high. I am currently pretty happy with the structure of the site, although updating the front page takes a bit of time so perhaps it’s time to introduce a new layer of abstraction.

At a high level, all requests go to an index page

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.cgi [QSA,L]

which grabs the desired page to be visited from the URL as well as the subpage option (I thought it would be cool to separate the option with a colon — I never liked the questions marks and ampersands, and overloading slashes for paths and parameter separations never agreed with me. And so http://elevenseconds.com/photography/italy:slides takes you to an index page which knows to display a page called photography/italy with an option of slides.

Most of the pages are very similar so I put in place a kind of Metacontent-Metaview paradigm: every page request will fetch content from the /content/ directory. The ruby files there are organized in the same hierarchy as the URLs, so the above link will fetch content from /content/photography/italy.rb.

The actual content file is very configuration-like; let’s take a look at a part of the main content file (root URL resolves to /content/main.rb):


append = []
append << rendering('text', {
  'x'=>1,
  'y'=>0,
  'text'=>'<img src="/images/ui/whatis.png"/>11seconds: on exploration, introspection and creation'
})
append << rendering('verticalLine', {
  'x'=>1,
  'y'=>2,
  'size'=>3
})
append << rendering('imageWithCaptionOnRight', {
  'x'=>1,
  'y'=>2,
  'link'=>'http://blog.elevenseconds.com/trends/',
  'src'=>'/images/thumbs/main/glogo.png',
  'text'=>'trends'
})
append << rendering('imageOnRight', {
  'x'=>1,
  'y'=>11.5,
  'link'=>'/pictures/glowdoodle',
  'src'=>'/thumb.cgi?im=/images/pictures/glowdoodle/sadterminator.jpg&x1=197&y1=74&ss=344',
  'id'=>'projects',
  'text'=>'glow doodles'
})
render('main', {'append'=>append})

append is really a collection of items to append. Each item is a rendered view with some parameters. Each view is simply some HTML markup with Ruby inline code. For example, imageOnRight.rb contains

<div class="rightOfLine" style="left:#{x*35+2}px;top:#{y*35+69}px">
  <a href="#{link}">
    <img class="image" src="#{src}"
      onMouseOver='caption("#{id}", "#{text}", "#{link}")'
      onMouseOut='caption("#{id}", "", "")'/>
  </a>
</div>

(To make the page more structured, I decided on absolute positioning — maybe that’s because I’m a bit of a control freak.)

Note that I’m not quite allowing hierarchical content — there is no need for it given the current design of the site. All I need to do is a two-level hierarchy: a main view (the last line in the main.rb file above may include a bunch of other views.

I needed to introduce another abstraction because a lot of the sites with photography looked the same and I saw myself writing the same code over and over again. So I wrote a function that displays a generic set of pictures. Take our italy.rb content page:


category = 'photography/italy'
caption = 'italy june 2010'
images = [
  ['italy-0', true, '115, 45, 305'],
  ['italy-1', true, ''],
  ['italy-2', true, '296, 20, 54'],
  ...
  ['italy-45', true, '117, 75, 85'],
]
append = []
append << generateSeries(images, category, caption, [534, 356, 2.42])
render('main', {'append'=>append})

The above specifies the absolute minimum that is needed to render the Italy photographs — a definition of each images (I don’t always just number them in sequence), with a specification of whether the image is in landscape (true) or portrait (false) mode, and the top-left coordinate and the size of a window which will be made into a thumbnail. If not specified, the function chooses a smart default.


$explore = [
  ['http://www.gagneint.com/Final%20site/Animation/Sensology/Sensology.html', '/images/thumbs/main/sensology.png', 'sensology'],
  ['http://js1k.com/demos', '/images/thumbs/main/js1k.png', 'demos'],
  ...
]

I do the same with the front page — since it’s mostly made up of a bunch of links, I define each (in the example above, all I need for a link is a URL and a thumbnail picture) and then just cycle over the array. I only look at the latest 10 images for each category (except for EXPLORE which gets 20) but when you click on the link you get them all (http://elevenseconds.com/detail:explore) — again, code reuse.

As the content gets more streamlined (and as I get more lazy), I’ll probably go a step further towards configuration and just define everything in some standard configuration format like JSON (XML may be human-readable, but it’s certainly not human-writeable!). My goal is not quite to minimize the number of characters that I type (because then the conventions at play will no doubt be too obscure, plus the amount of plumbing code I’ll have to write too much for me to remember what I wrote in a year), but I’ll want to get close to it.

The thumbnails are also pretty painless. The utility page, thumb.cgi, generates a thumbnail out of any picture. You just need to specify the top-left coordinate and the size of the window to made into a thumbnail, and the resulting size. Most thumbnails on my page are 32×32 (it’s a kind of hallmark of the site). Some are 67×67 (not 64×64 because I want the images to line up — two 32×32 in a row actually take up ((1+32+1)+1+(1+32+1)) = 69 pixels because of the border and the one-pixel gap so to replace it with a bigger picture means it needs to be 67: (1+67+1)=69.

thumb.cgi saves the autogenerated thumbnails in a cache directory so that the images don’t have to be scaled each time the page is loaded. That is, when thumb.cgi is called with the same arguments again, it will just bring up the saved thumbnail instead of resizing and cropping the picture:


# by default output png unless the target size is specified
format = cgi.has_key?('sc') ? 'jpeg' : 'png'
hash = Digest::SHA1.hexdigest(ENV['REQUEST_URI'].to_s())[0..7]
cacheFile = "cache/" + hash + "." + format
if(File.exist?(cacheFile))
  puts cgi.header("image/#{format}")
  file = new File(cacheFile, "r")
  puts file.sysread(20)
  exit
end

But (great example of just-enough abstraction layers), I go even further: instead of having thumb.cgi do the logic, I replace the source of the image when rendering the view with its cached image. That way I don’t even have to call thumb.cgi which significantly speeds up the page load:


def gen2cache(html)
  source = html.clone
  links = []
  while(source =~ /"(\/thumb.cgi\?[^"]+)"/)
    links.push($1)
    source[$1] = ''
  end
  links.each { |link|
    format = link.index('sc=') ? 'jpeg' : 'png'
    hash = Digest::SHA1.hexdigest(link)[0..7]
    cacheFile = "cache/" + hash + "." + format
    if(File.exist?(cacheFile))
      html[link] = "/"+cacheFile
    end
  }
  return html
end

I guess the next step would be to actually autogenerate the entire HTML response.

Anyway, while Rails is certainly a much better solution to arrive at the final answer, I’ve learned a great deal about Ruby through this exercise. I doubt I’ll make the site much more complex than that.

A New Generation

Monday, September 20th, 2010

Think of an upscale restaurant, on a Saturday night. The diners are in their 50s, enjoying an expensive meal they’ve pretty much worked their life for — toiling away at some meaningless job before working their way through the ranks to positions of power and money. But now a new generation of people in their mid-20s begin to appear in their midst — granted, it’s a pretty rare sight still, but definitely a unique one. It’s not like these people inherited a lot of money from their parents so they can afford to drop $400 on a dinner. No, not at all: they work in finance.

On one hand this seems fairly strange. It’s tempting to talk about fairness and whether these people deserve to lead such an upscale life, but the situation is complicated by the fact that the value that someone adds (and therefore is rewarded for, so they can afford a fancy dinner) is a complex function of skills, abilities, experience, luck, personality, but also–let’s be honest–that value has never been proportional to the rewards. But the society is definitely not used to accepting young people in places that have for the longest time been a shrine for those who have been around for a while. You have the night clubs, let us have those fancy restaurants, one might say. For a long time, establishments seeking sophistication simply needed to make the means expensive: sophistication (which was correlated with age) happened to very often be also correlated with wealth.

On the other hand it’s still to purport to know how the society changes and whether a change is not taking place as we speak. Yes, while the correlation of wealth and age filled restaurants with well-behaved people in their 50s, this has not always been the case — just a couple of centuries ago the same restaurants would be filled with people of all ages, but of a single class, which seems to me to be a better predictor of the kind of atmosphere fancy restaurants may seek. So to those people, the switch from class to just wealth (no matter how you made the money) may seem just as preposterous as the presence of the 20-odd-year-olds in fancy restaurants.

The salient point here is that if it indeed is a shift, what are these 20-odd-year-olds going to be doing when they are in their 50s?

One of my Favorite Proofs

Sunday, September 19th, 2010

Proof that \pi is irrational.

Assume \pi is rational, that is, assume it is of the form \frac{a}{b} where a and b are both positive integers. Let

f(x) = \frac{x^n (a-bx)^n}{n!}

F(x) = f(x) + \cdots + (-1)^j f^{[2j]}(x) + \cdots + (-1)^n f^{[2n]}(x)

where f^{[k]} denotes k-th derivative of f.

  1. f(x) has integer coefficients except \frac{1}{n!}
  2. f(x) = f(\pi - x)
  3. 0 \leq f(x) \leq \frac{\pi^n a^n}{n!} for 0 \leq x \leq \pi
  4. For 0 \leq j < n, the j-th derivative of f equals 0 at 0 and \pi
  5. For j \geq n, the j-th derivative of f is integer at 0 and \pi (from 1. above)
  6. F(0), F(\pi) is integer (from 4., 5. above)
  7. F(x) + F''(x) = f(x)
  8. (F'(x) \sin x - F(x) \cos x)' = f(x) \sin x (from 7. above)
  9.  \int_0^\pi f(x) \sin x is an integer
  10. For large n, this integral is between 0 and 1 (from 3. above)

Contradiction. So \pi is irrational.

Animated Shows

Sunday, September 19th, 2010

When I was growing up, we had two TV channels, programming started at 6pm and ended at 11pm. At 7pm all kids would sit in front of the TVs and watch a great animated TV show. Sundays were the best — animated shows imported from abroad (mostly the U.S.), with voiceover and everything!

The Moomins


[source]

The Moomins

They haven’t really been popular here much, but I have some very warm memories of watching the Moomins. The show is really serene, soft, and a little creepy.

Rescue Rangers


[source]

Rescue Rangers

My favorite TV show tune of all times. And, quite frankly, I kind of wanted to be Chip (that was before Teenage Mutant Ninja Turtles, I guess).

Gummi Bears



[source]

Gummi Bears

I liked this show primarily because there was a whole colony of “Other” Gummi Bears that was across the sea that the Gummi Bears desperately tried to find. No matter how close they got, they could never actually find the others. I liked the mystery of it.

Come to think of it, I guess I also liked the fact that those seemingly quite normal bears acquired superpowers after they drank the mystery potion.

The Smurfs



The Smurfs

I used to like the Smurfs because they were a rather original idea; I’m not sure anybody expected blue creatures with white hats to be so successful. However, the show was a little too predictable; the characters were too stereotypical (one is always clumsy, the other is always depressed, etc.). I abandoned the Smurfs in favor of Gummi Bears.

Duck Tales



[source]

Duck Tales

Another great show tune.

Disney did a great job casting their shows with characters — first, the choice of an animal was just brilliant: ducks are toony, their faces are expressive (and the beaks are funny), and the great sounds they make when under stress come for free. But also the decision to base the show on three brothers and their uncle, a stingy millionaire modeled on Scrooge, is original, clever (the fact that it’s their uncle and not their dad gives them more freedom to go on their crazy adventures (which are also made possibly by their uncle’s wealth) and make fun of him occasionally (and point out why it’s bad to be greedy).

Darkwing Duck



[source]

Darkwing Duck

I haven’t really watched it much, but I really liked the imagery — the protagonist, a duck in a cape, dressed in purple. There was a video game based on the show that I would play religiously.

Branding, part II

Sunday, September 19th, 2010

Words have a lifecycle; hey are born and they die. They die for many reasons; some die naturally (get out of fashion). Others die more untimely death (for example, they suddenly acquire a negative connotation). There are also words that get perceived as politically incorrect — they are on life support because there is still a large group of people who use them, if just to spite everyone else.

This is a good thing. Language is a strange combination of social conventions and explicit structure, and it’s dynamic to reflect the changing needs and thoughts of the society. A language that wouldn’t be allowed to change would be dead. I’m glad unfriend is now a word.

It’s interesting to note that the half-life of phrases seems to have decreased over the past fifty years or so — we get tired of words more quickly, perhaps because as consumers, we’re not satiated and are looking for the next big thing faster and faster. We react to words, and a new word can make us switch from one product to a different one. Inexpensive becomes economical and we suddenly stop thinking of ourselves as cheapos and instead pat ourselves on the back for not wasting money.

Branding is also one way to keep up with class inflation. We don’t want to be gardeners, stewardesses or waitresses. We want to be landscapists, flight attendants, and servers (although the latter seems to me — and to many waitresses — as a step back). A different word — borrowed from what used to be a slightly different role — changes our perception enough to trick the same minds of ours that make us think that it’s somehow less glamorous than it once was to have such a profession.

However, this can also be used as a political tool, to cover up issues or make them seem less like issues. Why do we need to rebrand dwarf to vertically challenged? Is it because it makes us appear to do something about the issue? Or are we ashamed of the fact that the characteristic has found its way into popular culture as a signifier, just like retarded has?

Life Hack #30: VPN

Sunday, September 19th, 2010

Use VPN if you’re abroad and your favorite movie or TV show streaming service is using some legal excuse to prevent you from catching up on that episode of Lost where they explain everything. (I used to do that back when Skype had free calling anywhere within the U.S.)

You can search for personal VPN services with servers located in the U.S. — I am not in the business of endorsing other services unless they are, like, the best thing since sliced bread — there are even some free ones.

Free parking?

Sunday, September 19th, 2010

I’ve used these parking garages that have a ticket machine by the entrance quite a lot. You pull up, get the ticket, drive in, and on exit you pay for how long you stayed in the parking garage. Usually the garages have a grace period of about 5 minutes.

What prevents me from pulling up to one of these ticket machines, grabbing a ticket, and then driving away instead of in? If nothing, I can enter with one car, with another car just get the ticket, and then use the second ticket to get your first car out. Both cars are out of the parking garage and you paid nothing.