You are on page 1of 40

How Airplanes Fly

Issue 21 February 2012


Curator Hacker Monthly is the print magazine version
Lim Cheng Soon of Hacker News — news.ycombinator.com, a social news
website wildly popular among programmers and startup
Contributors founders. The submission guidelines state that content
David Anderson can be “anything that gratifies one’s intellectual curiosity.”
Scott Eberhardt Every month, we select from the top voted articles on
Peiter Buick Hacker News and print them in magazine format.
Pat Shaughnessy For more, visit hackermonthly.com.
Nick Johnson
Ian Ward
Brandon Mintern
Timothy Daly
Advertising Published by
James Tauber
ads@hackermonthly.com Netizens Media
Lisa Zhang
46, Taylor Road,
11600 Penang,
Proofreaders
Contact Malaysia.
Emily Griffin
contact@hackermonthly.com
Sigmarie Soto

Printer
MagCloud

Cover Photography: Dave Morrow’s Custom Creations

Hacker Monthly is published by Netizens Media and not affiliated with Y Combinator in any way.

2  
Contents
FEATURES

04  How Airplanes Fly


By David Anderson and Scott Eberhardt

DESIGN

  The Messy Art of UX Sketching


14
By Peiter Buick

PROGRAMMING

20  Never Create Ruby Strings Longer


Than 23 Characters
By Pat Shaughnessy

  Fountain Codes
24
By Nick JohnSon

  Unfortunate Python
27
By Ian Ward

  Tips for Remote Unix Work


30
By Brandon Mintern

  Being a Great Coder


34
By Timothy Daly

SPECIAL

  Why 13th Chords


36
By JAMES TAUBER

  Elevator Algorithms
38
By Lisa Zhang

For links to Hacker News dicussions, visit hackermonthly.com/issue-21

 3
FEATURES

How Airplanes Fly


A Physical Description of Lift

By David Anderson & Scott Eberhardt

A
Photo: Black & White Bi-Plane, flickr.com/photos/daves-f-stop/5516483143

lmost everyone cover for this paradox we some- same distance over the top and
today has flown times see a description for inverted the bottom of the wing. Yet this
in an airplane. flight that is different than for airplane flew and was the second
Many ask the normal flight. In reality the shape of airplane purchased by the US Army
simple question “what makes an the wing has little to do with how in 1911.
airplane fly?” The answer one fre- lift is generated and everything to The second example of a wing
quently gets is misleading and often do with efficiency in cruise and stall that violates the idea that lift is
just plain wrong. As an example, characteristics. Any description that dependent on the shape of the wing
most descriptions of the physics relies on the shape of the wing is is of a very modern wing. Figure
of lift fixate on the shape of the wrong. 2 shows the profile of the Whit-
wing (i.e. airfoil) as the key factor Let us look at two examples comb Supercritical Airfoil (NASA/
in understanding lift. The wings in of successful wings that clearly Langley SC(2)-0714). This wing
these descriptions have a bulge on violate the descriptions that rely is basically flat on top with the
the top so that the air must travel on the shape of the wing. The curvature on the bottom. Though
farther over the top than under the first example is a very old design. its shape may seem contrary to the
wing. Yet we all know that wings fly Figure 1 shows a photograph of popular view of the shape of wings,
quite well upside down where the the Curtis 1911 model D type IV this airfoil is the foundation of the
shape of the wing is inverted. To pusher. Clearly the air travels the wings modern airliners.

4  FEATURES
The Bernoulli equation is a As an example, an object sitting
statement of the conservation on a table exerts a force on the
of energy. It is correct, but table (its weight) and the table puts
not applicable to the descrip- an equal and opposite force on the
tion of lift on a real wing. The object to hold it up. In order to gen-
wings of an 800,000 pound erate lift a wing must do something
airplane are doing a great to the air. What the wing does to
deal of work to keep the the air is the action while lift is the
Figure 1. Curtis 1911 model D type IV pusher airplane in the air. They are reaction.
adding a large amount of energy Let’s compare two figures used
to the air. One of the requirements to show streamlines over a wing.
of the application of the Bernoulli In figure 4 the air comes straight at
principle is that no energy is added the wing, bends around it, and then
Figure 2. Whitcomb Supercritical Airfoil
to the system. Thus, the speed and leaves straight behind the wing. We
The emphasis on the wing shape pressure of the air above a real wing have all seen similar pictures, even
in many explanations of lift is based in flight are not related by the Ber- in flight manuals. But, the air leaves
on the Principle of Equal Transit noulli principle. Also, descriptions the wing exactly as it appeared
Times. This assertion mistakenly of lift that evoke the Bernoulli prin- ahead of the wing. There is no net
states the air going around a wing ciple depend on the shape of the action on the air so there can be no
must take the same length of time, wing. As already stated, the shape lift! Figure 5 shows the streamlines,
whether going over or under, to get of the wing affects the efficiency as they should be drawn. The air
to the trailing edge. The argument and stall characteristics of the wing passes over the wing and is bent
goes that since the air goes farther but not the lift. That is left to the down. Newton’s first law says that
over the top of the wing it has to go angle of attack and speed. there must be a force on the air to
faster, and with Bernoulli’s principle bend it down (the action). New-
we have lift. Knowing that equal Newton’s laws and lift ton’s third law says that there must
transit times is not defendable the So, how does a wing generate lift? be an equal and opposite force
statement is often softened to say To begin to understand lift we must (up) on the wing (the reaction). To
that since the air going over the top review Newton’s first and third generate lift a wing must divert lots
must go farther it must to faster. laws. (We will introduce Newton’s of air down.
But, this is again just a variation second law a little later.) Newton’s
on the idea of equal transit times. first law states:
In reality, equal transit times holds
A body at rest will remain at rest,
only for a wing without lift. Figure
or a body in motion will continue
3 shows a simulation of the airflow Figure 4. Common depiction of airflow
in straight-line motion unless sub-
around a wing with lift. over a wing. This wing has no lift.
jected to an external applied force.
That means, if one sees a
bend in the flow of air, or if
air originally at rest is acceler-
ated into motion, a force is
acting on it.
Newton’s third law states Figure 5. True airflow over a wing with
that: lift showing upwash and downwash.
Figure 3 Air over a wing with lift.
For every action there is an equal
and opposite reaction.

 5
The lift of a wing is equal to the
change in momentum of the air it
is diverting down. Momentum is
the product of mass and velocity
(mv). The most common form of
Newton’s second law is F= ma, or
force equal mass times acceleration.
The law in this form gives the force
necessary to accelerate an object of
Figure 6. How downwash appears to a pilot and to an observer on the ground.
a certain mass. An alternate form
of Newton’s second law can be
As stated, an observer on the Diverting so much air down
written:
ground would see the air going is a strong argument against lift
The lift of a wing is proportional to almost straight down behind the being just a surface effect (that is
the amount of air diverted down plane. This can be demonstrated only a small amount of air around
times the vertical velocity of that by observing the tight column of the wing accounts for the lift), as
air. air behind a propeller, a household implied by the popular explana-
fan, or under the rotors of a heli- tion. In fact, in order to divert 5
It is that simple. For more lift
copter; all of which are rotating ton/sec the wing of the Cessna 172
the wing can either divert more air
wings. If the air were coming off must accelerate all of the air within
(mass), increase its vertical veloc-
the blades at an angle the air would 18 feet (7.3 m) above the wing.
ity or a combination of the two.
produce a cone rather than a tight One should remember that the
This vertical velocity behind the
column. The wing develops lift by density of air at sea level is about
wing is the vertical component of
transferring momentum to the air. 2 lb per cubic yard (about 1kg per
the “downwash.” Figure 6 shows
For straight and level flight this cubic meter). Figure 7 illustrates
how the downwash appears to the
momentum eventually strikes the the effect of the air being diverted
pilot (or in a wind tunnel). The
earth. If an airplane were to fly over down from a wing. A huge hole is
figure also shows how the down-
a very large scale, the scale would punched through the fog by the
wash appears to an observer on
weigh the airplane. downwash from the airplane that
the ground watching the wing go
Let us do a back-of-the-envelope has just flown over it.
by. To the pilot the air is coming
calculation to see how much air
off the wing at roughly the angle Figure 7.
a wing might divert. Take for Downwash and
of attack and at about the speed
example a Cessna 172 that weighs wing vortices in
of the airplane. To the observer
about 2300 lb (1045 kg). Traveling the fog.
on the ground, if he or she could
at a speed of 140 mph (220 km/h),
see the air, it would be coming
and assuming an effective angle of
off the wing almost vertically at a
attack of 5 degrees, we get a vertical
relatively slow speed. The greater
velocity for the air of about 11.5
the angle of attack of the wing the
mph (18 km/h) right at the wing. If So how does a thin wing divert
greater the vertical velocity of the
we assume that the average vertical so much air? When the air is bent
air. Likewise, for a given angle of
velocity of the air diverted is half around the top of the wing, it pulls
attack, the greater the speed of the
that value we calculate from New- on the air above it accelerating that
wing the greater the vertical veloc-
ton’s second law that the amount air downward. Otherwise there
ity of the air. Both the increase in
of air diverted is on the order of 5 would be voids in the air above
the speed and the increase of the
ton/s. Thus, a Cessna 172 at cruise the wing. Air is pulled from above.
angle of attack increase the length
is diverting about five times its own This pulling causes the pressure to
of the vertical velocity arrow. It is
weight in air per second to produce become lower above the wing. It
this vertical velocity that gives the
lift. Think how much air is diverted is the acceleration of the air above
wing lift.
by a 250-ton Boeing 777. the wing in the downward direction

6  FEATURES
that gives lift. (Why the wing bends This air must be compensated for, so From Newton’s third law we
the air with enough force to gener- the air shifts around the wing to fill know that there must be an equal
ate lift will be discussed in the next in. This is similar to the circulation and opposite force acting on the
section.) of the water around a canoe paddle. glass. The stream of water puts a
Normally, one looks at the air This circulation around the wing is force on the glass that tries to pull
flowing over the wing in the frame no more the driving force for the it into the stream, not push it away
of reference of the wing. In other lift on the wing than is the circula- as one might first expect.
words, to the pilot the air is moving tion in the water drives the paddle. Figure 9. Water
and the wing is standing still. We Though, it is true that if one is able wrapping around
have already stated that an observer to determine the circulation around a glass
on the ground would see the air a wing the lift of the wing can be
coming off the wing almost verti- calculated. Lift and circulation are
cally. But what is the air doing proportional to each other.
below the wing? Figure 8 shows One observation that can be
an instantaneous snapshot of how made from Figure 8 is that the top
air molecules are moving as a wing surface of the wing does much So why does the water bend
passes by. Remember in this figure more to move the air than the around the glass, or air over a wing?
the air is initially at rest and it is bottom. So the top is the more criti- First consider low-speed flight. In
the wing moving. Arrow “1” will cal surface. Thus, airplanes can carry low-speed flight the forces on the
become arrow “2” and so on. Ahead external stores, such as drop tanks, air and the associated pressures
of the leading edge, air is moving under the wings but not on top are so low that the air is not only
up (upwash). At the trailing edge, where they would interfere with considered a fluid but an incom-
air is diverted down (downwash). lift. That is also why wing struts pressible fluid. This means that the
Over the top the air is accelerated under the wing are common but volume of a mass of air remains
towards the trailing edge. Under- struts on the top of the wing have constant and that flows of air do
neath, the air is accelerated forward been historically rare. A strut, or any not separate from each other to
slightly. Far behind the wing the air obstruction, on the top of the wing form voids (gaps).
is going straight down. would interfere with the lift. A second point to understand is
that streamlines communicate with
Air Bending Over a Wing each other. A streamline, in steady-
As always, simple statements often state flight, can be looked at as the
result in more questions. One path of a particle in the moving air.
natural question is why does the air It is the path a small, light object
Figure 8. Direction of air movement bend around the wing? This ques- would take in the airflow over the
around a wing as seen by an observer on tion is probably the most challeng- wing. The communication between
the ground. ing question in understanding flight streamlines is an expression of pres-
and it is one of the key concepts. sure and viscosity. Pressure is the
So, why does the air follow this Let us start by first looking at a force per area that the air exerts on
pattern? First, we have to bear simple demonstration. Run a small the neighboring streamline. Viscos-
in mind that air is considered an stream of water from a faucet and ity in a gas or liquid corresponds to
incompressible fluid for low-speed bring a horizontal water glass over friction between solids.
flight. That means that it cannot to it until it just touches the water, Think of two adjacent stream-
change its volume and that there is a as in Figure 9. As in the figure, the lines with different speeds. Since
resistance to the formation of voids. water will wrap partway around the these streamlines have different
Now the air has been accelerated glass. From Newton’s first law we velocities forces between them
over the top of the wing by of the know that for the flow of water to trying to speed up the slower
reduction in pressure. This draws air bend there must be a force on it. streamline and slow down the faster
from in front of the wing and expels The force is in the direction of the streamline. The speed of air at the
if back and down behind the wing. bend. surface of the wing is exactly zero

 7
with respect to the surface of the Two streamlines communicate but in the opposite direction. These
wing. This is an expression of vis- on a molecular scale. This is an forces, working through pressure,
cosity. The speed of the air increases expression of the pressure and the represent the mechanism in which
with distance from the wing as viscosity of air. Without viscosity the force is transferred to the wing.
shown in Figure 10. Now imagine there would be no communica-
the first non-zero velocity stream- tion between streamlines and no
line that just grazes the highpoint boundary layer. Often, calculations
of the top of the wing. If it were of lift are made in the limit of zero
initially to go straight back and not viscosity. In these cases viscosity is
follow the wing, there would be a re-introduced implicitly with the
volume of zero velocity air between Kutta-Joukowski condition, which
it and the wing. Forces would strip requires that the air come smoothly Figure 11. Forces on the air and the cor-
this air away from the wing and off at the trailing edge of the wing. responding reaction forces on the wing
without a streamline to replace it, Also, the calculations require that
the pressure would lower. This low- the air follows the surface of the Look again at Figure 11, while
ering of the pressure would bend wing which is another introduc- paying attention to the black arrows
the streamline until it followed the tion of the effects of viscosity. One representing the forces on the wing.
surface of the wing. result of the near elimination of There are two points to notice.
viscosity from the calculations is The first is that most of the lift is
that there is no boundary layer on the forward part of the wing.
calculated. In fact, half of the total lift on a
It should be noted that the wing at subsonic speeds is typically
Figure 10. The variation of the speed of speed of the uniform flow over produced in the first one-fourth
a fluid near an object the top of the wing is faster then of the chord length. The chord is
the free-stream velocity, which is the distance from the leading edge
The next streamline above the velocity of the undisturbed air to the trailing edge of the wing.
would be bent to follow the first by some distance from the wing. The The second thing to notice is that
the same process, and so on. The bending of the air causes the reduc- the arrows on the leading part of
streamlines increase in speed with tion in pressure above the wing. the wing are tilted forward. Thus
distance from the wing for a short This reduction in pressure causes the force of lift is pulling the wing
distance. This is on the order of 6 an acceleration of the air. It is often along as well as lifting it. This would
inch (15 cm) at the trailing edge of taught that the acceleration of the be nice if it were the entire story.
the wing of an Airbus A380. This air causes a reduction in pressure. In Unfortunately, the horizontal forces
region of rapidly changing air speed fact, it is the reduction of pressure on the trailing part of the wing
is the boundary layer. If the bound- that accelerates the air in agreement compensate the horizontal forces
ary layer is not turbulent, the flow with Newton’s first law. on the leading part of the wing.
is said to be laminar. Let us look at the air bending We now have the tools to
Thus, the streamlines are bent around the wing in Figure 11. To understand why a wing has lift. In
by a lowering of the pressure. This bend the air requires a force. As brief, the air bends around the wing
is why the air is bent by the top indicated by the colored arrows, the producing downwash. Newton’s
of the wing and why the pressure direction of the force on the air is first law says that the bending of
above the wing is lowered. This perpendicular to the bend in the the air requires a force on the air,
lowered pressure decrease with air. The magnitude of the force is and Newton’s third law says that
distance above the wing but is the proportional to the tightness of the there is an equal and opposite force
basis of the lift on a wing. The low- bend. The tighter the air bends the on the wing. That is a description of
ered pressure propagates out at the greater the force on it. The forces lift. The pressure difference across
speed of sound, causing a great deal on the wing, as shown by the black the wing is the mechanism in which
of air to bend around the wing. arrows in the figure, have the same lift is transferred to the wing due to
magnitude as the forces on the air the bending of the air.

8  FEATURES
Lift as a function of angle of at the wing as a virtual scoop that
attack intercepts a certain amount of air
There are many types of wing: con- and diverts it to the angle of the
ventional, symmetric, conventional downwash. This is not intended to
in inverted flight, the early biplane imply that there is a real, physical
wings that looked like warped scoop with clearly defined bound-
boards, and even the proverbial aries, and uniform flow. But this
“barn door”. In all cases, the wing is visualization aid does allow for a
forcing the air down, or more accu- clear understanding of how the
rately pulling air down from above. amount diverted air is affected by
(although the early wings did have speed and density. The concept of
a significant contribution from the the virtual scoop does have a real
bottom.) What each of these wings physical basis but beyond the scope
has in common is an angle of attack of this work.
with respect to the oncoming air. It Figure 12. Lift as a function of angle of The virtual scoop diverts a
is the angle of attack that is the pri- attack certain amount of air from the
mary parameter in determining lift. horizontal to roughly the angle of
To better understand the role of One can see in the figure that the attack, as depicted in Figure 13.
the angle of attack it is useful to lift is directly proportional to the For wings of typical airplanes it is a
introduce an “effective” angle of effective angle of attack. The lift good approximation to say that the
attack, defined such that the angle is positive (up) when the wing is area of the virtual scoop is pro-
of the wing to the oncoming air tilted up and negative (down) when portional to the area of the wing.
that gives zero lift is defined to be it is tilted down. When corrected The shape of the virtual scoop
zero degrees. If one then changes for area and aspect ratio, a plot of is approximately elliptical for all
the angle of attack both up and the lift as a function of the effec- wings, as shown in the figure. Since
down one finds that the lift is tive angle of attack is essentially the lift of the wing is proportional
proportional to the angle. Figure 12 the same for all wings and all wings to the amount of air diverted, the
shows the lift of a typical wing as inverted. This is true until the lift of is also proportional to the
a function of the effective angle of wing approaches a stall. The stall wing’s area.
attack. A similar lift versus angle of begins at the point where the
attack relationship is found for all angle of attack becomes so
wings, independent of their design. great that the airflow begins
This is true for the wing of a 747, to separate from the trailing
an inverted wing, or your hand out edge of the wing. This angle
the car window. The inverted wing is called the critical angle of
can be explained by its angle of attack and is marked on the
attack, despite the apparent con- figure. This separation of the Figure 13. The “virtual scoop” as a visualization
tool
tradiction with the popular expla- airflow from the top of the
nation of lift. A pilot adjusts the wing is a stall. As stated before, the lift of a
angle of attack to adjust the lift for wing is proportional to the amount
the speed and load. The role of the The wing as air “virtual virtual of air diverted down times the
angle of attack is more important scoop” vertical velocity of that air. As a
than the details of the wings shape We now would like to introduce a plane increases speed, the virtual
in understanding lift. The shape new mental image of a wing. One scoop diverts more air. Since the
comes into play in the understand- is used to thinking of a wing as a load on the wing does not increase,
ing of stall characteristics and drag thin blade that slices though the the vertical velocity of the diverted
at high speed. air and develops lift somewhat by air must be decreased proportion-
magic. For this we would like to ately. Thus, the angle of attack is
adopt a visualization aid of looking reduced to maintain a constant lift.

 9
When the plane goes higher, the air But, we all know
becomes less dense so the virtual that to go faster (in
scoop diverts less air at a given cruise) we must
speed. Thus, to compensate the apply more power.
angle of attack must be increased. So there must be
The concepts of this section will more to power than
be used to understand lift in a the power required
way not possible with the popular for lift. The power
explanation. associated with
lift is often called
Figure 14. The power required for flight
Lift requires power the “induced” power. Power is also
as a function of speed.
When a plane passes overhead the needed to overcome what is called
formally still air gains a downward “parasite” drag, which is the drag At cruise, the power requirement
velocity. Thus, the air is left in associated with moving the wheels, is dominated by parasite power.
motion after the plane leaves. The struts, antenna, etc. through the air. Since this goes as the speed3 an
air has been given energy. Power is The energy the airplane imparts increase in engine size gives one a
energy, or work, per time. So, lift to an air molecule on impact is faster rate of climb but does little
requires power. This power is sup- proportional to the speed2 (from to improve the cruise speed of the
plied by the airplane’s engine (or by ½mv2). The number of molecules plane. Doubling the size of the
gravity and thermals for a sailplane). struck per time is proportional to engine will only increase the cruise
How much power will we need the speed. The faster one goes the speed by about 25%.
to fly? If one fires a bullet with higher the rate of impacts. Thus the Since we now know how the
a mass, m, and a velocity, v, the parasite power required to over- power requirements vary with
energy given to the bullet is simply come parasite drag increases as the speed, we can understand drag,
½mv2. Likewise, the energy given to speed3. which is a force. Drag is simply
the air by the wing is proportional Figure 14 shows the “power power divided by speed. Figure 14
to the amount of air diverted down curves” for induced power, parasite shows the induced, parasite, and
times the vertical velocity squared power, and total power (the sum total drag as a function of speed.
of that diverted air. We have already of induced power and parasite Here the induced drag varies as 1/
stated that the lift of a wing is power). Again, the induced power speed2 and parasite drag varies as
proportional to the amount of air goes as 1/speed and the parasite the speed2. Taking a look at these
diverted times the vertical velocity power goes as the speed3. At low figures one can deduce a few things
of that air. Thus, the power needed speed the power requirements of about how airplanes are designed.
to lift the airplane is proportional to flight are dominated by the induced Slower airplanes, such as gliders,
the load (or weight) times the verti- power. The slower one flies the are designed to minimize induced
cal velocity of the air. If the speed less air is diverted and thus the power, which dominates at lower
of the plane is doubled, the amount angle of attack must be increased speeds. Faster propeller-driven
of air diverted down also doubles. to increase the vertical velocity of airplanes are more concerned
Thus to maintain a constant lift, the that air. Pilots practice flying on the with parasite power, and jets are
angle of attack must be reduced to “backside of the power curve” so dominated by parasite drag. (This
give a vertical velocity that is half that they recognize that the angle distinction is outside of the scope of
the original. The power required for of attack and the power required this article.)
lift has been cut in half. This shows to stay in the air at very low speeds
that the power required for lift are considerable.
becomes less as the airplane’s speed
increases. In fact, we have shown
that this power to create lift is pro-
portional to 1/speed of the plane.

10  FEATURES
Wing efficiency Power and wing loading The increase in the angle of
At cruise, a non-negligible amount Now let us consider the relation- attack with increased load has a
of the drag of a modern wing is ship between wing loading and downside other than just the need
induced drag. Parasite drag of a power. At a constant speed, if the for more power. As shown in Figure
Boeing 747 wing is only equivalent wing loading is increased the verti- 12 a wing will eventually stall when
to that of a 1/2-inch cable of the cal velocity of the downwash must the air can no longer follow the
same length. One might ask what be increased to compensate. This upper surface. That is, when the
affects the efficiency of a wing. We is accomplished by increasing the critical angle is reached. Figure 17
saw that the induced power of a angle of attack of the wing. If the shows the angle of attack as a func-
wing is proportional to the verti- total weight of the airplane were tion of airspeed for a fixed load and
cal velocity of the air. If the area of doubled (say, in a 2g turn), and the for a 2-g turn. The angle of attack
a wing were to be increased, the speed remains constant, the verti- at which the plane stalls is constant
size of our virtual scoop would also cal velocity of the air is doubled and is not a function of wing load-
increase, diverting more air. So, for to compensate for the increased ing. The angle of attack increases
the same lift the vertical veloc- wing loading. The induced power is as the load and the stall speed
ity (and thus the angle of attack) proportional to the load times the increases as the square root of the
would have to be reduced. Since vertical velocity of the diverted air, load. Thus, increasing the load in
the induced power is proportional which have both doubled. Thus the a 2-g turn increases the speed at
to the vertical velocity of the air, induced power requirement has which the wing will stall by 40%.
it is also reduced. Thus, the lifting increased by a factor of four! So An increase in altitude will further
efficiency of a wing increases with induced power is proportional to increase the angle of attack in a 2-g
increasing wing area. The larger the load2. turn. This is why pilots practice
the wing the less induced power One way to measure the total “accelerated stalls” which illustrates
required to produce the same lift, power is to look at the rate of fuel that an airplane can stall at any
though this is achieved with and consumption. Figure 16 shows speed, since for any speed there is a
increase in parasite drag. the fuel consumption versus gross load that will induce a stall.
There is a misconception by some weight for a large transport air-
that lift does not require power. This plane traveling at a constant speed
comes from aeronautics in the study (obtained from actual data). Since
of the idealized theory of wing sec- the speed is constant the change
tions (airfoils). When dealing with in fuel consumption is due to the
an airfoil, the picture is actually that change in induced power. The data
of a wing with infinite span. We are fitted by a constant (parasite
have seen that the power neces- power) and a term that goes as the
sary for lift decrease with increasing load2. This second term is just what
area of the wing. A wing of infinite was predicted in our Newtonian Figure 17. Angle of attack versus speed
span does not require power for lift discussion of the effect of load on for straight and level flight and for a 2-g
since it develops lift by diverting an induced power. turn.
infinite amount of air at near-zero
velocity. If lift did not require power
airplanes would have the same
range full as they do empty, and
helicopters could hover at any alti-
tude and load. Best of all, propellers
(which are rotating wings) would
not require much power to produce
thrust. Unfortunately, we live in
the real world where both lift and
propulsion require power. Figure 16. Fuel consumption as a function of
weight for large jet at a costant speed.

  11
Wing vortices Winglets (those small vertical What is the cause of this reduc-
One might ask what the down- extensions on the tips of some tion in drag? There are two contri-
wash from a wing looks like. The wings) are used to improve the butions that can be credited with
downwash comes off the wing as a efficiency of the wing by increasing the reduction in drag. The ground
sheet and is related to the details on the effective length, and thus area, influences the flow field around the
the load distribution on the wing. of the wing. The lift of a normal wing which, for a given angle of
Figure 18 shows, through condensa- wing must go to zero at the tip attack, increases the lift. But, at the
tion, the distribution of lift on an because the bottom and the top same time, there is a reduction in
airplane during a high-g maneuver. communicate around the end. The downwash. It can be surmised that
From the figure one can see that winglet blocks this communication this additional lift must come from
the distribution of load changes so the lift can extend farther out on an increase in pressure between the
from the root of the wing to the the wing. Since the efficiency of a wing and the ground. In addition,
tip. Thus, the amount of air in the wing increases with area, this gives since lift is increased for a given
downwash must also change along increased efficiency. One caveat is angle of attack, the angle of attack
the wing. The wing near the root is that winglet design is tricky and can be reduced for the same lift,
“virtual scooping” up much more winglets can actually be detrimental resulting in less downwash and less
air than the tip. Since the wing near if not properly designed. induced drag.
the root is diverting so much air Ground effect introduces a
the net effect is that the downwash Ground effect fundamental change from the
sheet will begin to curl outward The concept of ground effect is discussion of flight at altitude.
around itself, just as the air bends well known to pilots. This effect is When no ground is present, the
around the top of the wing because the increase in efficiency of a wing relationship between lift, drag and
of the change in the velocity of the as it comes to within about a wing’s downwash is straight forward. But,
air. This is the wing vortex. The length of the ground. The effect near the ground, there is an action-
tightness of the curling of the wing increases with the reduction in the reaction between the wing, the air
vortex is proportional to the rate distance to the ground. A low-wing and the ground. At altitude the
of change in lift along the wing. At airplane will experience a reduction ground is so distant that this effect
the wing tip the lift must rapidly in the induced drag of as much as does not exist. Near the ground
become zero causing the tightest 50 percent just before touchdown. this interaction helps produce lift
curl. This is the wing tip vortex and This reduction in drag just above and reduce downwash due to an
is just a small (though often most a surface is used by large birds, increase in pressure below the wing.
visible) part of the wing vortex. which can often be seen flying just The details of ground effect are
Returning to Figure 7 one can above the surface of the water. extremely complex. Most aerospace
clearly see the development of the Pilots taking off from deep-grass texts devote a paragraph or two
wing vortices in the downwash as or soft runways also use ground and don’t attempt to describe it in
well as the wing tip vortices. effect. The pilot is able to lift the depth. The truth is that so much
airplane off the soft surface at a is changing in ground effect that it
speed too slow to maintain flight is difficult to describe by pointing
out of ground effect. This reduces to a single change in the air flow
the resistance on the wheels and or a term in an equation. There is
allows the airplane to accelerate to no simple way to describe how the
a higher speed before climbing out airflow adjusts to satisfy the change
of ground effect. in conditions.
Figure 18. Condensation showing the
distribution of lift along a wing.

12  FEATURES
Conclusions
Let us review what we have learned ■■ A plane flies upside down. The
and get some idea of how the physical view has no problem
physical description has given us a with this. The plane adjusts the
greater ability to understand flight. angle of attack of the inverted
First what have we learned: wing to give the desired lift. The
popular explanation implies that
■■ The amount of air diverted by
inverted flight is impossible.
the wing is proportional to the
speed of the wing and the air As one can see, the popular expla-
density. nation, which fixates on the shape
of the wing, may satisfy many but it
■■ The vertical velocity of the
does not give one the tools to really
diverted air is proportional to the
understand flight. The physical
speed of the wing and the angle
description of lift is easy to under-
of attack.
stand and much more powerful. n
■■ The lift is proportional to the
amount of air diverted times the David Anderson is a private pilot and a
vertical velocity of the air. lifelong flight enthusiast. He as degrees
from the University of Washington, Seattle,
■■ The power needed for lift is and a Ph.D. in physics from Columbia Uni-
proportional to the lift times the versity. He has had a 30-year career in high-
vertical velocity of the air. Now energy physics at Los Alamos National Lab-
let us look at some situations oratory, CERN in Geneva, Switzerland, and
from the physical point of view the Fermi National Accelerator Laboratory.
and from the perspective of the
popular explanation. Scott Eberhardt is a private pilot who works
in high-lift aerodynamics at Boeing Com-
■■ The plane’s speed is reduced. mercial Airplanes Product Development.
The physical view says that the He has degrees from MIT and a Ph.D. in
amount of air diverted is reduced aeronautics and astronautics from Stanford
so the angle of attack is increased University. He joined Boeing in 2006 after
to compensate. The power 20 years on the faculty of the Department
needed for lift is also increased. of Aeronautics and Astronautics at the Uni-
The popular explanation cannot versity of Washington, Seattle.
address this. Reprinted with permission of the original authors.
First appeared in hn.my/allstar (allstar.fiu.edu)
■■ The load of the plane is
increased. The physical view says This material can be found in more detail in Un-
derstanding Flight 1st and 2nd editions by David
that the amount of air diverted is Anderson and Scott Eberhardt, McGraw-Hill, 2001,
the same but the angle of attack and 2009.
must be increased to give addi-
tional lift. The power needed
for lift has also increased. Again,
the popular explanation cannot
address this.

  13
DESIGN

The Messy Art of


UX Sketching
By Peiter Buick

I hear a lot of people talk-


ing about the importance of
sketching when designing or
problem-solving, yet it seems that
very few people actually sketch. As
not the best way to visually prob-
lem-solve. When you need to ideate
website layouts or mobile applica-
tions or to storyboard workflows
and context scenarios, sketching is
it, but they don’t go into the how
or the methods involved. Sketching
seems straightforward, but there are
certain ways to do it effectively. In
this article, we’ll cover a collection
a UX professional, I sketch every much more efficient. It keeps you of tools and techniques that I (and
day. I often take over entire walls from getting caught up in the tech- many other UX and design folks)
in our office and cover them with nology, and instead focuses you on use every day.
sketches, mapping out everything the best possible solution, freeing
from context scenarios to wire- you to take risks that you might not Sketching ≠ Drawing
frames to presentations. otherwise take. Some of the most effective sketches
Although starting a prototype on Many articles discuss the power I’ve seen are far from perfect draw-
a computer is sometimes easier, it’s of sketching and why you should do ings. Just like your thoughts and
ideas, sketches are in a constant
state of flux, evolving and morph-
ing as you reach a potential solu-
tion. Don’t think that you have to
be able to draw in order to sketch,
although having some experience
with it does help.
■■ Sketching is an expression of
thinking and problem-solving.
■■ It’s a form of visual communi-
cation, and, as in all languages,
some ways of communicating are
clearer than others.
■■ Sketching is a skill: the more you
do it, the better you’ll get at it.
When evaluating your sketches,
ask yourself, “How could I better
communicate these thoughts?”
My desk.

14  DESIGN
Getting caught up in evaluating Sketching in layers also keeps you Play To Your Strengths
your drawing ability is easy, but try from getting caught up in details Technique
to separate the two. Look at your right away. It forces you to decide Rotate the page before drawing
sketch as if it were a poster. What’s on the content and hierarchy of the a line in order to draw multiple
the first thing that’s read? Where is view first. If you are sketching an angles of lines more easily.
the detailed info? Remember, the interface that contains a list, but
Why?
eye is drawn to the area with the you don’t yet know what will go
Very few people can draw lines in
most detail and contrast. in the list, put in a few squiggles.
all directions equally well. Rotat-
Just as one’s ability to enunci- Later, you can go back in and sketch
ing the page allows you to draw a
ate words affects how well others a few options for each list item and
line in the range and direction that
understand them, one’s ability to append them to the page.
works best for you. Don’t try to
draw does have an impact on how
Caution draw a vertical line if you find it
communicative a sketch is. The
If you start drawing with a ball- difficult; rotate the page 90 degrees,
good news is that drawing and
point pen and then go in later with and draw a horizontal one instead.
sketching are skills, and the more
a marker, the pen’s ink will likely It’s super-simple but amazingly
you do them, the better you’ll get.
smear from the alcohol in the marker. powerful.
OK, let’s get started.
As you get more confident in
Caution
your sketching, you will become
Work In Layers This does not translate well to a
more comfortable and find that you
Often when I’ve done a sketch, the whiteboard, so you’ll still need to
don’t need to draw as many under-
result looks more like a collage than learn to draw vertical lines.
lays. But I still find it useful because
a sketch. Efficiency in sketching
it allows you to experiment and
comes from working in layers. Sketching Interactions
evaluate ideas as you sketch.
Technique
Technique
Start with a base sketch, and then
Start with a light-gray marker (20 Loosen Up
use sticky notes to add tooltips,
to 30% gray), and progressively add Technique
pop-overs, modal windows and
layers of detail with darker markers When sketching long lines, consider
other interactive elements.
and pens. moving your arm and pen with your
shoulder rather than from the elbow Why?
Why?
or wrist. Reserve drawing with your Using sticky notes to define tooltips
Starting with a light-gray marker
wrist for short quick lines and areas and other interactive elements lets
makes this easy. It allows you
where you need more control. you quickly define interactions and
to make mistakes and evaluate
concepts without having to redraw
your ideas as you work through a Why?
the framework of the application.
problem. Draw a crooked line with This will allow you to draw longer,
They are easy to move around and
the light marker? No big deal. The straighter lines. If you draw from
can be sketched on with the same
lines will barely be noticeable by the elbow, you’ll notice that the
markers and pens you are already
the time you’re finished with the lines all have a slight curve to them.
using.
sketch. Placing two dots on the paper, one
As the pages fill up with ideas, go where you want the line to start ■■ Define multiple interactions on
back in with a darker marker (60% and one where you want it to end, one sketch, and then strategi-
gray) or pen, and layer in addi- is sometimes helpful. Then, orient cally remove pieces one at a time
tional details for the parts you like. the paper, make a practice stroke or before scanning them in or copy-
This is also a great way to make a two, and then draw the line. ing the sketch.
particular sketch pop beside other A bonus to drawing from the
■■ Use different colors to represent
sketches. shoulder is that much of the
different types of interaction.
motion translates to drawing on
a whiteboard; so, in time, your
straight lines will be the envy of
everyone in the room.

  15
■■ Is one sticky note not big enough Copying And Pasting For The Technique
for your modal window? Add Real World Use a photocopier to quickly create
another right next to it. At times, you may want to manu- templates from existing sketches or
ally redraw a UI element multiple to redraw an area of a sketch.
■■ Is one sticky note too big for your
times in a sketch. This is not always
tooltip, user a ruler as a guide to Why?
a bad thing, because it gives you the
quickly rip the note down to size. A photocopier is the old-school
opportunity to quickly iterate and
version of Control + C, Control
forces you to reconsider your ideas.
+ V. It makes the production of
That being said, an all-in-one scan-
templates and underlays more effi-
ner or photocopier could dramati-
cient. It also boosts your confidence,
cally increase your efficiency.
because if you mess up (and you
will mess up), you can easily fix it.
■■ Does one part of your interface
need to be consistently redrawn
in multiple sketches? Run a few
copies, and then sketch directly
on the print-outs.
■■ Did you mess up a part of the
sketch? No problem. Cover up
that portion of the sketch with a
piece of paper or with correction
fluid, run off a copy, and then
start sketching directly on the
print-out.
■■ Are you working on a mobile
project? Or do you want to make
a series of sketches all of the same
Explore a variety of interactions and ideas in a single sketch using sticky notes.
size? Create a layout and copy off
a few rounds of underlays. Easier
yet, print off underlays of devices
or browsers; a good selection can
be found in the article “Free Print-
able Sketching, Wireframing and
Note-Taking PDF Templates 8.”
[hn.my/wireframe]
■■ Do you want to change the
layout of a sidebar in your last
five sketches? Sketch the new
sidebar, run off a few copies, and
then tape the new sidebars over
the old ones. It’s that easy.
■■ To use a sketch as an underlay
of another similar one, adjust the
density or darkness setting on
your photocopier to run a copy
Upon photocopying various versions of a sketch, each with different sticky notes,
of the sketch at 20% of it original
you’ll end up with various distinct sketches.
value.

16  DESIGN
Sketching over a photocopy of the original to reevaluate the The final sketch. Notice how the sidebar and its detail are
sidebar. darker than the photocopy. This is intentional, because it
allows you to explore ideas in the context of the overall
design.

The Design Is In The Details


Use a ruler; specifically, a quilting ruler. Quilting rulers
are translucent and are normally printed with a grid
screen, letting you see the line you’re drawing relative
to the rest of the sketch.
Technique
Use a ruler and a light-gray marker to draw an underlay
for a detailed sketch.
Why?
This lets you quickly draw a series of lines that are
Quickly creating evenly spaced lines with a quilting ruler and offset a set distance from each other. This works great
30% gray marker. for elements such as lists items, charts, buttons and
anything else that needs to be evenly spaced. It’s like an
analog version of “smart guides.”
Technique
After using a light-gray marker to lay out a sketch, use
a ruler and ballpoint pen or black marker to finalize it.
Why?
When sketching in layers, you want the final design or
layout to “pop.” A ruler enables you to be more pre-
cise in detailed areas and ensures that long edges are
straight.
There is no shame in using a ruler. The key is know-
ing when to use it. Don’t start sketching with a ruler;
rather, bring one in when you need the detail and pre-
cision. Remember, you’re sketching, not drawing.

Ripping a sticky note with a ruler.

  17
Technique
Use a ruler to quickly rip paper or
sticky notes by firmly holding the
paper with one hand and ripping
away the edge with the other hand.
Why?
It’s quicker then grabbing scissors;
you already have the ruler with
you; and you can take it through
airport security.
After lightly sketching an inter-
face with a light marker, finalize it
or make one area pop by using a
ruler to lay down darker lines.

Sketching ideas for a mobile application in the context of where it will be used.

Tell The Whole Story


Technique Why? Caution
Draw the application in the context This forces you to think about the Drawing the surrounding envi-
of where and how it being used, or environment that the application ronment can be challenging and
frame it with the device it will be will be used in, instills empathy for requires a higher level of sketching
used on. your users, and establishes under- competency. Don’t let this intimi-
standing of the challenges unique to date you. If you’re not comfortable
this application. sketching the environment or you
I get it. No one wants to sketch find it takes too long, use a picture
out a monitor every time they draw as an underlay instead.
a wireframe. I’m not saying you
have to, but a few sketches with
context go a long way. Especially
with mobile devices, the more con-
text you add to a sketch, the better.
Moreover, I always sketch the
device for a mobile interface as an
underlay, and I often try to sketch
the UI at full scale. This forces you
to deal with the constraints of the
device and makes you aware of how
the user may be holding the device.

18  DESIGN
One of the many walls of sketches in our office.

Ditch The Sketchbook What Are You Waiting For? It’s worth repeating that sketch-
Technique Sketching is not reserved for design- ing is the quickest way to explore
Draw on 8.5 × 11" copy paper. ers. Developers, project managers and share thinking with others. It
and business analysts can get in on focuses you on discovering the best
Why?
the fun, too. It’s the best way for possible solution, without getting
Sketches are for sharing. You can
teams to quickly communicate, caught up in the technology.
easily hang 8.5 × 11" sheets on a
explore and share ideas across dis- Go for it! Don’t get caught up in
wall to share ideas with others or to
ciplines. Also, I’ve found that others the tools. Make a mess. And have
see a project in its entirety. When
are more receptive to give feedback fun! n
you need to save a sketch or two,
and make suggestions when shown
you can easily batch scan them into
sketches than when shown print- Peiter Buick is Senior UX Specialist at
a computer without ripping them
outs or screenshots. Universal Mind. He is passionate about
out of the sketchbook. Still not con- design’s ability to directly impact peoples
Remember, it’s about getting
vinced? Copy paper is cheaper; it lives. With a background in industrial
ideas out, reviewing those ideas
allows you to use sketches as under- design, he brings a unique perspective to
and documenting them, not about
lays without photocopying; and the UX community.
creating a work of art. When evalu-
you don’t have to choose between
ating your sketches, ask yourself,
book-bound or spiral-bound. Reprinted with permission of the original author.
“How could I better communicate First appeared in hn.my/sketch (smashingmagazine.com)
these thoughts?” Getting caught up Images by Michael Kleinpaste.
in evaluating your drawing ability
is easy, but try to separate the two,
and know that the more you do it,
the better you’ll get.

  19
PROGRAMMING

Never Create Ruby Strings


Longer Than 23 Characters
By Pat Shaughnessy

O bviously this is an utterly


preposterous statement: it’s
hard to think of a more ridicu-
lous and esoteric coding requirement.
I can just imagine all sorts of amusing
containing 23 characters, while
the second line creates one with
24. It turns out that the MRI
Ruby 1.9 interpreter is opti-
mized to handle strings contain-
explains all of the basic Ruby
data types, including strings.
After reading through that,
I decided to dive right into the
MRI 1.9.3 C source code to learn
conversations with designers and business ing 23 characters or less more more about how Ruby handles
sponsors: “No… the size of this <input> quickly than longer strings. This strings; since I use RVM, for me
field should be 23… 24 is just too long!” isn’t true for Ruby 1.8. the Ruby source code is located
Or: “We need to explain to users that Today I’m going to take a under ~/.rvm/src/ruby-1.9.3-
their subject lines should be less than 23 close look at the MRI Ruby preview1. I started by looking
letters…” Or: “Twitter got it all wrong… 1.9 interpreter to see how it at include/ruby/ruby.h, which
the 140 limit should have been 23!” actually handles saving string defines all of the basic Ruby data
Why in the world would I even imagine values… and why this is actually types, and string.c, which imple-
saying this? As silly as this requirement true. ments Ruby String objects.
might be, there is actually a grain of truth Reading the C code, I discov-
behind it: creating shorter Ruby strings is Not all strings are created ered that Ruby actually uses
actually much faster than creating longer equal three different types of string
ones. It turns out that this line of Ruby Over the holidays I decided to values, which I call:
code: read through the Ruby Hack-
■■ Heap Strings
ing Guide [rhg.rubyforge.org].
str = "1234567890123456789012" + "x"
If you’ve never heard of it, it’s ■■ Shared Strings
… is executed about twice as fast by the a great explanation of how the
■■ Embedded Strings
MRI 1.9.3 Ruby interpreter than this line Ruby interpreter works inter-
of Ruby code: nally. Unfortunately, it’s written I found this fascinating! For
in Japanese, but a few of the years I’ve assumed every Ruby
str = "12345678901234567890123" + "x"
chapters have been translated String object was like every
Huh? What’s the difference? These two into English. Chapter 2, one other String object. But it turns
lines look identical! Well, the difference of the translated chapters, was out this is not true! Let’s take a
is that the first line creates a new string a great place to start since it closer look…

20  PROGRAMMING
Heap Strings You can see that the RString Shared Strings
The standard and most structure contains two values: Another type of string value that the Ruby
common way for Ruby to save ptr and len, but not the actual interpreter uses is called a “Shared String” in
string data is in the “heap.” The string data itself. Ruby actu- the Ruby C source code. You create a Shared
heap is a core concept of the ally saves the string character String every time you write a line of Ruby
C language: it’s a large pool of values themselves in some code that copies one string to another, similar
memory that C programmers memory allocated from the to this:
can allocate from and use via a heap, and then sets ptr to the
str = "Lorem ipsum dolor sit amet, con-
call to the malloc function. For location of that heap memory
sectetur adipisicing elit"
example, this line of C code and len to the length of the
str2 = str
allocates a 100 byte chunk of string.
memory from the heap and Here’s a simplified version Here the Ruby interpreter has realized that
saves its memory address into of the C RString structure: you are assigning the same string value to
a pointer: two variables: str and str2. So in fact there’s
struct RString {
no need to create two copies of the string
char *ptr = malloc(100); long len;
data itself. Instead, Ruby creates two RString
char *ptr;
Later, when the C program- values that share the single copy of the string
};
mer is done with this memory, data. The way this works is that both RString
she can release it and return it I’ve simplified this a lot; structs contain the same ptr value to the
to the system using free: there are actually a number shared data… meaning both strings contain
of other values saved in this the same value. There’s also a shared value
free(ptr);
C struct. I’ll discuss some of saved in the second RString struct that points
Avoiding the need to them next and others I’ll skip to the first RString struct. There are some
manage memory in this very over for today. If you’re not other details, which I’m not showing here,
manual and explicit way is one familiar with C, you can think such as some bit mask flags that Ruby uses to
of the biggest benefits of using of struct (short for “struc- keep track of which RStrings are shared and
any high level programming ture”) as an object that con- which are not.
language, such as Ruby, Java, tains a set of instance
C#, etc. When you create a variables, except in
string value in Ruby code like C there’s no object
this, for example: at all – struct is just
a chunk of memory
str = "Lorem ipsum dolor
containing a few
sit amet, consectetur adip-
values.
isicing elit"
I refer to this type
… the Ruby interpreter creates of Ruby string as
a structure called “RString” “Heap String” since
that conceptually looks like the actual string data
this: is saved in the heap.

Aside from saving memory, this also speeds


up execution of your Ruby programs dramat-
ically by avoiding the need to allocate more
memory from the heap using another call to
malloc. malloc is actually a fairly expensive
operation: it takes time to track down avail-
able memory of the proper size in the heap
and also to keep track of it for freeing later.

  21
Here’s a somewhat more accurate How do Embedded Strings work? The actual RString structure
version of the C RString structure, Well, the key is the size of the ary For those of you familiar with the C
including the shared value: array, which is set to RSTRING_ language, here’s the actual Ruby 1.9
EMBED_LEN_MAX+1. If you’re running definition of RString:
struct RString {
a 64-bit version of Ruby, RSTRING_
long len; struct RString {
EMBED_LEN_MAX is set to 24. That
char *ptr; struct RBasic basic;
means a short string like this will fit
VALUE shared; union {
into the RString ary array:
}; struct {
str = "Lorem ipsum dolor" long len;
Strings that are copied from one
char *ptr;
variable to another like this I call … while a longer string like this will
union {
“Shared Strings.” not:
long capa;
str = "Lorem ipsum dolor sit VALUE shared;
Embedded Strings
amet, consectetur adipisicing } aux;
The third and last way that MRI
elit" } heap;
Ruby 1.9 saves string data is by
embedding the characters into the
char ary[RSTRING_EMBED_LEN_
RString structure itself, like this: How Ruby creates new string
MAX + 1];
values
str3 = "Lorem ipsum dolor" } as;
Whenever you create a string value
};
in your Ruby 1.9 code, the inter-
preter goes through an algorithm I won’t try to explain all the code
similar to this: details here, but here are a couple
important things to learn about
■■ Is this a new string value or a
Ruby strings from this definition:
copy of an existing string? If it’s
a copy, Ruby creates a Shared ■■ The RBasic structure keeps
This RString structure contains String. This is the fastest option track of various important bits
a character array called ary and not since Ruby only needs a new of information about this string,
the ptr, len and shared values we RString structure and not another such as flags indicating whether
saw above. Here’s another simpli- copy of the existing string data. it’s shared or embedded, and
fied definition of the same RString a pointer to the corresponding
■■ Is this a long string or a short
structure, this time containing the Ruby String object structure.
string? If the new string value is
ary character array:
23 characters or less, Ruby cre- ■■ The capa value keeps track of the
struct RString { ates an Embedded String. While “capacity” of each Heap String...
char ary[RSTRING_EMBED_LEN_ not as fast as a Shared String, it’s it turns out Ruby will often
MAX + 1]; still fast because the 23 charac- allocate more memory than is
} ters are simply copied right into required for each Heap String,
the RString structure and there’s again to avoid extra calls to
If you’re not familiar with C
no need to call malloc. malloc if a string size changes.
code, the syntax char ary[100]
creates an array of 100 characters ■■ Finally, for long string values, 24 ■■ The use of union allows Ruby
(bytes). Unlike Ruby, C arrays are characters or more, Ruby cre- to EITHER save the len/ptr/
not objects. Instead, they are really ates a Heap String — meaning it capa/shared information OR the
just a collection of bytes. In C you calls malloc and gets some new actual string data itself.
have to specify the length of the memory from the heap, and then
■■ The value of RSTRING_EMBED_LEN_
array you want to create ahead of copies the string value there. This
MAX was chosen to match the size
time. is the slowest option.
of the len/ptr/capa values. That’s
where the 23-character limit
comes from.

22  PROGRAMMING
Here’s the line of code from ruby.h that defines We get an interesting result:
this value:
user system total real
#define RSTRING_EMBED_LEN_MAX ((int) 21 chars 0.250000 0.000000 0.250000 (0.247459)
((sizeof(VALUE)*3)/sizeof(char)-1)) 22 chars 0.250000 0.000000 0.250000 (0.246954)
23 chars 0.250000 0.000000 0.250000 (0.248440)
On a 64-bit machine, sizeof(VALUE) is 8,
24 chars 0.480000 0.000000 0.480000 (0.478391)
leading to the limit of 23 characters. This will be
25 chars 0.480000 0.000000 0.480000 (0.479662)
smaller for a 32-bit machine.
26 chars 0.480000 0.000000 0.480000 (0.481211)
27 chars 0.490000 0.000000 0.490000 (0.490404)
Benchmarking Ruby string allocation
Let’s try to measure how much faster short strings Note that when the string length is 23 or less, it takes
are vs. long strings in Ruby 1.9.3. Here’s a simple about 250ms to create 1 million new strings. But when
line of code that dynamically creates a new string my string length is 24 or more, it takes around 480ms,
by appending a single character onto the end: almost twice as long!
Here’s a graph showing some more data; the bars show
new_string = str + 'x'
how long it takes to allocate 1 million strings of the given
The new_string value will either be a Heap length:
String or an Embedded String, depending on how
long the str variable’s value is. The reason I need Time required to create 1 million strings (ms)
to use a string concatenation operation, the + 'x'

481=
450

490=

490=
481=
479=
478=

478=
475=
400
part, is to force Ruby to allocate a new string 350
dynamically. Otherwise, if I just used new_string = 300
250

248=
247=
247=
str, I would get a Shared String. 200
150
Now I’ll call this method from a loop and bench- 100
mark it: 50
0
require 'benchmark' 20 21 22 23 24 25 26 27 28 29 30
String Length

ITERATIONS = 1000000
Conclusion
Don’t worry! I don’t think you should refactor all your
def run(str, bench)
code to be sure you have strings of length 23 or less. That
bench.report("#{str.length + 1} chars") do
would obviously be ridiculous. The speed increase sounds
ITERATIONS.times do
impressive, but actually the time differences I measured
new_string = str + 'x'
were insignificant until I allocated 100,000s or millions
end
of strings — how many Ruby applications will need to
end
create this many string values? And even if you do need to
end
create many string objects, the pain and confusion caused
Here I’m using the benchmark library to mea- by using only short strings would overwhelm any perfor-
sure how long it takes to call that method 1 million mance benefit you might get.
times. Now running this with a variety of different For me I really think understanding something about
string lengths: how the Ruby interpreter works is just fun! I enjoyed
taking a look through a microscope at these sorts of tiny
Benchmark.bm do |bench|
details. I do also suspect having some understanding of
run("12345678901234567890", bench)
how Matz and his colleagues actually implemented the
run("123456789012345678901", bench)
language will eventually help me to use Ruby in a wiser
run("1234567890123456789012", bench)
and more knowledgeable way. n
run("12345678901234567890123", bench)
run("123456789012345678901234", bench)
Pat Shaughnessy (@pat_shaughnessy) is a Ruby developer working
run("1234567890123456789012345", bench)
at a global management consulting firm. Pat also writes in-depth
run("12345678901234567890123456", bench)
articles at patshaughnessy.net, some of which have been featured on
end the Ruby Weekly newsletter, the Ruby5 podcast and the Ruby Show.

Reprinted with permission of the original author. First appeared in hn.my/23char (patshaughnessy.net)

  23
Fountain Codes
By Nick JohnSon

F ountain Codes, otherwise


known as “rateless codes,” is
a way to take some data — a
file, for example — and transform
it into an effectively unlimited
sending a static file over a broad-
cast medium, such as on-demand
TV, to propagating chunks of a file
amongst a large number of peers,
like BitTorrent does.
That’s pretty straightforward,
right? A lot depends on how we
pick the number of blocks to com-
bine together — called the degree
distribution — but we’ll cover that
number of encoded chunks, such Fundamentally, though, fountain in more detail shortly. You can see
that you can reassemble the origi- codes are surprisingly simple. There from the description that some
nal file given any subset of those are a number of variants, but for encoded blocks will end up being
chunks, as long as you have a little the purposes of this article, we’ll composed of just a single source
more than the size of the origi- examine the simplest, called an LT, block, while most will be composed
nal file. In other words, it lets you or Luby Transform Code. LT codes of several source blocks.
create a “fountain” of encoded data; generate encoded blocks like this:
a receiver can reassemble the file by
1. Pick a random number, d,
catching enough “droplets,” regard-
between 1 and k, the number of
less of which ones they get and
blocks in the file. We’ll discuss
which ones they miss.
how best to pick this number
What makes this so remarkable
later.
is that it allows you to send a file
over a lossy connection — such as, 2. Pick d blocks at random from the
say, the internet — in a way that file, and combine them together.
doesn’t rely on you knowing the For our purposes, the xor opera-
rate of packet loss, and it doesn’t tion will work fine.
require the receivers to commu-
3. Transmit the combined block,
nicate anything back to you about
along with information about
which packets they missed. You
which blocks it was constructed
can see how this would be useful
from.
in a number of situations, from

24  PROGRAMMING
Another thing that might not be immedi- Let’s work through an
ately obvious is that while we do have to let example of decoding to 0x48 0x48 = "H"
the receiver know what blocks we combined make it clearer. Suppose
together to produce the output block, we we receive five encoded
don’t have to transmit that list explicitly. blocks, each one byte
If the transmitter and receivers agree on a long, along with informa- 0x2D ?
pseudo-random number generator, we can tion about which source
seed that PRNG with a randomly chosen blocks each is constructed
seed and use that to pick the degree and from. We could represent
the set of source blocks. Then, we just send our data in a graph, like 0x24 ?
the seed along with the encoded block, and this:
our receiver can use the same procedure to
reconstruct the list of source blocks we used.
The decoding procedure is a little — but
0x66 ?
not much — more complicated:
1. Reconstruct the list of source blocks that
were used to construct this encoded block.
0x03 ?
2. For each source block from that list, xor
that block with the encoded block if you
have already decoded it, and remove it
from the list of source blocks.
3. If there are at least two source blocks left
in the list, add the encoded block to a
Nodes on the left repre-
holding area.
sent encoded blocks we 0x48 0x48 = "H"
4. If there is only one source block remaining received, and nodes on
in the list, you have successfully decoded the right represent source
another source block! Add it to the blocks. The first block
decoded file, and iterate through the hold- we received, 0x48 turns 0x2D 0x65 = "e"
ing list, repeating the procedure for any out to consist of only one
encoded blocks that contain it. source block — the first
source block — so we
already know what that 0x24 0x6C = "I"
block was. Following the
arrows pointing to the
first source block, we can
see that the second and
0x66 ?
third encoded blocks only
depend on the first source
block and one other. Since
we now know the first
0x03 ?
source block, we can xor
them together, giving us
this:

  25
Repeating the same Admittedly this is a fairly contrived
procedure again, we can 0x48 0x48 = "H" example since we happened to receive just
see we now know enough the blocks we needed to decode the message,
to decode the fourth with no extras and in a very convenient order.
encoded block, which However, it serves to demonstrate the prin-
depends on the second 0x2D 0x65 = "e" ciple. I’m sure you can see how this applies to
and third source blocks, larger blocks and larger files quite simply.
both of which we now I mentioned earlier that selecting the
know. XORing them degree distribution, which is the number of
together lets us decode 0x24 0x6C = "I" source blocks each encoded block should
the fifth and final source consist of, is quite important. Ideally, we need
block, giving us this: to generate a few encoded blocks that have
just one source block so decoding can get
started, and a majority of encoded blocks that
0x66 ?
depend on a few others. It turns out such an
ideal distribution exists, and is called the ideal
soliton distribution.
Unfortunately, the ideal soliton distribu-
0x03 0x6F = "o"
tion isn’t quite so ideal in practice, as random
variations make it likely that there will be
source blocks that are never included, or that
decoding will stall when it runs out of known
blocks. A variation on the ideal soliton distri-
Finally, we can now bution, called the robust soliton distribution,
decode the last remaining 0x48 0x48 = "H" improves on this, generating more blocks
source block, giving us the with very few source blocks and also generat-
rest of the message: ing a few blocks that combine all or nearly all
of the source blocks to facilitate decoding the
0x2D 0x65 = "e" last few source blocks.
That, in a nutshell, is how fountain codes,
and LT codes specifically, work. LT codes
are the least efficient of the known fountain
0x24 0x6C = "I" codes, but also the simplest to explain. If
you’re interested in learning more, I’d highly
recommend reading this technical paper on
fountain codes [hn.my/mackay], as well as
reading about Raptor Codes [hn.my/raptor],
0x66 0x6C = "I"
which add only a little complexity over LT
codes, but significantly improve their effi-
ciency, both in terms of transmission over-
head and computation. n
0x03 0x6F = "o"

Nick Johnson is a Developer Programs Engineer for


Google App Engine, who’s just seen the light and relo-
cated to Australia. He regularly blogs about interesting
computer science topics at his blog [blog.notdot.net].
When he’s not saving the world there, he can be found
Reprinted with permission of the original author. on Twitter (@nicksdjohnson) or Stack Overflow help-
First appeared in hn.my/fountain (notdot.net) ing folks out.

26  PROGRAMMING
Unfortunate Python
By Ian Ward

P ython is a wonder-
ful language, but some
parts should really
have bright warning
signs all over them. There are fea-
tures that just can’t be used safely
and others are that are useful but
Ducks in a Row
Explicitly checking the type of a
parameter passed to a function
breaks the expected duck-typing
convention of Python. Common
type checking includes:
■■ isinstance(x, X)
Not Really a Vegetable
import pickle # or cPickle

Objects serialized with pickle are


tied to their implementations in
the code at that time. Restoring
an object after an underlying class
people tend to use in the wrong has changed will lead to undefined
ways. ■■ type(x) == X behavior. Unserializing pickled data
from an untrusted source can lead
With type() being the worse of the
Easy Stuff First to remote exploits. The pickled data
two.
Starting with the non-controversial: itself is opaque binary that can’t be
If you must have different behav-
Anything that has been marked easily edited or reviewed.
ior for different types of objects
deprecated should be avoided. The This leaves only one place
passed, try treating the object as
deprecation warning should have where pickle makes sense — short-
the first data type you expect, and
instructions with safe alternatives lived data being passed between
catching the failure if that type
you can use. processes, just like what the
wasn’t that type, and then try the
Some of the most frequent multiprocessing module does.
second. This allows users to create
offenders are parts of the language Anywhere else, use a different
objects that are close enough to the
that make it difficult to safely call format. Use a database or use JSON
types you expect and still use your
other programs: with a well-defined structure. Both
code.
are restricted to simple data types
■■ os.system()
and are easily verified or updated
■■ os.popen() outside of your Python script.
■■ import commands

We have the excellent subprocess


module for these now, use it.

27  PROGRAMMING
Toys are for Children Python’s garbage collector and Admit You Always Hated It
Many people are drawn to these could lead to memory leaks.
if __name__ == '__main__':
modules because they are part of Use a weakref.ref object with a
Python’s standard library. Some callback to run code when an object This little wart has long been a
people even try to do serious work is being removed instead. staple of many Python introduc-
with them. tions. It lets you treat a Python
Split Personality script as a module or a module as
■■ asyncore / asynchat
a Python script. Clever, sure, but
reload(x)
■■ SimpleHTTPServer it’s better to keep your scripts and
It looks like the code you just modules separate in the first place.
The former resembles a reason-
changed is there, except the old If you treat a module like a script,
able asynchronous library, until you
versions of everything are still there and then something imports the
find out there are no timers. At all.
too. Objects created before the module, you’re in trouble: now you
Use Twisted instead; it’s the best
reload will still use the code as it have two copies of everything in
we’ve got.
was when they were created, lead- that module.
The latter makes for a neat demo
ing to situations with interesting I have used this trick to make
by giving you a web server in your
effects that are almost impossible to running tests easier, but setuptools
pocket with the one command
reproduce. already provides a better hook for
python -m SimpleHTTPServer. But
Just re-run your program. If running tests. For scripts, setuptools
this code was never intended for
you’re debugging at the interactive has an answer too: just give it a
production use and certainly not
prompt, consider debugging with a name and a function to call, and
designed to be run as a public web
small script and python -i instead. you’re done.
server. There are plenty of real,
My last criticism is that a single
hardened web servers out there
Almost Reasonable line of Python should never be 10
that will run your Python code as a
alphanumeric characters and 13
WSGI script. Choose one of them import copy
punctuation characters. All those
instead.
The copy module is harmless underscores are there as a warn-
enough when used on objects that ing that some special non-obvious
Foreign Concepts
you create and you fully under- language-related thing is going on,
import array stand. The problem is once you get and it’s not even necessary.
in the habit of using it, you might
All the flexibility and ease of use of
be tempted to use it on objects Don’t Emulate stdlib
C arrays, now in Python!
passed to you by code you don’t If it’s in standard library, it must be
If you really, really need this you
control. well written, right?
will know. Interfacing with C code
Copying arbitrary objects is May I present the implementa-
in an extension module is one valid
troublesome because you will often tion of namedtuple, which is a
reason.
copy too little or too much. If this really handy little class that, if used
If you’re looking for speed, try
object has a reference to an external properly, can significantly improve
just using regular Python lists
resource, it’s unclear what copying your code’s readability:
and PyPy. Another good choice is
that even means. It can also easily
NumPy for its much more capable def namedtuple(typename,
lead to subtle bugs introduced into
array types. field_names, verbose=False,
your code by a change outside your
rename=False):
code.
Can't be Trusted # Parse and validate the field
If you need a copy of a list or a
# names. Validation serves
def __del__(self): dict, use list() or dict() because
# two purposes, generating
you can be sure what you will get
The mere existence of this method # informative error messages
after they are called. copy(), how-
makes objects that are part of a # and preventing template
ever, might return anything, and
reference cycle uncollectable by # injection attacks.
that should scare you.

28  PROGRAMMING
Wait, what? “preventing template injection attacks”? Yes, that’s a class definition in a big
This is followed by 27 lines of code that validates field_names. Python string, filled with variables from
And then: locals(). The result is then execed in the
right namespace, and some further magic is
template = '''class %(typename)s(tuple):
applied to “fix” copy() and pickle().
'%(typename)s(%(argtxt)s)' \n
I believe this code was meant as some
__slots__ = () \n
sort of warning to people that would con-
_fields = %(field_names)r \n
tribute code to Python — something like
def __new__(_cls, %(argtxt)s):
“We make it look like we know what we’re
'Create new instance of %(typename)s(%(argtxt)s)'
doing, but we’re really just nuts” (love ya
return _tuple.__new__(_cls, (%(argtxt)s)) \n
Raymond).
@classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
Trying Too Hard
'Make a new %(typename)s object from a sequence or
iterable' hasattr(obj, 'foo')
result = new(cls, iterable)
hasattr has always been defined to swal-
if len(result) != %(numfields)d:
low all exceptions, even ones you might
raise TypeError('Expected %(numfields)d arguments,
be interested in (such as a KeyboardInter-
got %%d' %% len(result))
rupt), and turn them into a False return
return result \n
value. This interface just can’t be fixed, so
def __repr__(self):
use getattr with a sentinel value instead.
'Return a nicely formatted representation string'
return '%(typename)s(%(reprtxt)s)' %% self \n
Off by One
def _asdict(self):
'Return a new OrderedDict which maps field names to 'hello'.find('H')
their values'
str.find and str.rfind return -1 on failure.
return OrderedDict(zip(self._fields, self)) \n
This can lead to some really hard-to-find
__dict__ = property(_asdict) \n
bugs when combined with containers like
def _replace(_self, **kwds):
strings that treat -1 as the last element. Use
'Return a new %(typename)s object replacing specified
str.index and str.rindex instead. n
fields with new values'
result = _self._make(map(kwds.pop, %(field_names)r,
Ian Ward is an independent software developer
_self))
in Ottawa, Canada. He works primarily with Linux,
if kwds:
Python, C and PostgreSQL. He is also the author and
raise ValueError('Got unexpected field names: maintainer of the Python console user interface
%%r' %% kwds.keys()) library Urwid.
return result \n
def __getnewargs__(self): Reprinted with permission of the original author.
'Return self as a plain tuple. Used by copy and First appeared in hn.my/unfortunate (excess.org)
pickle.'
return tuple(self) \n\n''' % locals()

  29
Tips for Remote Unix Work
By Brandon Mintern

I f you are anything like me,


you have programs running
on all kinds of different
servers. You probably have
a GitHub account, a free Heroku
instance, a work desktop, a couple
website instances, and maybe even
Logging in via SSH without a
password
We have only recently seen web-
sites start to offer solutions for
logging in without a password. SSH
has provided a secure mechanism
for this (based on public-key cryp-
2. Copy the public key to each
computer you connect to
For each computer that you
connect to, run the following
command:
ssh-copy-id user@example.com

a home server. The best part is that tography) since its inception. It’s (Note that you can specify -p PORT
using common Unix tools, you can pretty easy to setup once you know or any other SSH arguments before
connect to all of them from one how it works. the user@example.com portion of
place. the above command.)
1. Generate a public-private key
In this article, I will review some
pair This should be the last time
of the more interesting aspects of
If you haven’t already, run ssh- you ever have to type your login
my workflow, covering the usage
keygen on your laptop, or what- password when connecting to the
of SSH, screen, and VNC, includ-
ever computer you will be doing remote server. From now on, when
ing a guide for getting started with
your work from. You can just you SSH to the remote server, its
VNC. I’ll provide some quick start
continue pressing Enter to accept sshd service will encrypt some
information and quickly progress
the defaults, and you can leave the data using the public key that you
to advanced topics (like SSH pipes
password blank (if you secure your appended to authorized_keys, and
and auto-session-creation) that even
laptop with encryption, a locking your local machine will be able to
experienced Unix users may not be
screensaver, and a strong password, decode that challenge with your
aware of.
your SSH key doesn’t require a private key.
password). This will generate a
SSH to rule them all 3. There is no step 3
public key at ~/.ssh/id_rsa.pub
By now you’ve almost certainly It’s that easy! Don’t you wish you
and a private key at ~/.ssh/id_rsa.
used SSH. It’s the easiest way to had set this up a long time ago?
The private key should never leave
login to a remote machine and get
your computer.
instant command line access. It’s as
easy as ssh user@example.com. You
type in your password, and you’re
in! But you might not know that
it can be even easier (and more
secure) than that.

30  PROGRAMMING
SSH and pipes Send the files at ~/src/ to example. Create an SSH tunnel
If you take a look at the ssh-copy- com:~/src/ without rsync or scp
ssh -NT -L 9000:localhost:8000
id script, you’ll see a line that
cd && tar czv src | ssh exam- example.com
roughly translates to:
ple.com 'tar xz'
Using the -L flag, you can tell SSH
cat ~/.ssh/id_rsa.pub | ssh
to listen on a local port (9000),
user@example.com "umask 077; Copy the remote website at exam-
and to reroute all data sent and
test -d ~/.ssh || mkdir ple.com:public_html/example.com
received on that port to example.
~/.ssh ; cat >> ~/.ssh/ to ~/backup/example.com
com:8000. To any process listen-
authorized_keys"
mkdir -p ~/backup/ ing on example.com:8000, it will
When you ran ssh-copy-id above, look like it’s talking to a local
here’s what that line did: cd !$ process (and it is: an SSH process).
So open a terminal and run the
1. The contents of ~/.ssh/id_rsa.
ssh example.com 'cd public_html above command, and then fire up
pub were piped into the SSH
&& tar cz example.com' | tar your browser locally and browse to
command.
xzv localhost:9000. You will be whisked
2. SSH encrypted that data and away to example.com:8000 as if
sent it across the network to your See if httpd is running on you were working on it locally!
remote machine. example.com Let me clarify the argument to -L
a bit more. The bit before the colon
3. Everything in double quotes after ssh example.com 'ps ax | grep
is the port on your local machine
the host is a single argument to [h]ttpd'
that you will connect to in order
ssh; this specified that instead of
to be tunneled to the remote port.
giving you an interactive login,
Other SSH tunnels The part after the second colon is
you instead wanted to run a
If piped data were the only thing the port on the remote machine.
command.
that could be securely tunneled The “localhost” bit is the remote
4. The first portion of that com- over SSH connections, that would machine you will be connected to,
mand (umask 077; test -d still be useful. But SSH can also from the perspective of example.
~/.ssh || mkdir ~/.ssh ;) make remote ports seem local. com. When you realize the rami-
created a .ssh directory on the Let’s say that you’re logged into fications of this, it becomes even
remote machine if it did not example.com, and you’re editing a more exciting! Perhaps you have a
already exist, ensuring that it had remote website that you’d like to work computer to which you have
the proper permissions. test on port 8000. But you don’t SSH access, and you have a com-
want just anyone to be able to pany intranet site at 192.168.10.10.
5. The second portion (cat >>
connect to example.com:8000, and Obviously, you can’t reach this
.ssh/authorized_keys) received
besides, your firewall won’t allow it. from the outside. Using an SSH
the standard input via the SSH
What if you could get a connection tunnel, however, you can!
tunnel and appended it to the
to example.com, localhost:8000,
authorized_keys file on the ssh -NT -L
but from your local computer and
remote machine. 8080:192.168.10.10:80 work-
browser? Well, you can!
account@work-computer.com
This avoids the need to use SCP
and login multiple times. SSH Now browse to localhost:8080
can do it all! Here are some more from your local machine, and smile
examples to show you some of the as you can access your company
neat things you can do with SSH intranet from home with your lap-
pipe functionality. top’s browser, just as if you were on
your work computer.

  31
But my connection sucks, or, What happened to Control-a? Starting screen automatically
GNU screen Screen intercepts Control-a to It’s pretty easy to forget to run
Have you ever started a long- enable some pretty cool function- screen after logging in. Personally,
running command, checked in on it ality. Unfortunately, you may be any time I am using SSH to login
periodically for a couple hours, and used to using Control-a for readline and work interactively, I want to be
then watched horrified as your con- navigation. You can now do this by in a screen session. We can com-
nection dropped and all the work pressing Ctrl-a, a. Alternatively, bine SSH’s ability to run a remote
was lost? Don’t let it happen again. you can remap it by invoking screen command upon login with screen’s
Install GNU screen on your remote with the -e option. For example, ability to reconnect to detached ses-
machine, and when you reconnect running screen -e ^jj would sions. Simply create an alias in your
you can resume your work right cause Control-j to be intercepted ~/.bashrc file:
where you left off (it may have by screen instead of Control-a. If
alias sshwork='ssh -t work-
even completed while you were you do this, just replace references
username@my-work-computer.com
away). to “C-a” in the aforementioned ref-
"screen -dR"'
Now, instead of launching right erence guide with whatever escape
into your work when you connect key you defined. This will automatically fire up
to your remote machine, first start a screen session if there is not one
Shift-PageUp is broken
up a screen session by running running, and if there is one running,
Like vim and less, screen uses
screen. From now on, all the work it will connect to it. Detaching from
the terminal window differently
you are doing is going on inside the screen session will also logout of
from most programs, controlling
screen. If your connection drops, the remote server.
the entire window instead of just
you will be detached from the
dumping text to standard output
screen session, but it will continue Remote graphical work
and standard error. Unfortunately,
running on the remote machine. Even in spite of SSH’s port for-
this breaks Shift-PageUp and Shift-
You can reattach to it when you log warding capabilities, we still some-
PageDown in gnome-terminal. For-
back in by running screen -r. If times need to use graphical applica-
tunately, we can fix this by creating
you want to manually detach from tions. If you have a fast connection
a ~/.screenrc file with the follow-
the session but leave it running, or a simple GUI, passing the -Y flag
ing line in it:
type Ctrl-a, d from within the to SSH could be enough to allow
screen session. termcapinfo xterm ti@:te@ you run the application on your
local desktop. Unfortunately, this
Using screen And while you’re mucking
often is a very poor user experience,
Screen is a complex program, and around in .screenrc, you might as
and it does not work well with
going into everything it can do well add an escape ^jj line to it, so
screen (a GUI application started
would be a series of articles. Instead, that you can stop typing in -e ^jj
in a screen session dies when you
check out this great screen quick every time you invoke screen.
detach from the screen session).
reference guide [hn.my/screen].
The time-tested Unix solution to
Some of screen’s more notable
this problem is VNC. This is effec-
features are its ability to allow
tively a combination of screen and
multiple terminal buffers in a single
a graphical environment. Unfortu-
screen session and its scrollback
nately, it has several drawbacks.
buffer.

32  PROGRAMMING
■■ It can be tricky to setup You can start a VNC server with On your local machine, install
reasonably. the following command: a VNC viewer. I personally use
gvncviewer, though I don’t par-
■■ It is inherently insecure, with vncserver -geometry WIDTHxHEIGHT
ticularly recommend it. Now, to
unencrypted data and a weak
where WIDTHxHEIGHT is your connect to that remote port, you’ll
password feature.
desired resolution. For me, it’s need to start an SSH tunnel on
■■ Its performance on a sub-optimal 1440x900. The first time you run your local machine:
connection is less-than-stellar. this, it will ask you to create a
ssh -NT -L 5901:localhost:5901
password. We are going to ensure
■■ It doesn’t transfer sounds over remote-machine.com
security through other means, so
the network.
you can set it to whatever you want. We can now run the VNC viewer
I’m going to help you solve all of Running the above command will on our local machine to connect via
these problems, except the sound give a message like “New ‘remote- the tunnel to our VNC session:
one. Who needs sounds, anyway? machine:1 (username)’ desktop is
gvncviewer :1
remote-machine:1”. The “:1” is the
VNC installation and setup
display number. By adding 5900
On the remote machine, you’ll Speeding up VNC?
to this, we can determine which
need to install a VNC server and a When starting an SSH tunnel, we
port the VNC server is listening
decent lightweight window man- can compress the data it sends by
on. At this point, we can connect
ager. I chose fluxbox and x11vnc: including the -C flag. Depending
to remote-machine:5901 with a
on your connection speed, it may
sudo apt-get install x11vnc vncviewer and log in to the session
be worth including the flag in your
fluxbox we’ve created. We don’t want the
tunnel command. Experiment with
entire Internet to be able to connect
The programs that are started this option and see what works best
to our poorly-secured session, so let’s
when you first start a VNC ses- for you.
terminate that VNC server session:
sion are controlled by the ~/.vnc/ If you are really having prob-
xstartup file. I prefer something a vncserver -kill :1 lems, you might also want to check
bit better than the defaults, so mine out the -deferUpdate option,
looks like this: Securing the VNC server which can delay how often display
Remember how we tunneled ports changes are sent to the client. For
#!/bin/sh
with SSH? We can do the same more information, man Xvnc.
[ -x /etc/vnc/xstartup ] &&
thing with VNC data. First, we’ll
exec /etc/vnc/xstartup Automatically starting and connect-
invoke our VNC server slightly
[ -r $HOME/.Xresources ] && ing to your VNC session
differently:
xrdb $HOME/.Xresources Putting everything together, we can
netbeans & vncserver -localhost -geometry create a script that does all of this
gnome-terminal & WIDTHxHEIGHT -SecurityTypes for us. Simply set the GEOMETRY and
fluxbox & None SSH_ARGS variables appropriately (or
modify it slightly to accept them as
Modify this to suit your own This causes the VNC server
command line arguments).
needs. I only invoke netbeans to only accept connections that
because it’s the only reason I originate on the local machine.
ever use a remote GUI at all. NB: It also indicates that we will not
Although it may seem counterin- need a password to connect to
tuitive, it’s typically best to put the our session; simply being logged
window manager command last. in locally as the user who created
the session is enough. You should
now have a VNC server running
on a remote machine listening on
localhost:5901.

  33
#!/bin/bash from there. This all happens within a single command
set -e executed by ssh, and the resulting output is piped across
the network back into our vnc_display variable.
GEOMETRY=1440x900 Either way we get the value, we now know which
SSH_ARGS='-p 22 username@remote-server.com' port to connect to in order to reach our VNC server.
We start our SSH tunnel and get the resulting PID.
# Get VNC display number. If there is not a VNC Finally, we invoke the vncviewer on that tunneled local
# process running, start one port. When the VNC viewer exits, we automatically
vnc_display="$(ssh $SSH_ARGS 'ps_text="$(ps x | kill our SSH tunnel as well.
grep X[v]nc | awk '"'"'{ print $6 }'"'"' | sed
s/://)"; if [ "$ps_text" = "" ]; then vncserver Concluding remarks
-localhost -geometry '$GEOMETRY' -Security- One of the best parts of Unix is that it was built to
Types none 2>&1 | grep New | sed '"'"'s/^.*:\ be run remotely from Day 1. Just about anything you
([^:]*\)$/\1/'"'"'; else echo "$ps_text"; fi')" can do on your local computer can also be done on a
port=`expr 5900 + $vnc_display` remote one. By leveraging tools like SSH, screen, and
ssh -NTC -L $port:localhost:$port $SSH_ARGS & VNC, we can make remote work as easy and conve-
SSH_CMD=`echo $!` nient as local work. I hope this gave you some ideas for
sleep 3 how you can create a productive workflow with these
gvncviewer :$vnc_display very common Unix tools. n
kill $SSH_CMD
Brandon Mintern is Lead Software Engineer at EasyESI, a seed-
The vnc_display line is pretty gross, so I’ll give some
funded startup in Berkeley. His pursuits include reverse engi-
explanation. It uses SSH to connect to the remote server neering, data processing, and language design. He presented
and look for a running process named Xvnc: this is the at the first annual PyOhio. He currently enjoys exploring all the
running VNC server. If there’s one running we extract Bay Area has to offer.
the display number. Otherwise, we start one up with
the specified geometry and grab the display number Reprinted with permission of the original author.
First appeared in hn.my/remoteunix (brandonmintern.com)

Being a Great Coder By Timothy Daly

D o yourself a favor and lose


the “great coder” meme. Or
get a job at Google and remain
Your opinion of how great you
are at programming will follow a
bell curve. You’ll start off coming
Anybody who rates themselves
as “great” is probably on the uphill
side of the learning curve.
blissfully unaware. out of college thinking you’re ok, If you’re trying to learn Clojure,
One of the best books I’ve ever memorize a few algorithms and moving into areas that are beyond
read about programming is called order theory (“the Google disease”) your comfort zone, and trying
“Practicing: A Musician’s Return and think you’re “great” (“Google to learn literate programming to
to Music,” where the author talks only hires great coders”). But as improve your game, all points to the
about his development as a musi- you learn more you’ll discover that fact that you will likely reach a point
cian. He would receive compli- you have SO much more to learn, where you feel that being labeled
ments on how great he was at and as you work on larger proj- “great” is a sign that the speaker is
playing the guitar. At one point he ects you’ll discover the musician’s clueless. Give it 10000 hours. n
replies, “How would you know?” insight. People would rate you
The better he got, the worse he “great,” but you’ll be able to say, Timothy Daly is Axiom’s lead developer.
knew he was. “How would you know?” At which He is currently running his own consulting
point, the better you get, the worse business, Literate Software, while building
you’ll know you are. a base of literate tools.

Reprinted with permission of the original author. First appeared in hn.my/greatcoder


SPECIAL

Why 13th

Chords
By JAMES TAUBER

A s the background to my
music theory is more classical
in nature, it used to puzzle me
when I saw jazz chords like
C9, B♭ 11 or F13. I mean, I knew what a 9th,
11th and 13th note were, but I wondered why
you’d call a note a 9th rather than a 2nd, or a
The 3rd and 7th are really the defining notes
of a chord in jazz, particularly comping on
piano where you expect the bass to provide the
root. So the final light went off when I saw the
closing jazz riff of Ben Folds Five’s Underground
notated. There were a bunch of triads that were
marked as 13th chords. So, for example, the
13th rather than a 6th and so on. voicing E♭ +A+D was marked as F13.
After all, when you talk about chord, you’re Note that that voicing has just the 3rd, 7th
normally talking about notes independent of and 13th. The 13th is also a 6th, but by call-
octave. If you describe something as a C7 chord, ing the chord F13, it’s making it clear the 7th
you’re not saying anything about whether the E is there as well, which gives the chord a very
and B♭ are in the same octave or not. different direction it wants to go. The 7th makes
I can’t remember when, but the breakthrough the whole chord want to resolve to a B♭ , which
came when I realized that a 9th chord isn’t just gives the 13th/6th (the D) more of a suspended
a major triad with the 2nd added, but one with feel it doesn’t have in an F6 chord.
the 2nd and 7th added. An 11th chord is one I find not only the 13th chord a great sub-
with the 4th and 7th added. stitute for a 7th now, especially when it’s the
(Just as an aside: the fact 2+7=9 and 4+7=11 dominant resolving to the tonic, but I also love
here is an unrelated coincidence. An 11th is the 7th+3rd+13th/6th way of voicing it too.
4th+octave, but due to the 1-based indexing I know this is jazz 101, but it was a break-
used, you add 7, not 8.) through moment for me. n
Now yes, I’ve seen the theory books
where they show a C9 as C+E+G+B♭ +D, James Tauber is the founder and CEO of web startup
a C11 as C+E+G+B♭ +D+F and a C13 as Eldarion, Inc. When not working with software startups,
C+E+G+B♭ +D+F+A, but that really didn’t help websites and open source software, he is an aspiring
emphasize that it’s the existence of the 7th that composer, music theorist, mathematician and linguist.
makes the chord sound like (and be described James lives just outside of Boston with his wife but is
as) a C9, C11 or C13 respectively, instead of, originally from Perth, Western Australia.
say a Cadd2, Cadd4 or C6.

Reprinted with permission of the original author. First appeared in hn.my/chords (jtauber.com). Image by Mauricio Duque.

36  SPECIAL
  37
I n Philadelphia, I spent a
lot of time waiting for eleva-
tors. I inevitably paid a lot
of attention to the control
algorithms used by different eleva-
tors in different buildings.
ground floor from the floor they’re
at or up from ground floor to the
floor they should be in. This means
that approximately half the time,
elevator requests would occur at
the ground floor. A better design is
the following:
floor 6, but I’m not sure if there’s a
pattern here.
This makes a lot of sense. The
first elevator takes care of the case
where people want to go up from
floor 1. The second elevator takes
care of the case where people

Elevator
Example #2 would want to go down, and since
There are no more the elevator is at floor 6, the wait
than 10 floors time is reduced.
(I believe it was For small n and m, I really can’t

Algorithms
less) and about 6 think of a better solution than the
elevators. When one used in Example #3. For larger
an elevator is idle, n and m, though, it becomes more
it moves to the complicated:
ground floor and
Example #4
opens its door.
This building has about 38 floors
By Lisa Zhang This speeds things and at least 12 elevators. The
up a lot. Not only elevators are divided into 2 groups:
could you avoid the first group goes to floors up to
All elevator algorithms solve the waiting for the elevator to get to the 22. The second elevator skips all
same type of optimization problem: ground floor, you don’t even have the floors until floor 22, so it stops
if a building has n floors and m to press the button and wait for the at floors 22-38 (and the ground
elevators, how could we most effi- door to open! I thought this was a floor).
ciently move people up/down the great idea! An acquaintance pointed
It would be quite disastrous if
floors? I’m sure you already know out, though, that unsuspecting
elevators aren’t organized this way.
of the simple algorithm that every people might mistakenly think the
Imagine working on the top floor
elevator implements, but one can elevator is broken. Well then...
and having to wait for the elevator
definitely improve on this. Here’s The algorithm used in Example
to stop at every floor in between!
one improvement someone tried to #2 focuses a lot more on people
This elevator is designed to go
make: going up rather than people going
super fast from floor 1 to floor 22,
down. I think this makes sense.
Example #1 making things even more efficient.
Going up stairs takes a lot more
This building has 1 elevator and All of these examples are real.
effort than going down stairs, so
8 floors. The elevator was made What I don’t understand is why so
people are more likely to use the
to move back to floor 4 when it is many buildings do not have these
elevator to go up. However, in a
idle. optimizations built into their eleva-
building with more floors, more
tors. Implementing these changes
This is an intuitive solution. people would want to use the
cost almost nothing, and they can
Since there are n floors from where elevator to go down, so having all
save a lot of peoples’ time in the
people could call the elevator, the elevators on ground floor is not
long run. n
why not minimize the wait time going to help. Here’s a solution that
by making the elevator go back seems to work well:
Lisa is a pure math and applied math
to floor n/2 when it is idle? The
Example #3 student at the University of Waterloo.
problem with this argument is that She is passionate about data science,
This building has 2 elevators and
it assumes an elevator is equally data mining, data visualization and
~12 floors. It is programmed to
likely to be called from any of the entrepreneurship.
ensure that at least 1 elevator is on
n floors, which is not true. In most
the ground floor at any given time.
cases, people who use the elevator
The other elevator is often seen on Reprinted with permission of the original author.
would use it to either go down to First appeared in hn.my/elevator (lisazhang.ca)

38  SPECIAL
Dream. Design. Print.
MagCloud, the revolutionary new self-publishing web service
by HP, is changing the way ideas, stories, and images find
their way into peoples’ hands in a printed magazine format.

HP MagCloud capitalizes on the digital revolution, creating a


web-based marketplace where traditional media companies,
upstart magazine publishers, students, photographers, design-
ers, and businesses can affordably turn their targeted content
into print and digital magazine formats.

Simply upload a PDF of your content, set your selling price, and
HP MagCloud takes care of the rest—processing payments,
printing magazines on demand, and shipping orders to loca-
tions around the world. All magazine formatted publications
are printed to order using HP Indigo technology, so they not
only look fantastic but there’s no waste or overruns, reducing
the impact on the environment.

Become part of the future of magazine publishing today at


www.magcloud.com.

25% Off the First Issue You Publish


Enter promo code HACKER when you set your
magazine price during the publishing process.
Coupon code valid through February 28, 2011.
Please contact promo@magcloud.com with any questions.

You might also like