2010-11-07

What's Point-free Programing?

Perm url with updates: http://xahlee.org/comp/point-free_programing.html

What's Point-free Programing?

Xah Lee, 2010-11-07

This page explains what's point-free programing, and how is it possible.

Discovered a new programing language. Factor (programming language). Quote:

Factor is a stack-oriented programming language created by Slava Pestov. Factor is dynamically typed and has automatic memory management, as well as powerful metaprogramming features. The language has a single implementation featuring a self-hosted optimizing compiler and an interactive development environment. The Factor distribution includes a large standard library.

What's interesting is that it's called Concatenative programming language. Quote:

A concatenative programming language is one in which all terms denote functions and the juxtaposition of terms denotes function composition.[dead link][1] The combination of a compositional semantics with a syntax that mirrors such a semantics makes concatenative languages highly amenable to algebraic manipulation and formal analysis.[2]

Basically, it's another interesting advance of functional programing. Now, every “word” is a function, and a sequence of words effective means function chaining or composition. So, it's like a strict postfix or prefix syntax but without operators. (See: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Nested Notations)

Point-free programming

Another new jargon i learned is Point-free programming (aka “tacit programing”, “pointless programing”). Here's a quote:

Tacit programming is a programming paradigm in which a function definition does not include information regarding its arguments, using combinators and function composition (but not λ-abstraction) instead of variables. The simplicity behind this idea allows its use on several programming languages, such as J programming language and APL and especially in stack or concatenative languages, such as PostScript, Forth, Joy or Factor. Outside of the APL and J communities, tacit programming is referred to as point-free style[1], or more pithily as pointless programming. This is because of the relation between how definitions are done in pointless topology and how they are done in this style.

Basically, what that means is the elimination of formal parameters in function definitions. (similar to what Combinator notation is trying to do.)

How is It Possible to Not Have Variables in Function Definition?

here's a typical form of a function definition (using javascript):

function f(x,y) { return x+y;}

How is it possible to eliminate the variables? How do you specify where the argument goes?

Answer: thru some “tricks” of syntax, and theory of function.

Allow Functions of 1 Parameter Only

First, is to allow definition of functions of 1 parameter only. And all functions in the lang are all just single-parameter functions. This is done in 2 basic ways.

Multi-parameter as a List

The most simple way, is to consider multi-parameters function as function of a single parameter of a list. So, for example, if you need to define 「f(x,y)」, you can define it as a function that takes a list 「f(mylist)」, where the “mylist” is a list of 2 elements.

Function De-composition (aka Currying)

We'll discuss this later, below.

Linear Notation

Once the language allows only function of 1 parameter, then the syntax can be made into a linear form, either as prefix or postfix, and the paren to mark parameters are no longer necessary. The following are examples of linear syntax.

The most familiar linear notation is unix pipe. For exmaple:

x | h | g | f

means 「f(g(h(x)))」 or in lisp nested notation as 「(f (g (h x)))」.

In other functional languages, this can be written simply as:

f g h x

or

x h g f

In the above, the space is a implicit operator, meaning function application.

In some lang with object oriented flavor, a “dot” syntax is popular (e.g. javascript, ruby, java), like this:

x.h.g.f

or like this (perl):

x -> h -> g-> h

Those starting with the argument x and apply functions from left to right (e.g. 「x h g f」), are postfix notations, because argument comes first, functions come after. Those starting with argument at the right (e.g. 「f g h x」) are prefix notations. (See: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Nested Notations)

Here's Mathematica's prefix syntax:

f @ g @ h @ x

And the following is Mathematica's postfix syntax:

x // h // g // f

Dropping the Parameter

Now, if a functional lang allows only functions of one single parameter, and if its syntax is a uniform prefix or postfix linear syntax, then a function definition may be like this in postfix notation:

# square function

or prefix notation:

function square #

This defines a function that squares a number. That is, it computes “x^2”. Now, notice, that every function definition will always have a dummy variable at the end of the line. So, it is syntactically redundant. We can simply drop it, and change the semantics of the “function” keyword to always assume there's a parameter.

Function Decomposition (Currying)

There is another technique for point-free programing syntax, by the theory of function decomposition. That is, instead of requiring multi-parameter function to take a list as argument, the lang automatically decompose any function of multi-parameter into a sequence of 1-param function application. (aka function chaining)

Suppose you have a function of 2 parameters 「(f x y)」 (using lisp syntax here). Here, the “x” and “y” are called formal parameters (aka dummy variables). In a trivial math theory, any function of 2 parameters can be reduced to sequential application of functions of 1 parameter. That is, for any function f of 2 parameters, there exist functions g and h, such that 「(f x y) = ((g x) y)」, where the result of 「(g x)」 is a function we'll call “h”, and result of 「(h y)」 will equal to 「(f x y)」.

It's hard to think how could one concretly define g, or what g could be in some abstract function mapping model, but it's easy to think of it as the result of evaluating f with one of its parameter assumed as a constant. When you evaluate f with one of its parameter given, say 「(f 2 y)」 you get a function with 1 single parameter the y. That's your h, which is g evaluated at 2: 「(g 2)」.

(The process of de-composing function is sometimes called “currying” in computer science. (See: What is Currying in a Computer Language?))

By this argument of reducing 2 parameters to 1, it follows that a function of n parameters can be expressed by a composition of functions that all have just 1 parameter. In other words, functions with 1 parameter is all you need, when thinking about the theoretical aspects of functions.

Languages like Haskell and OCaml, functions of multiple parameters are automatically de-composed into a sequence of functions of 1 parameter, in the syntax as well as at compiler level. In fact, the syntax used to define multi-param function, is just a variant syntax that is syntactically equivalent to the syntax for sequential application functions of 1 parameter. (See: OCaml Tutorial: Function )

So now, the task of making point-free syntax for function definition, is reduced to making a syntax for functions of 1 variable, but without using a symbol to represent dummy variable at all. This is now trivial, because you simply don't need to write that dummy variable, and always assume there's a variable to go with the function.

For example, in 「(function (x) (g (f x)))」, we have in traditional math notation 「 f(x) := g(f(x))」. Now, since all functions have just 1 parameter, we simply don't need to write it anymore. So, we write 「(function (g (f)))」, and it's assumed that in the deepest level it's always a function, and some argument is to be fed to it.

In functonal langs like Haskell, OCaml, Mathematica, they have prefix or postfix syntax. For example, 「g f x」 means 「(g (f x))」. In this linear syntax, with point-free style, you simply don't need to write the x anymore, because it's always just the last part. You automatically assume the last part will be a argument. So you simply write 「g f」.

Summary

Here's a few things to remember what “point-free programing” is:

  • It is about a particular syntax for function definition.
  • When defining a function, no symbol is used for function parameter.

And this syntax is made possible by:

  • All functions in the lang are functions of one parameter only.
  • Support linear notation. (prefix or postfix)

And allowing function of 1 parameter only is made possible by:

  • Multi-param are just functions of 1 param of a list (APL, J).
  • Support function decomposition (OCaml, Haskell)

花样的年华 (Age of Blossom)

Perm url with updates: http://xahlee.org/Periodic_dosage_dir/sanga_pemci/hua3yang4nian2hua2.html

花样的年华 (Age of Blossom)

Xah Recommends:
iPod Nano
iPod Nano
.

Xah Lee, 2005-04, 2010-11-07

Title: 花樣的年華 (from movie 《长相思》)
Lyrics: 范烟橋
Music: 陈歌辛
Date: 1946
Singer: 周璇
Translation: 李杀 (Xah Lee)
花样的年华, 
月样的情深 

冰雪样的聪颖, 
美丽的生活, 

多情的泉水, 
圆满的家庭 

墓地里的孤岛, 
笼罩着残雾愁云 

可爱的祖国, 
几时我能够投近你的怀抱 

门前的雾消云散, 
重见你现出光明 

花样的年华, 
月样的情深 
an age of blossom
affectionate as the moon

bright as the snow
splendid is living

caring is spring water
in union are families

the lonely islands in the graveyard,
shrouded in torn clouds and grief-stricken mists 

O my dearly beloved country,
when would i be in your embrace

to see clouds dissipate
and see you shine again

an age of blossom
affectionate as the moon

Clip of from the movie 长相思. Amazon music at amazon

The Poem

Note the sudden twist in this poem.

I was listening to this song and like it fairly and have been listening to it repeatedly. Though, i was not quite sure what it is singing. I thought it is a song for lovers. Then, i searched and found the lyrics.

Note how the lyrics made a about-face at line 7: “the lonely islands in the graveyard...” This immediately changed the nature of the poem. All lines before that is tame and serene. The “torn clouds and grief-stricken mist” drives the misery into the readers in a terse dismay. Then, the next line “O my dearly beloved country...” is another sharp twist that immediately adds the context, to the misery of the previous line, and as well as fixing the beginning six serene lines into a sublimely beautiful quality by context. Such lines as these (8th, 9th) have incredible weight, making this a heavy poem.

Now if we go back and look at the beginning serene lines. “An Age of Blossom, affectionate as the moon”. When lives are at stake, one does not wish to have lots of money or fancy cars, but as simple as a loving and prosperous society. “Bright as snow, splendid is living”. How the good things are chosen to be cited tells us a lot about the wisher's situation. Note the way it is said: “splendid is living”, as oppose to, say, “all are rich”, or “life is great”, or “party every day”. The next line “caring is spring water”. This is a critical verse, because of all needs and desires in a human animal, nothing is more precious than clean, drinkable water. This fact cannot be known until subsistence is on the brink. Then “in union are families”, again, a universal yearning not to surface in peace time.

Note: there's some discrepancies in the lyrics that i wasn't sure which is correct. In the line 月样的情深, alternative version found on the web is 月样的精神, which seems to be the phrase sung. Also, i used 冰雪样的聰颖 and there's 冰雪樣的聰明, and i used 多情的泉 水 and elsewhere i've found 多情的眷顾. In all cases, i prefer the one i used. Not sure which ones are the original lyrics. If you know, please let me know.

Wartime China

This song says so much. It is sung by 周璇 (Zhou Xuan, 1918-1957), a Shanghai superstar. During the early 1900s, China was in a state of devastation, besieged by Western invasions, World War Two with Japan , and more civil wars. Modern people in affluent states couldn't imagine this, especially the fat WASPs in USA. In such a era, one lives in blood, in famine, in broken families, missing members and limbs, in perpetual flight and fear. This song is very sad, sung by a feminine high-pitched style idiosyncratic to Shanghai. In this era, there are many such songs like this, usually in a extremely beautiful, serene, tune, and the lyrics are often exceedingly sad in a poetic way. (many of these are de facto poems) The contents are often about separation, or the wish for peace and union. Many songs of sexual love are also in this bleak, masochistic depressive style.

As time moved on, eras and sentiments come and go. Songs like this do not get written as much today, but the devastation of war and misery have left a indelible mark in Chinese people, still can be seen in their thoughts, aspirations, culture, and songs today. (after Nationalist/Communist Civil War, then China is devastated by Great Leap Forward and Cultural Revolution of Mao).

It is interesting a psychological phenomenon, where one will like what's deep in a person's life. As in, if one suffers thru hardship, one tends to like songs that sang their wishes and dreams. A culture sacked by prolonged war, will not, for example, develop into Rock'n'Roll or Heavy Metal. In other words, different era and cultural make up instigates its music. Here, we might presume that Heavy Metal, was born in a environment of rich boredom and modern technology.

baby sitting alone in a rail track among destruction

A very popular photo, of a baby sitting amidst destruction, published by LIFE magazine . (photo may depict Shanghai in 1937. The LIFE Mag publication date may be 1937-10-04.)

Singer Zhou Xuan

Zhou Xuan

Photo of the singer, Zhou Xuan (周璇 1918-1957).

Zhou Xuan herself is a interesting story. She was a orphan, and throughout her life she searched for her parents to no avail. Although a superstar, she did not live a happy life, and ended up in a mental institution and died young. For more info about the singer, see Zhou Xuan (周璇)

For some other wartime era songs of this period, see:

Apocalypse Now; Ride of the Valkyries

Perm url with updates: http://xahlee.org/Periodic_dosage_dir/skina/apocalypse_now.html

Apocalypse Now; Ride of the Valkyries

Xah Lee, 2010-11-06

apocalypse now poster

Apocalypse Now amazon

Apocalypse Now (1979).

The helicopter scene.

The music is “The Ride Of The Valkyries” amazon by Richard Wagner.

What is a Valkyrie? Quote:

In Norse mythology, a valkyrie (from Old Norse valkyrja “chooser of the slain”) is one of a host of female figures who decide who will die in battle.

Valkyrie on horse

«Valkyrie On Horse Statue of a warlike valkyrie, riding a horse and carrying a spear. Labeled as “SINDING VALKYRIE” and located in a roadside park in Copenhagen, Denmark.» Source

Walkyrien by Emil Doepler

Walkyrien by Emil Doepler. Source

2010-11-06

Llorando (Crying) from Mulholland Drive

Perm url with updates: http://xahlee.org/Periodic_dosage_dir/sanga_pemci/llorando_mulholland_drive.html

Llorando (Crying) from Mulholland Drive

Xah Recommends:
iPod Nano
iPod Nano
.

Xah Lee, 2010-11-06

There is a very emotionally disturbing song, “llorando”, from the movie Mulholland Drive (2001)

The song is so touching that when it is playing, it makes me listen intently, and it changes my brain's state into a deep philosophical sorrow on human suffering, and often i broke into silent tears all over my face.

While in 2001 when Mulholland Drive with this song came out, i researched on the web who's the singer. I found the singer's site with email, and sent her $1 thru paypal. (1 dollar was small, but in my opinion is the right way to express my deep appreciation. At the time, it's the dot com era with lots of new visions of web stores and economy, and the concept of Micropayment is still alive. Though, i think she probably doesn't even know what paypal is, and i doubt she actually got my dollar.)

“Llorando” from the movie Mulholland Drive, sung by Rebekah Del Rio.

The song “Llorando” is a spanish version of the song “Crying” by Roy Orbison (1936-1988).

“Crying” by Roy Orbison. amazon

Here's the lyrics.

Yo estaba bien por un tiempo,
volviendo a sonreír.
Luego anoche te vi
tu mano me tocó
y el saludo de tu voz.
Y hablé muy bien de tu
sin saber que he estado
llorando por tu amor.

Luego de tu adiós sentí todo mi dolor.
Sola y llorando,
llorando, llorando, llorando
No es fácil de entender
que al verte otra vez
Yo seguiré llorando

Yo que pensé que te olvidé
pero es verdad es la verdad
que te quiero aún más,
mucho más que ayer.

Dime tú qué puedo hacer
no me quieres ya
y siempre estaré
llorando por tu amor (x2).

Tu amor se llevó
todo mi corazon
y quedo llorando
llorando
por tu amor.
I was all right for a while,
I could smile for a while
But I saw you last night
you held my hand so tight
As you stopped to say hello
Oh, you wished me well, you couldn't tell
That I've been crying over you, crying over you

And you said, so long
Left me standing all alone
Alone and crying, crying, crying, crying
It's hard to understand but the touch of your hand
Can start me crying

I thought that I was over you
But it's true, so true
I love you even more than I did before

But darling, what can I do
For you don't love me and I'll always be
Crying over you, crying over you

Yes, now you're gone and from this moment on
I'll be crying, crying, crying, crying
Yeah, crying, crying over you

Here's a mixed version, with scenes from the movie.

Mulholland Drive: Llorando/Crying Mix

Mulholland drive 2

“Mulholland drive” amazon

I bought the Mulholland Drive soundtrack too. All the songs are fantastic. amazon

What is a Tech Geeker?

Perm url with updates: http://xahlee.org/UnixResource_dir/writ/tech_geeker.html

What is a Tech Geeker?

Xah Lee, 2008-05-03, 2010-11-06

Definition

tech geeker: (noun) A elite programer nerd who severely lacks literacy of social sciences yet persistently loud of his opinions on many social issues related to programing, such as language popularity, pros and cons of GUI, software engineering practices, software license issues, IT industry practices, ethics of corporations.

Are You a Tech Geeker?

  • Are you male?
  • Are you proficient in a computer language or technology? perhaps several?
  • Is computer coding or sys admin your way of getting food?
  • Do you love the term “hacker”? Have you been called a hacker?
  • You do not have a degree in history, arts, philosophy, law, economics, communication, psychology, or any credential from the field of social sciences.
  • You are keen on social issue of software. You read slashdot and groklaw and reddit and hacker news.
  • You have strong opinions on software licensing, the concept of software freedom, user interface design, how social media should or should not be (newsgroups, internet, blog, youtube) and how people should use them. You have strong opinions on software design, computer language design, and opinions on the cause and value of popularity.
  • You are loud about your opinions on social issues of software. You think your opinions are correct in some technical way.
  • You can effortlessly name 20 top computer scientists or celebrity programers of this decade.
  • It'd be hard pressed for you to name 5 historians, philosopher, or social scientists of this century.
  • You are aversive to usages like “u” (you), 4 (for), omg, wtf, lol. You find them annoying and childish.
  • But you use and love argots such as the following: troll, plonk, YMMV, IANAL, RTFM, RMS, *nix (as opposed to “unix”), unixen (instead of unixes or unices), emacsen (as opposed to “emacs user” or (aghast) “emacser”), lisperati (vs just “lisper”).
  • Do you love to debate on grammar sometimes? such as split infinitives, preposition.
  • You never in your life ran a business, operated a store, or started a organization.

A Letter to Tech Geekers

Dear George,

You and Rainer, are the epitomy of what i'd call the tech geeking morons (or just “tech geekers”), in my eyes. That's the type of people in computing industry, who can't see the gist of things, the context of things, the purpose of things, but perpetually bury their heads deep in technical obscurity.

(one quick way to picture this class of folks is to think of linuxers, in the context of software usability (imagine, the worse scenario, if your grandma calls in tech support asking about some problems with the computer, and a tech geeker on the other end is yelling about jumpers and drivers and kernel space, running out of patience, quite frustrated and aghast at the level of ignorance and stupidity of people in the world. Everything about the jumpers, drivers, kernel, and their relations, and relevance to the grandma's problem the tech geeker speaks of, is technically correct, and we marvel at the tech geeker's knowledge at the workings of computing machine. But his inanity and ineffectually, bedazzles us.))

This class of folks, typically are slightly above average programers, and some are academics. Most have been in the industry for a while. Also, a significant percentage of them are a subset of studious college students studying computer science. Put it in another way, these tech geekers are a certain subset of elite programers, who pride in calling themselfs “hackers”.

The tech geekers, their thinking and views are inline with orthodox wisdom. They are also keen with the latest thinkings and trends and thoughts, and pride themselfs in this fact of fashionability (but conspicuously aversive to fads and fashion.). However, they have very little ability in creativity, or perspicacity. Their IQ is often above average, but typically are not outstanding. Also, their ability to analyze mathematically is low, possibly below average among their intellectual peers. They never possess the acumen typical of a mathematician.

However, a notable ability of tech geekers, is their tolerance for dense, incomprehensible, obscure, technicalities. (perhaps that's is also why they are good in their profession: coding) Specifically, the ability to drill down dense technical details, often at the expense of forgetting, discarding, or not understanding the context, whole design, or original purpose. More often than not, a hallmark of their foolhardiness caused by their tech drilling propensity, is that they often create the most unusable software.

I have been in comp.lang.lisp for 9 years. I've been posting very actively in the past few months. You know me, i know you, we know each other to some degree. So, instead of starting another perhaps ultimately tiresome and useless argumentation here about some computer science or programing subject, i thought i'd write something else, just to be fresh, about what i think of your cohorts as a class.

The usenet newsgroup comp.lang.* hierarchy, is in fact a mecca for this tech geeker class i speak of. In contrast, the tech geekers are also almost never mathematicians, inventors, scientists. (For that matter, nor ever sociologists, historian, philosopher, or great writers. O, and never artists of any standing.) I think a good alternative epithet to convey the characteristics of this class of people, is “Engineers”, in particular of the nerdy, uncreative, brute force, subset.

Another tech geeker who was a regular here comes to mind. His name is Christopher. I wrote of him, in 2001, here: Unix And Literary Correlation.

2010-11-05

Cyborg RAT 5 gaming mouse

2 months ago, i found a fantastic mouse:

Cyborg RAT 5 gaming mouse 2-s

Cyborg RAT 5 gaming mouse.

But reading amazon reviews today, it seems to have its problems. For video review and detail, see: Best Input Devices (Jog/Shuttle, Touchpad, Cyborg Mouse, Pen Tablet).

2010-11-04

真善美 (Truth, Virtue, Beauty)

Perm url with updates: http://xahlee.org/Periodic_dosage_dir/sanga_pemci/stace_vrude_melbi.html

真善美 (Truth, Virtue, Beauty)

Xah Lee, 2005-04, 2010-11-04

Title: 真善美 (Truth, Virtue, Beauty)
Singer: 周璇 Zhou1 Xuan2 (1918-1957)
Lyrics: 李雋青
Music: 侯湘 (李厚襄(1916─1973))
Source: 《鸞鳳和鳴》電影插曲
Translation: 李杀 (Xah Lee)
真善美, 真善美,
它们的代价是脑髓, 
是心血是眼泪,
哪件不带酸辛味?

真善美, 真善美,
它们的代价是疯狂,
是沉醉是憔悴,
哪件不带酸辛味?

多少因循多少苦闷,
多少徘徊,
换几个真善美?

多少牺牲多少埋没,
多少残毁,
剩几个真善美?

真善美, 真善美,
它们的欣赏究有谁?
爱好的有谁?
需要的有谁?
几个人知这酸辛味?
Truth, Virtue, Beauty; Truth, Virtue, Beauty
They are the nervous breakdowns
Sweat and tears
How do they taste?

Truth, Virtue, Beauty; Truth, Virtue, Beauty
Their cost is insanity
Intoxication, and despondency
Are they not suffering?

How many failings, the dejections
and futilities
Buys how much truth, virtue, and beauty?

What sacrifices, oblivion
What wreckage
For how much truth, virtue, and beauty?

Truth, Virtue, Beauty; Truth, Virtue, Beauty
Just who appreciates them?
Who loves them?
Who needs them?
Have you tasted their costs?

God help me, for, i'm expiring, but i refuse to desist. If i'm deranged, so i am.

For some bio info about the singer, see Zhou Xuan (周璇). She is a orphan, is the biggest Asian superstar, and she died of a nervous breakdown at age 39.

Emacs Lisp Power: Text-Soup Automation

Perm url with updates: http://xahlee.org/emacs/elisp_text-soup_automation.html

Emacs Lisp Power: Text-Soup Automation

Xah Lee, 2010-11-03

This pages showcases a example of emacs lisp power, in dealing with text-soup processing that requires human interaction.

The Problem

I have a favorite movies page at Xah's Favorite Movies.

The page contain about 70 amazon links like this:

<a class="amz" href="http://www.amazon.com/dp/B000055Y0X/?tag=xahh-20">amazon</a>

It's a mystery what the link is, unless you visit the link. I want them to be like this:

<a class="amz" href="http://www.amazon.com/dp/B000055Y0X/?tag=xahh-20" title="Dr. Strangelove; movie">amazon</a>

It's a thorny problem. You have to write a script to fetch the amazon page then parse the result to get the product title then insert them at the right place. Amazon may block crawlers, and even if not, the parsing of the complex html to extract the title may take hours to code. You don't even know if product title is clearly marked by a specific tag.

Luckily, my page is written so that for each amazon link, the movie title is within the paragraph, preceding the link, and usually in the form of a Wikipedia link. Here's a sample paragraph:

<p><a href="http://en.wikipedia.org/wiki/To_sleep_with_a_vampire">To sleep with a vampire</a>
 (1993) ◇ Director: Adam Friedman. ◇ I love
stripper Nina (Charlie Spradling). I love her looks, love her
attitude, love her mannerism, love her despondency and destitute. I
love her fairly big tits too. She's the dark haired angle.
<a class="amz" href="http://www.amazon.com/dp/B0000648YN/?tag=xahh-20">amazon</a>
</p>

Solution

So, the plan is to write a elisp script. Here's the basic steps:

  • 0. open the file
  • 1. find the amazon link.
  • 2. search backward for the Wikipedia link that contains the movie title.
  • 3. insert the “title” attribute in the amazon link.
  • Repeat steps 1 to 3.

This is a job perfect for elisp, and can be done interactively, far better than any perl, python, ruby, due to emacs lisp's buffer system. I imagine it's a 20 min scripting job. Here's the code:

;; -*- coding: utf-8 -*-
;; 2010-11-03
;; add 「title="product title"」 to amazon links on a html page.

;; rough steps:
;; find amazon link of the form
;; <a class="amz" href="http://www.amazon.com/dp/B000055Y0X/?tag=xahh-20">amazon</a>

;; find a Wikipedia link above it, of this form
;; <a href="http://en.wikipedia.org/wiki/Dr._Strangelove">Dr. Strangelove</a>
;; extract the movie title

;; insert the attribute
;; title="..."
;; into the amazon link. Like this
;; <a class="amz" href="http://www.amazon.com/dp/B000055Y0X/?tag=xahh-20" title="Dr. Strangelove; movie">amazon</a>

(setq outputBuffer "*xah output*" )
(with-output-to-temp-buffer outputBuffer 

  (find-file "~/web/xahlee_org/Periodic_dosage_dir/skina/nelci_skina.html" )
  (goto-char 1)

  (while 
      (search-forward-regexp "<a class=\"amz\" href=\"http://www.amazon.com/dp/[^\"]+?\">amazon</a>"  nil t)

    (progn 
      ;; set points for amazon link
      (backward-char 11)
      (setq amzLinkInsertPoint (point) )

      ;; get title from preceding Wikipedia link
      (search-backward-regexp "<a href=\"http://...wikipedia.org/wiki/[^\"]+?\">\\([^<]+?\\)</a>")
      (setq titleText (match-string 1 ) )

      (when (yes-or-no-p titleText) 
        (goto-char amzLinkInsertPoint)
        (insert (concat " title=\"" titleText "; movie\"")) )
      )

    (progn (print "not found"))
    )
  
  (princ "Done deal!")
  )

Emacs is fantastic!

(In practice, the job took close to one hour to complete, counting all mistakes, and whatnot when actually coding. For example, in the process i noticed that 2 of the amazon links are preceded by Wikipedia links that are not actually related to the amazon link, and this and other miscellaneous irregularities are actually expected. The code above is actually sligthly cleaned up, but is still meant to be one-time-use code. It always looks easy when seeing someone's published code than actually coding from scratch.)

There are few hundred amazon links on my site of 4k pages. They all need a similar fix. The job will be slightly different, because the links are arbitary product or book names. But typically, the product name is usually demarked like this 《book title》 or “song cd” or some other way in the text before the link, but not always. Also, some amazon links may already have a “title” attribute. The point is that it's a text-soup situation and requires human baby-sitting for correct completion, and elisp excels at this. Tomorrow or so, i'll write a elisp script to fix these few hundred amazon links among 4k pages. Total time for the task is expected to be 2 to 4 hours.

2010-11-08

Aaron Culich wrote a elisp script that does the same thing but using several interesting techniques, among them is using DOM/XPATH in elisp to process html, and also yahoo's Yahoo! query language (YQL), both of which i don't have any experience with. His code can be seen here: github.com. Here's a excerpt of his comment:

I often find myself having to do some xpath myself and since want to do this sort of thing inside emacs myself from time to time instead of busting out python, so I've been playing around with your Dr. Strangelove movie example (a favorite movie of mine, btw) using emacs and xpath. You can find my results here: https://github.com/aculich/misc-elisp

I tried using 3 methods.

  • (1) First with pure elisp using the dom/xpath stuff on emacswiki. Unfortunately the processing is broken and at least in some of the cases I tried, gobbled up all available memory. I didn't look at it closely, but I have a feeling the elisp implementation would a fair amount of work to get working and even still would probably not be very fast for large documents. Also, you still probably want to run the input through tidy first so that you're not dealing with broken HTML (which it seems nearly every website in the universe has).
  • (2) Using a few handy unix utilities not uncommon on most systems: wget, tidy, and xmlstarproc. You'll need to first install those before using this method.
  • (3) Yahoo's YQL web service is handy for this sort of thing. And the nice thing is that if you need to process a large document, all of it will be done remotely.

#3 is the default method that I use in my elisp code since it only relies on modules that ship with most recent versions of emacs (specifically json.el and url.el and w3m.el) and doesn't require any special binaries to be installed the way #2 does.

Also, since #1 was so broken I did not include any example implementation for it. Anyway, if you find the code useful, let me know.

Fix Defective Keys in Comfort Curve Keyboard

Perm url with updates: http://xahlee.org/emacs/ms_keyboard/ms_comfort_curve_keyboard_2000_fix.html

Fix Defective Keys in Comfort Curve Keyboard

Xah Lee, 2010-10-18, 2010-11-03

If you bought a Microsoft Comfort Curve Keyboard 2000, and some keys started to fail, this page shows you how to fix it.

Microsoft Comfort Curve keyboard 2000

Microsoft Comfort Curve keyboard 2000. amazon

This keyboard is known for key-failure problem. For detail, see: Microsoft Comfort Curve Keyboard 2000 Review.

What's the Cause of The Problem?

Static Built-Up?

There's a guy SMApple who wrote a post here: Source. He says the problem is electric static built-up inside the keyboard. Quote:

The problems with this MS comfort curve keyboard starts when at random some of the keys stop working, it dose not matter how hard you press or for how long, they just wont work, this problem is due to static charge build up on the thin plastic sheet/mat inside the keyboard that has electric circuit printed on them. This new keyboard technology is wonderful and superb, the keyboard is sheer pleasure to use when it is working, when you press the key it is quite soft and silent, so, it wont wake the baby up. it has no mechanical parts inside keyboard, it has lots of small soft plastic **** on plastic matt that you press with your keys so they don’t make any sound, same as in your average Remote control. Even in this year 2010 this plastic sheet circuit board needs lots of improvement yet, because it suffers from static charge build up. Microsoft seems to have opted for the cheapest quality non expensive plastic sheet circuit mat for their keyboard, probably made from some cheep biodegradable recycled plastic condoms, these cheep mats always have tendency to hold onto electric charge and wont discharge when they should, and consequently cut off circuit connections to the keys, same technology that is used in majority of the household remote controls, and ,so, the reason why Remote keys tend to stop functioning after a while.

His solution is to spend 15 min to open up the keyboard to discharge it, whenever keys starts to not working.

Membrance Mis-Alignment?

Another guy, at Source, claims it's membrance mis-alignment.

2010-10-18 Reviews on newegg also has lots people saying that the keys doesn't work. Source

The bottom line about the defect is that the failure is not consistent. Sometimes some keys just work perfectly.

Beware of Garbage Advise

There are lots of sites that give garbage advices about this keyboard. They'll say update the driver, clean the keyboard. These are not the problems of this keyboard. The problem is with the keyboard hardware itself. Also, return for replacement will probably not help. Lots of reports that says new replacement are still bad. Again, the problem is with this keyboard's design.

How to Fix This Keyboard

Just learned from a friend, a good method of fixing this keyboard. Whenever some key doesn't work, take the keyboard up and hold it with one hand, and use the other hand to give the keyboard a slap with big impact. WHACK! Then, the defective keys will all work again! Seriously. She told me this, then i immediately plugged in the keyboard, checked that x is still defective, then i whacked it, and it immediately workd! We were laughing about this.

This is a fantastic solution. Because this is a really great keyboard, and now you can actually make it work.

2010-11-03

Emacs Lisp Power! amazon-linkify

Perm url with updates: http://xahlee.org/emacs/elisp_amazon-linkify.html

Emacs Lisp Power! Transform Text Under Cursor

Xah Lee, 2010-11-03

This pages showcases the power of emacs.

Just updated a elisp command.

(defun amazon-linkify ()
  "Make the current url or region into a Amazon link.

; examples of Amazon product url formats
http://www.amazon.com/Cyborg-R-T-Gaming-Mouse/dp/B003CP0BHM/ref=pd_sim_e_1
http://www.amazon.com/gp/product/B003CP0BHM
http://www.amazon.com/exec/obidos/ASIN/B003CP0BHM/xahh-20
http://www.amazon.com/exec/obidos/tg/detail/-/0877796335/

Example output:
<a class=\"amz\" href=\"http://www.amazon.com/dp/B003CP0BHM/?tag=xahh-20\" title=\"Cyborg R T Gaming Mouse\">amazon</a>

For info about the amazon id in url, see:
URL `http://en.wikipedia.org/wiki/Amazon_Standard_Identification_Number'"
  (interactive)
  (let (asin p1 p2 meat productName tmpBds)
    (if (region-active-p)
        (setq p1 (region-beginning) p2 (region-end))
      (progn
        (setq tmpBds (bounds-of-thing-at-point 'url) )
        (setq p1 (car tmpBds) )
        (setq p2 (cdr tmpBds) )
        ))
    ;; get the text
    (setq meat (buffer-substring-no-properties p1 p2) )

    ;; extract the id from text
    (cond
     ((string-match "/dp/\\([[:alnum:]]\\{10\\}\\)/" meat) (setq asin (match-string 1 meat) ))
     ((string-match "/gp/product/\\([[:alnum:]]\\{10\\}\\)" meat) (setq asin (match-string 1 meat) ))
     ((string-match "/ASIN/\\([[:alnum:]]\\{10\\}\\)" meat) (setq asin (match-string 1 meat) ))
     ((string-match "/tg/detail/-/\\([[:alnum:]]\\{10\\}\\)/" meat) (setq asin (match-string 1 meat) ))
     ((and 
       (equal 10 (length meat ) )
       (string-match "^\\([[:alnum:]]\\{10\\}\\)$" meat)
       )
      (setq asin meat ))
     (t (error "no amazon ASIN found"))
     )

    ;; extract the product name from url, if any
    (cond
     ((string-match "amazon\.com/\\([^/]+?\\)/dp/" meat) (setq productName (match-string 1 meat) ))
     (t (setq productName "") (message "no product name found" ) (ding))
     )

    ;; replace dash to space in productName
    (setq productName (replace-regexp-in-string "-" " " productName) )
 
    (delete-region p1 p2)
    (insert
     "<a class=\"amz\" href=\"http://www.amazon.com/dp/"
     asin "/?tag=xahh-20\" title=\"" productName "\">amazon</a>")
    (search-backward "\">")
    ))

Sample Use

For example, when i'm writing about keyboards or any tech product Kindle, Apple Macbook, iPad, or movie reviews, i go to amazon and read reviews, then press 【Ctrl+l】 to place cursor on the url field, 【Ctrl+c】 copy, press F6 to switch me to emacs, paste. I get a url that may be in any of the following form:

http://www.amazon.com/Cyborg-R-T-Gaming-Mouse/dp/B003CP0BHM/ref=pd_sim_e_1
http://www.amazon.com/gp/product/B003CP0BHM
http://www.amazon.com/exec/obidos/ASIN/B003CP0BHM/
http://www.amazon.com/exec/obidos/tg/detail/-/B003CP0BHM/

then, i press a button, it become a link with this uniform format:

<a class="amz" href="http://www.amazon.com/dp/B003CP0BHM/?tag=xahh-20" title="Cyborg R T Gaming Mouse">amazon</a>

With proper CSS it shows in browser like this: amazon.

The uniform format is important, because it allows me to systematically process them in the future. For example, possibly one day i need to make them into some particular HTML Microformat, or get a list of all amazon links with product names.

Similar Uses

This snippet is simple to understand, shows a common and powerful use of elisp, is great for learning elisp. I have 30 other similar “linkify” commands. They are:

Transform URL Into Links

The following transform a URL into a link of particular format for my site:

  • amazon-linkify
  • blogger-linkify
  • wikipedia-linkify
  • full-size-img-linkify
  • image-linkify
  • nks-linkify
  • source-linkify
  • xah-all-linkify
  • xah-curve-linkify
  • xah-file-linkify
For example, if the word under cursor is “emacs”, then calling “wikipedia-linkify” changes it to:
<a href="http://en.wikipedia.org/wiki/emacs">emacs</a>

The following transform a URL into search link:

  • amazon-search-linkify
  • amazon-search-linkify-url
  • youporn-search-linkify
  • youtube-search-linkify
  • video-search-linkify
  • google-search-linkify

For example, if text selection is “world juggling federation”, then calling “video-search-linkify” it becomes:

<a class="gvidsr" href="http://www.google.com/search?tbs=vid%3A1&amp;q=world+juggling+federation">world juggling federation</a>

And with CSS it shows in browser like this:

world juggling federation

Transform URL Into Computer Language References

  • elisp-ref-linkify
  • emacs-ref-linkify
  • java-ref-linkify
  • mathematica-ref-linkify
  • perldoc-ref-linkify
  • php-ref-linkify
  • povray-ref-linkify
  • python-ref-linkify

For example, the “elisp-ref-linkify” transform any of the following form:

(elisp) The Mark
file:///Users/xah/web/xahlee_org/elisp/The-Mark.html#The-Mark
file:///Users/xah/web/xahlee_org/elisp/The-Mark.html
~/web/elisp/The-Mark.html

Into this link of uniform format:

<span class="ref"><a href="../elisp/The-Mark.html">(info "(elisp) The Mark")</a></span>

The relative link path above is automatically generated. With CSS it is displayed in browser like this:

(info "(elisp) The Mark")

Transform URL Into Embedded Video

  • youtube-linkify
  • dailymotion-video-linkify
  • google-video-linkify
  • redtube-linkify
  • break-video-linkify
  • tudou-video-linkify

For example, the “youtube-linkify” command turns the url under cursor, grabbed from the url field in a browser, like this:

http://www.youtube.com/watch?v=fjml8K7_Xfk

into a embedded video with VALID HTML and works in all browsers, like this:

<object type="application/x-shockwave-flash" data="http://www.youtube.com/v/fjml8K7_Xfk" width="480" height="385"><param name="movie" value="http://www.youtube.com/v/fjml8K7_Xfk"></object>

About 10 of these linkify commands i use few times per hour, each, for writing my website. You can see the source code at Xah Lee's Emacs Customization Files.

Power in Transform Text Under Cursor

The essense of power of these is that they transform the text under cursor or a text selection by one single button press, to anything you want, may it be a specialized html link, or customized programing function template, or even creating a file on the fly in the process (e.g. Writing a google-earth Function). If any command you use often, just assign a keyboard key to them.

So, start learning elisp today. If you are a complete newb, see: Emacs Lisp Basics and Emacs Lisp Examples. If you have some elisp experience, you can read Emacs Lisp Idioms and the 10 or so detail example tutorial at Emacs Lisp Tutorial.

If your elisp skill is young, you can still get this text transform power by writing the text transform part in a lang you already know. See: Emacs Lisp Wrapper For Perl Scripts.

2010-11-02

Apple Macbook Air Review

Perm url with updates: http://xahlee.org/comp/macbook_air.html

Apple Macbook Air Review

Xah Lee, 2010-11-02

Apple recently come out with 2 new fancy laptop computers. Macbook Air. It's thin and light. The special part is that it's got flash drive instead of the hard-disk, and does not have a DVD drive. Here's the spec for the smaller sized model.

apple-macbookair-q410-11-front-sm

Macbook Air, 2010 October

Macbook Air MC505LL/A
Dimension30 cm × 19.2 cm × 1.7 cm
Weight1.04 kg (that's like 6 apples)
screen pixels1366 × 768
CPU1.4 GHz Core 2 Duo
Memory2 GB (RAM)
Storage128 GB Solid State Drive
GPUNVIDIA GeForce 320M Integrated Graphics
apple-macbookair-q410-11-hero thin-lg

Macbook Air, 2010 October.

Apple Macbook Air commercial. Slick, ain't it?

Note that they not only dropped the hard-disk for a flash-drive, they also dropped DVD drive. So, if you are thinking of watching DVD on the plane, you are a rube. The cool kids don't watch DVDs on a computer anymore. Instead, you watch video thru downloaded files or digital streaming e.g. Video On Demand.

Apple's been like that, always on the bleeding edge. (they are the first major brand to use the mouse, the CD, the DVD. First to have builtin phone modem, ethernet (internet) port. First to have wireless internet builtin. First to include USB port and Firewire port. They are also the first to drop floppy drive, seriel/parallel port, and other outdated ports. (and now Firewire port is also dropped on this machine) And now, first to drop hard-disk and DVD drive. While it takes 1 or 2 year for PC to come with these new tech builtin, and takes about 3 to 5 years for PC to eliminate outdated tech. (many PC today still come with a PS2 (mouse) port and analog video port and serial/parallel port!))

“Introducing the new MacBook Air”

Watched the above video? Look at the mugs of those stinking Apple heads. I really get tired of them. Since about 2000, every year or two you have these folks peddling Apple design. I especially hate the Philip W Schiller guy.

Overall, it's a very slick machine. Light. Comes with camera, mic, speakers, and all the wireless internet stuff. So you can cam with your buddies across the world anytime. Unless you are a rocket scientist, it'd suite your needs on the go. How much? One Thousand US Dollars! For the same price, you can get a normal Macbook that's got twice the muscle, but twice the weight and bulk. Or, you can buy a PC, for just $500, and you get 4 times the weight'n'bulk free.

  • 〈Apple MacBook Air MC506LL/A 11.6-Inch Laptop〉 amazon
  • 〈Apple MacBook MC516LL/A 13.3-Inch Laptop〉amazon
  • 〈MacBook Pro 13-inch 2.4GHz〉 amazon

Conical Surface Juggling

Perm url with updates: http://xahlee.org/vofli_bolci/conics.html

Conical Surface Juggling

Xah Lee, 2006-11, 2010-11-02

Greg Kennedy juggling inside a conical enclosure.

It looks like juggling in wonderland, doesn't it?

You may not know, that when a cone is cut by a plane, their intersection forms a curve on the cutting plane, and this curve is mathematically classified into 3 types: ellipse (closed), hyperbola (open), parabola (open), depending the angle of the cutting plane with respect to the cone.

In general, these curves are literally and collectively called Conic Sections, or just Conics, and is the first systematically studied math subject by ancient Greeks.

You can see illustrations and their math details here: conic sections, ellipse, hyperbola, parabola.

Now, this is why, when the guy throws the ball even towards the ground, the ball comes up higher.

As long as he does not aim the ball precisely at the tip of the cone (his feet), then the ball will make a dip and come up!

Also of interest, is that the intersection of a cylinder and a plane is also a ellipse. This means, if the glass wall is a cylinder, then a ball thrown in the downward direction will also come up.

In practice, gravity will make some of these impractical. And the cone can't be perfect with a pinnacle because else he wouldn't have a place to stand on.

Juggling on Surface

Greg Kennedy's conics juggling is interesting because it force the balls on a surface. Normal juggling, is a 3D affair. By making balls roll on a surface, the juggling becomes a 2D affair, and is in fact easier for the same number of balls.

However, note that in practice, most juggling of more than 3 balls are essentially planar. For example, imaging juggling 5 balls. Although there are no constraints on where the ball would fly, but in practice it is thrown such that its path lies on the plane parallel to the juggler's face.

Greg's juggling is interesting because by forcing the balls to roll on a surface, it visually accentuate one beautiful aspect of juggling: the mathematical patterns made by the ball's paths.

Surface Juggling on a Hemisphere

There are many of mathematical surfaces. We have the plane, cylinder, cone. These are all rather “flat”. They are part of what's called ruled surface, because they can all be generated by a single line. Then, there's sphere, torus, and many other weird surfaces. So, what happens if you juggle on a sphere?

Surface Juggling on a Hemisphere

Bounce Juggling on Two Orthogonal Planes

Bounce Juggling on Two Orthogonal Planes

2010-11-01

HTML5 Video and Audio Tag

Perm url with updates: http://xahlee.org/js/html5_video_audio.html

HTML5 Video and Audio Tag

Xah Lee, 2010-11-01

This page shows you how to embed video or audio using html5's “video” and “audio” tags.

HTML5 introduced a “audio” and “video” tags. They allow you to embed a video or audio file without using Flash or other plugins. However, currently it is not yet widely supported by browsers, and the format spec is also not settled. Latest versions of Firefox, Chrome, Safari, Opera, usually support some of it. Internet Explorer 9 (in public beta) also support some.

For detail about which browser supports the “video” tag, see: http://www.youtube.com/html5

HTML5 Audio

Here's a audio file embeded using HTML5 audio tag.

Bach's Well-tempered Clavier, Book I, prelude and fugue number 1.

Here's the html source code.

<audio src="i/Bach_WTC1_1_Martha_Goldstein.ogg" controls></audio>

Attributes

AttributePossible ValuesComment
preloadnone,metadata,auto
controlsDoes not take any value
autoplayDoes not take any value
loopDoes not take any value

Note that “controls”, “autoplay”, “loop” are called “boolean attributes”. They do not take any value. Their existence or non-existence defines a behavior. It is wrong to add a 「="true"」 or 「="false"」 in them.

Reference: http://dev.w3.org/html5/spec/Overview.html#audio

HTML5 Video

Here's a embeded html5 video:

Short animation “Sintel” by Blender Institute. Source

Here's the html source code:

<video src="http://upload.wikimedia.org/wikipedia/commons/6/66/Sintel_movie_340x144.ogv" controls width="680" height="288"></video>

Attributes

The attributes are similar to the audio tag, but added are “poster” and “width”, “height”.

Supported Video Formats

Right now, the supported video formats is not specified. If a browser that support html5 video at all, usually the supported video formats are QuickTime, Matroska, Ogg, and the video codec supported are usually: H.264, vp8. For detail, see: Intro to Video Streaming and Video Audio Codecs.

References

Player Piano, Music Box, and Designing Mechanical Music Devices

Perm url with updates: http://xahlee.org/piano/animusic.html

Player Piano, Music Box, and Designing Mechanical Music Devices

Xah Lee, 2008-11, 2010-11-01

Player Piano, Music Box, and Designing Mechanical Music Devices is a series of computer generated animation of imagined mechanical devices that plays instrumental music.

This is one of their best:

Animusic, Pipe Dream Percussion instruments.

Feasibility

This is fantastic. Such a machine is certainly possible, but not as depicted exactly by the video. For example, when balls hit the strings or drum, even when precisely controlled, their ending path is not predictable because the hit target is still moving, such as cymbals. So, the balls will not all neatly fall into their catch hole.

This can be mended by having the balls simply fall on the floor. Stray balls colliding with instruments can be avoided by considering all possible bounce paths. Also, the instrument itself, such as cymbals, can be designed so that it doesn't move in a uncontrolled way. With the floor approach, the floor needs to be made soudless. One simple way is to make it a “bottomless well”, for example, suppose this chamber is hosted on the floorless 10th floor. I'm sure there are other methods, such as watered floor, or a slanted trampoline-like catch that bounces the balls silently to the side...

Device Design

Also, if we were to design such a mechanical device to play midi music, and suppose the goal does not need to be visually pleasing, then such mechanical device'd be much simpler. Player piano, Music box, are examples.

Also, note that some of the devices depicted is not flexible enough to play any other composition. For example, in the beginning of the video, a ball hits a string, then it bounces off onto another string, then bounces off onto a drum. This means, when a ball fires, it necessarily make 3 notes in sequence. This device is not useful for playing music that isn't all just these 3-notes. Of course, this virtual device is designed this way to make it visually and mechanically stunning. This aspect is actually the main attraction of Animusic.

Fixed Instrument, Flowing Music

So, in designing such a virtual music device, one could make it as logical as possible, such as the mechanics of a piano, where strings are simply laid out by length, flat on a plane, with arrays of hammers and dampers for each string, ready to spring into action when receiving a signal. Or, the strings can be laid out in a very creative way, without consideration of practicalities, but still mechanically feasible. For example, instead of hammers hitting the string, it is plausible to have the string move to hit the hammer. Even though, this would create a lot complexities in the device if we were to actually make it, but the point of animusic is to make visually and mechanically stunning instruments.

Fixed Music, Flowing Instrument

Also, instead of one set of strings laid out flat and let the melody determine which string gets hit, we can instead consider a given piece of melody as fixed, and have the devices change to fit the music. A simple example is to have just one single hammer, and let the strings move to it's target position. Also, the strings need not be layout flat on a plane, but it can be laid out in fancy ways, such as a circular.

Or, a piano-like instrument be made with one single hammper and one single string. The string's length is variable and mechanically controlled, so it can actually very length for different pitch within a fraction of a second. (this is certainly possible with today's tech) Now, because a piano's pitch is not simply length of string, and for different sections you actually need different string materials, so, instead one single set of a hamer with a string, we could have multiple of them, each focus on a different pitch range. Multiple set also allow harmonics.

Similarly, this applies to other instruments, such as drums, strings, wind instruments. There are a lot potential for creativity.

In the Pipe Dream video, there is one prominent example of flowing instrument over fixed music idea. Near the middle of the video, various sized marimba bars moves like a train over a rail, to be hit by a regular sequence of balls dropped into one spot. (as opposed to, fixed marinba bars fixed in a plane in the traditonal way)

There are some principles though. For example, the devices should remain mechanical and plausible. That's the charm of it.

Animusic, Resonant Chamber Plucked strings.

  • 〈Animusic - A Computer Animation Video Album (Special Edition) (2001)〉 amazon

Emacs lookup: Dictionary, Google, PHP, Perl...

Perm url with updates: http://xahlee.org/emacs/emacs_lookup_ref.html

Dictionary, Google, PHP, Perl, ... Reference Lookup with Emacs

Xah Lee, 2008-11, 2010-11-01

This page shows you how to use emacs as a dictionary application, that allows you to lookup the definitions of a word under cursor, or any general reference such as Wikipedia, Google, or lookup documentation of computer language's keywords.

Looking Up Word Under Cursor

You can setup your emacs so that, pressing a button will lookup the definition of the word under cursor.

Place the following in your emacs init file:

(defun lookup-word-definition ()
  "Look up the current word's definition in a browser.
If a region is active (a phrase), lookup that phrase."
 (interactive)
 (let (myword myurl)
   (setq myword
         (if (and transient-mark-mode mark-active)
             (buffer-substring-no-properties (region-beginning) (region-end))
           (thing-at-point 'symbol)))

  (setq myword (replace-regexp-in-string " " "%20" myword))
  (setq myurl (concat "http://www.answers.com/main/ntquery?s=" myword))

  (browse-url myurl)
  ;; (w3m-browse-url myurl) ;; if you want to browse using w3m
   ))

(global-set-key (kbd "<f6>") 'lookup-word-definition)

With the above, pressing F6 will launch your browser and lookup definition of the word under cursor.

If you do a lot vocabulary research, you can have emacs open several dictionaries in one shot. Just add more of the “browse-url” line.

You can change the url to a different online dictionary reference website.

Here are some other online dictionary sites and their url search syntax, using sample word “curlicue”. AHD means American Heritage Dictionary.

If you prefer to lookup definitions within emacs, then you need to either install a web browser within emacs, the emacs-w3m. (Note: you might need to spend 30 minutes or more to get it to work.) Or, you can install a emacs dictionary client. See: Emacs Dictionary Lookup.

Perl, PHP, Ruby... Reference Lookup and Google, Wikipedia

The following is a example of looking up Wikipedia:

(defun lookup-wikipedia ()
  "Look up the word under cursor in Wikipedia.
This command generates a url for Wikipedia.com and switches you
to browser. If a region is active (a phrase), lookup that phrase."
 (interactive)
 (let (myword myurl)
   (setq myword
         (if (and transient-mark-mode mark-active)
             (buffer-substring-no-properties (region-beginning) (region-end))
           (thing-at-point 'symbol)))

  (setq myword (replace-regexp-in-string " " "_" myword))
  (setq myurl (concat "http://en.wikipedia.org/wiki/" myword))
  (browse-url myurl)
   ))

Here are some example urls for some reference lookup sites.

Perlhttp://perldoc.perl.org/search.html?q=‹SearchWord›
PHPhttp://us.php.net/‹SearchWord›
LSLhttp://wiki.secondlife.com/wiki/‹SearchWord›
AutoHotkeyhttp://www.autohotkey.com/docs/commands/‹SearchWord›.htm
Wikipediahttp://en.wikipedia.org/wiki/‹SearchWord›
Googlehttp://www.google.com/search?q=‹SearchWord›

If you know a url syntax for Ruby, Python, lisp, or other langs, please add at the comment below. Thanks.