Just got code-pwned by my coworker yesterday. Below, you’ll see the difference between a mechanical engineer and a computer scientist’s approach to the same problem. The elegant solution is to use recursion: a function that calls itself.
The Brute Force Middle School QBasic Programmer Approach:
- function getPath($selected) {
-
- // search entire menu structure for key matching $menu_name
- // return array with each level of menu path
- // a recursive function would be cool here, beyond my ability -dw
-
- $level[0] = getMenu('all');
-
- foreach ($level[0] as $key[1] => $level[1]) {
- $path[1] = $level[1];
- $path[1]['key'] = $key[1];
- unset($path[1]['sub']);
-
- if (false) {
- // first level is not allowed to be a match
- } elseif (isset($level[1]['sub'])) {
- foreach ($level[1]['sub'] as $key[2] => $level[2]) {
- $path[2] = $level[2];
- $path[2]['key'] = $key[2];
- unset($path[2]['sub']);
-
- if ($selected == $key[2]) {
- break 2;
- } elseif (isset($level[2]['sub'])) {
- foreach ($level[2]['sub'] as $key[3] => $level[3]) {
- $path[3] = $level[3];
- $path[3]['key'] = $key[3];
- unset($path[3]['sub']);
-
- if ($selected == $key[3]) {
- break 3;
- } elseif (isset($level[3]['sub'])) {
- foreach ($level[3]['sub'] as $key[4] => $level[4]) {
- $path[4] = $level[4];
- $path[4]['key'] = $key[4];
-
- if ($selected == $key[4]) {
- break 4;
- } else {
- unset($path[4]);
- }
- }
- }
- }
- }
- }
- }
- }
-
- return $path;
The Killer Coding Ninja approach:
+
+ // {{{ getValues()
+ /**
+ * Returns the properties of a specific path segment, minus any children.
+ * @param {string} id The unique id of the path segment
+ * @param {array} values All properties of the path segment
+ * @return {array}
+ */
+ function getValues($id, $values) {
+ $retval = array('key' => $id);
+ foreach ($values as $key=>$value) {
+ // don't include any submenus
+ if ($key != 'sub') {
+ $retval[$key] = $value;
+ }
+ }
+ return $retval;
+ }
+ // }}}
+
+ // {{{ getPath()
+ /**
+ * Recursive function to return the path of a section.
+ * @param {array} menu The menu to iterate over
+ * @param {string} selected The id of the ending path segment to find
+ * @return {array|false}
+ */
+ function getPath($menu, $selected) {
+
+ foreach ($menu as $path_id=>$path_vals) {
+ if ($path_id == $selected) {
+ return array(self::getValues($path_id, $path_vals));
+ } else if (isset($path_vals['sub'])) {
+ $path = self::getPath($path_vals['sub'], $selected);
+ if ($path != false) {
+ array_unshift($path, self::getValues($path_id, $path_vals));
+ return $path;
+ }
+ }
+ }
+ return false;
+ }
+ // }}}
When Facebook rolled out their latest redesign a few months ago, I was simultaneously pleased and upset with the round avatar treatment, but couldn’t explain why. My right brain said “Kudos fb, so smooth, fillet the blue sky!” While my left brain said, “width: 49px; margin: 9px; carry the 7; error;”
As I’ve thought about it more, with both sides of my brain, I’m formulating a theory: In the context of bulleted lists, especially where the avatar is being used as a giant bullet, alignment is crucial. Our eyes need to verify that everything lines up, because if it doesn’t, that probably means something like a nested reply. In the x dimension, we need to confirm that the bullets are directly on top of each other. And in the y, the top of the bullet needs to be in line with the top of the text—the closer to a fixed interval the more pleasing the rhythm.
Corners make this quick check easier, fillets make this harder. Corners deliver a fixed point of comparison, fillets demand us to make two tangents.
When Twitter surpasses Facebook as the next social medium, I’ll attribute it to this seemingly insignificant design decision.
Next month, I start a brand new job at Mailtrust, a locally-created email hosting company in the University Mall, recently bought by Rackspace of San Antonio, a household name in web-serving. Since accepting the offer, I’ve been taking more notice of the features so many of us have come to love in Gmail. They just rolled out a few amazing upgrades through “Labs”. If you click on the green test tube beaker thing at the top of your Gmail screen next to your login name, you should be able to scroll down and turn these on:
To-do List - Dec 8 - In addition to making nested to-dos, you can convert email messages into to-do list items with a click and assign due dates to items.
Display Calendar and Docs in sidebar - Oct 27 - Another important step in synchronizing the fully integrated online office. Can’t wait until MS Office totally disappears.
This morning, while holding the door open for preschool at Blacksburg United Methodist Church, I was able to greet various parents and kids with “howdy”, “good morning”, “guten tag”, “buenos dias”, and “dobre dien”. I was waiting to see the mom to whom I could have said “salam alaikum”, but she must have come through another door. Now that I’m looking it up I’m realizing that I can also say “god morgen” (Danish), and I’ll probably need to ask the many Asian moms what I should say in their respective languages. A new dad also asked me a question in some kind of Scandinavian/Germanic accent.
Could the 18th century Scotch-Irish/German founders of Blacksburg United Methodist Church have possibly had the slightest idea how many cultures would be served by their preschool ministry? The door to this church is so wide. Kudos BUMC!
“There will be setbacks and false starts. There are many who won’t agree with every decision or policy I make as president. And we know the government can’t solve every problem.
But I will always be honest with you about the challenges we face. I will listen to you, especially when we disagree. And, above all, I will ask you to join in the work of remaking this nation, the only way it’s been done in America for 221 years—block by block, brick by brick, calloused hand by calloused hand.
What began 21 months ago in the depths of winter cannot end on this autumn night.
This victory alone is not the change we seek. It is only the chance for us to make that change. And that cannot happen if we go back to the way things were.”
President Elect Barack Obama
November 5, 2008
“We should never despair, our situation before has been unpromising and has changed for the better, so I trust, it will again. If new difficulties arise, we must only put forth new exertions and proportion our efforts to the exigency of the times.”
Since the GOP, by the nomination of John Sidney McCain III, has betrayed its conservative traditions of small government, fiscal responsibility, and non-interventionism, my intention has been to stay true to principle and write-in Ron Paul as my preferred Republican Presidential selection.
Looking into the specific details of a Ron Paul write-in, I’ve come to the conclusion that despite allegiance to the man and the camaraderie I feel with the 1.2 million others who voted for him in the primary, a write-in vote for him in Virginia would be counterproductive to the cause of liberty. My voting allegiance is first and foremost to the Constitutional principals he espouses and secondarily to the actual person who has been living them out in public service for the last 20+ years.
Although he is actually on the ballot in California, Montana, and Louisiana, most states, including VA, do not count write-in votes for candidates who have not filed with the state board of elections. Dr. Paul has not filed in VA, so a write-in vote will not register in any tally and will essentially be the same as a non-vote.
Though I can’t imagine CNN recognizing any result beyond Obama, McCain, and “other”, it will feel good to make the third column one vote larger. My prediction is 46%, 44%, and 10% respectively. Before accusing me of being a spoiler for McCain, please be sure to look up the number of registered Republicans who will be voting for Obama directly—I guarantee it will outweigh the spread!
So what’s a voter to actually do?
If I can’t vote for Ron Paul as my president, the next best option is to vote for the candidate Ron Paul endorses: Chuck Baldwin. He’s on a 100% Paul platform, has a decent rational faculty, and a reputable character. The only fault I can find with him is poor website design, a deficiency I’m not quick to overlook. In a recent debate with Ralph Nader, Chuck mentioned the Constitution party claims the highest number of registered voters outside of the two major parties, a number the Ron Paul contingency could triple.
Again, why not McCain or Obama?
There are four critical areas where McCain and Obama have essentially the same errant philosophy. On September 10, 2008, Ron Paul called a press conference of 3rd party candidates to present the following statement of contrast with the status quo provided by the two major candidates.
The Republican/Democrat duopoly has, for far too long, ignored the most important issues facing our nation. However, alternate candidates Chuck Baldwin, Cynthia McKinney, and Ralph Nader agree with Ron Paul on four key principles central to the health of our nation:
1. Foreign Policy
The Iraq War must end as quickly as possible with removal of all our soldiers from the region. We must initiate the return of our soldiers from around the world, including Korea, Japan, Europe and the entire Middle East. We must cease the war propaganda, threats of a blockade and plans for attacks on Iran, nor should we re-ignite the cold war with Russia over Georgia. We must be willing to talk to all countries and offer friendship and trade and travel to all who are willing. We must take off the table the threat of a nuclear first strike against all nations.
2. Privacy
We must protect the privacy and civil liberties of all persons under US jurisdiction. We must repeal or radically change the Patriot Act, the Military Commissions Act, and the FISA legislation. We must reject the notion and practice of torture, eliminations of habeas corpus, secret tribunals, and secret prisons. We must deny immunity for corporations that spy willingly on the people for the benefit of the government. We must reject the unitary presidency, the illegal use of signing statements and excessive use of executive orders.
3. The National Debt
We believe that there should be no increase in the national debt. The burden of debt placed on the next generation is unjust and already threatening our economy and the value of our dollar. We must pay our bills as we go along and not unfairly place this burden on a future generation.
4. The Federal Reserve
We seek a thorough investigation, evaluation and audit of the Federal Reserve System and its cozy relationships with the banking, corporate, and other financial institutions. The arbitrary power to create money and credit out of thin air behind closed doors for the benefit of commercial interests must be ended. There should be no taxpayer bailouts of corporations and no corporate subsidies. Corporations should be aggressively prosecuted for their crimes and frauds.
May God grant us all wisdom this Tuesday as we participate in the grand experiment of democracy. I’ll close my short treatise with some helpful quotations from a few interesting characters:
“It does not require a majority to prevail, but rather an irate, tireless minority keen to set brush fires in peoples’ minds.” Samuel Adams
“A powerful national government may encroach considerably upon the liberty of individuals as well as of the different States (by following an imperial policy), if only every citizen recognizes such measures as means for making his nation greater.” Adolph Hitler
“In questions of power, then, let no more be said of confidence in man, but bind him down from mischief by the chains of the Constitution.”
“I am for a government rigorously frugal and simple. Were we directed from Washington when to sow, when to reap, we should soon have no bread.”
“If the American people ever allow the banks to control the issue of their money, first by inflation and then by deflation, the banks and corporations that will grow up around them, will deprive the people of their property until their children will wake up homeless on the continent their fathers conquered.” Thomas Jefferson
“Government is not reason, it is not eloquence, it is force; like fire, a troublesome servant and a fearful master. Never for a moment should it be left to irresponsible action.” George Washington
“You cannot bring about prosperity by discouraging thrift. You cannot strengthen the weak by weakening the strong. You cannot help the wage earner by pulling down the wage payer. You cannot further the brotherhood of man by encouraging class hatred. You cannot help the poor by destroying the rich. You cannot keep out of trouble by spending more than you earn. You cannot build character and courage by taking away man’s initiative and independence. You cannot help men permanently by doing for them what they could and should do for themselves.” Abraham Lincoln
“A long habit of not thinking a thing wrong, gives it a superficial appearance of being right, and raises at first a formidable outcry in defense of custom. But the tumult soon subsides.” Thomas Paine
I just found this video on The Lab, a design firm working in the U.S. campus ministry communications field. Interesting facts and effective presentation.