2011-09-17

Emacs Lisp Function to Trim String

Emacs Lisp Function to Trim String

Emacs lisp does not have a function that removes space from the beginning and end of a string. You must use “replace-regexp-in-string” for that. Here's a function that does it.

(defun trim-string (string)
  "Remove white spaces in beginning and ending of STRING.
White space here is any of: space, tab, emacs newline (line feed, ASCII 10)."
(replace-regexp-in-string "\\`[ \t\n]*" "" (replace-regexp-in-string "[ \t\n]*\\'" "" string))
)

See also:

roller coaster = calculus

when i see a roller-coaster, i see calculus.

Blue Fire roller coaster-s
Blue Fire roller-coaster. img src

2011-09-16

Emacs: manipulate Column Text, string-rectangle, ASCII-Art

Perm url with updates: http://xahlee.org/emacs/emacs_string-rectangle_ascii-art.html

Emacs: Manipulate Column Text, string-rectangle, ASCII-Art

Xah Lee, 2011-09-14

Some tips on manipulating a column of text.

In my 12 years of using emacs daily, the most useful to me are these two. I use them few times a week.

CommandKeyPurpose
kill-rectangleCtrl+x r kDelete a column block of text (and put it in a special clipboard)
replace-rectangleCtrl+x r tInsert text in all lines. This is alias to “string-rectangle”.

I use the above so often that in the past 2 years i gave them a shortcut such as 【Ctrl+8】 and 【Ctrl+9】.

Here's a example of how to use it. In the following, put your cursor before the “1”, then mark 【Ctrl+Space】, then move it to end of “2”, then call “kill-rectangle”

..............
..1xxx..oooo..
..xxxx..oooo..
..xxxx..oooo..
..xxxx..oooo..
..xxxx..oooo..
..xxxx..oooo..
..xxxx..oooo..
..xxxx..oooo..
..xxxx..oooo..
..xxx2..oooo..
..............

The other emacs command i often want but always forgot is:

CommandKeyPurpose
yank-rectangleCtrl+x r ypaste a column of text (after you used “killed-rectangle”).

The “yank-rectangle” is useful when you want to move a text somewhere. Try to swap the “x” block and “o” block in the above sample text.

These “rectangle” commands is designed for drawing ASCII diagrams. Here's some examples of ASCII diagram.

  _____________________________________________
 |                                             |
 |          Sequence                           |
 |  ______   ________________________________  |
 | |      | |                                | |
 | | List | |             Array              | |
 | |      | |    ________       ________     | |
 | |______| |   |        |     |        |    | |
 |          |   | Vector |     | String |    | |
 |          |   |________|     |________|    | |
 |          |  ____________   _____________  | |
 |          | |            | |             | | |
 |          | | Char-table | | Bool-vector | | |
 |          | |____________| |_____________| | |
 |          |________________________________| |
 |_____________________________________________|
(info "(elisp) Sequences Arrays Vectors")
  ---------------       ----------------       -------------------
 | car   | cdr   |     | car    | cdr   |     | car       | cdr   |
 | rose  |   o-------->| violet |   o-------->| buttercup |  nil  |
 |       |       |     |        |       |     |           |       |
  ---------------       ----------------       -------------------
(info "(elisp) Box Diagrams")

I almost never do ASCII diagram, yet, i still find “kill-rectangle” and “replace-rectangle” useful almost everyday when editing source code.

align-regexp

Emacs has another function that's helpful for alignment, the “align-regexp” function. For example, suppose you have:

tom = 5
jenny = 8
mary = 7

and you want to align them by the equal sign. Just select the text, then call “align-regexp” then give “=”. Then you get:

tom   = 5
jenny = 8
mary  = 7

Less Used Rectangle Commands

Here's others rectangle commands, but i've never used them:

commandKeyPurpose
delete-rectangleCtrl+x r dlike “kill-rectangle”, but doesn't save in a special kill-ring
clear-rectangleCtrl+x r creplace with space
string-insert-rectanglelike “string-rectangle”, but doesn't replace existing content
close-rectangleremove white places
delete-whitespace-rectangleDelete all whitespace following a specified column in each line.
delimit-columns-rectangle
open-rectangleCtrl+x r oBlank out the region-rectangle, shifting tex

picture-mode

Emacs also has a “picture-mode”, designed for drawing ASCII diagrams. I've never used it.

Open a new file. (in ErgoEmacs, 【Ctrl+n】. In GNU Emacs, call “switch-to-buffer” 【Alt+x b】, then give a random name.) Then, call “picture-mode”, then call “describe-mode” 【Ctrl+h m】 to see how to use it.

artist-mode

Emacs also has a “artist-mode”. It's a mode that lets you draw ASCII pictures with the mouse.

Open a new file. Now, you can draw with your mouse. Hold right button to erase. Middle click to switch to rectangle, ellipse, and other tools.

    +--------------+             -----------
    | +---+        |          --/   ------- \--
    | |+--+--------+---+    -/   --/       \-- \-
    | ||  |        |   |   /    /    -----    \  \
    | ||  |  +-----+-+ |   |    |   (     )   |  |
    +-++--+--+-----+ | |   \    \    -----    /  /
      ||  |  +-------+ |    -\   --\       /-- /-
      |+--+------------+      --\   ------- /--
      |   |                      -----------           ●●●●
      |   |                                     ●●●●●●●   ●●●
      +---+             ●●●●●         ●●●●●●●●●●●   ●●●●    ●●
                    ●●●●●    ●●●●●●●●●●    ●●●●●●   ●    ●   ●
                ●●●●●      ●●●●●●●●●●●●●●●●     ●●  ● ●  ●●  ●●
              ●●●       ●●●●              ●●●●   ●    ●   ●   ●
            ●●●      ●●●●           ●●●●●●      ●●  ●●●   ●  ●●
          ●●●      ●●●         ●●●       ●●●●     ●●●    ●●  ●
          ●      ●●●    ●●●●●●●  ●●●●●      ●●●●●●●     ●●   ●
         ●      ●●    ●●●            ●●●             ●●●●  ●●●
        ●●     ●●    ●●       ●●●●●    ●●●   ●●●●●●●●●    ●●
       ●●      ●    ●     ●●●●    ●●●    ●●   ●           ●
      ●●      ●    ●●   ●●●        ●●     ●   ●   ●●●●●   ●●
                   ●    ●     ●●●●●●      ●   ●   ●   ●●   ●●
                   ●●        ●●         ●●   ●●   ●    ●    ●
                    ●●●●     ●        ●●●   ●●   ●●   ●●    ●
                  ●●●●●●●●   ●●●●●●●●●●    ●●   ●●    ●    ●●
                  ●●●●●●●●    ●●●         ●●●  ●●    ●●    ●
                  ●●●●●●●●   ●● ●●●●●●●●●    ●●●     ●     ●
                   ●●●●●●●  ●           ●●●         ●●    ●●
                      ●●●  ●●     ●●●     ●●       ●●    ●●
                         ●●●    ●●● ●●     ●●●●●●●●     ●●
                 ●●●●●●●●●     ●●    ●●               ●●●
               ●●●            ●●      ●●●●●●●●●●●●●●●●●
               ●     ●●●●●●●●●●
               ●      ●●●●●●●●●●●●●●●●●●●●●●
               ●●●●                      ●●●
                  ●●●●●●●●●●●●●●●●●●●●●●●●
Some doodle with “artist-mode”.

You can see a video of this guy using it: Emacs Screencast: Artist Mode (2009-05-25) By Seong-Kook Shin. @ Source www.cinsk.org.

I should warn that you should not get into a habit of using ASCII art in comments, such as drawing boxes. Because, it is a form of hard-formatting. As such, it is not flexible and creates all sorts of problems. See:

For the same reason, i never liked any comment alignment in my source code, and i am annoyed that emacs by default aligns your comment when you call “comment-dwim” 【Alt+;

Programing Language: LISP Syntax Problem of Piping Functions

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

Programing Language: LISP Syntax Problem of Piping Functions

Xah Lee, 2011-09-16

One of the annoying problem of the lisp nested syntax is the problem of creating a function chain (aka unix pipe, filtering, stream).

Here's a example i frequently encounter in emacs lisp. I want to apply several different functions to a string, one after the other. Example:

(setq fname (file-name-sans-extension (file-name-nondirectory fname)))
(setq fname (replace-regexp-in-string "-" " " fname))
(setq fname (replace-regexp-in-string "_002d" "-" fname))
fname

Note the repeated reset of a variable. I don't want that. I want to avoid mutable variables; it's bad in functional programing. So, one should do like this:

(replace-regexp-in-string "_002d" "-"
 (replace-regexp-in-string "-" " "
  (file-name-sans-extension
   (file-name-nondirectory fname))))

But that has several problems. It's hard to debug. Also, in conventional lisp code formatting, “emacs-lisp-mode” would format it like this (expand your window width to prevent line wrapping):

(replace-regexp-in-string "_002d" "-"
                          (replace-regexp-in-string "-" " "
                                                    (file-name-sans-extension
                                                     (file-name-nondirectory fname))))

Alternative is a one-liner formatting, but it's hard to read and edit:

(replace-regexp-in-string "_002d" "-" (replace-regexp-in-string "-" " " (file-name-sans-extension (file-name-nondirectory fname))))

If lisp has adopted its early concept of M-expression as syntax wrapper, then it could be written like this using a postfix syntax like unix's pipe |. Here, i show it using Mathematica syntax:

fname //
file-name-nondirectory //
file-name-sans-extension //
Function[replace-regexp-in-string["-", " ", #]] //
Function[replace-regexp-in-string["_002d", "-", #]]

The // is similiar to unix's pipe | operator.

or in Mathematica's prefix notation, with @ as the prefix operator:

Function[replace-regexp-in-string["_002d", "-", #]] @
Function[replace-regexp-in-string["-", " ", #]] @
file-name-sans-extension @
file-name-nondirectory @
fname

Note that in functional languages (e.g. Haskell, OCaml), they have both prefix and postfix operators. Usually the space character is used as context-sensitive implicit prefix operator. e.g. f x means “f” applied to “x”, and f a b c means (((f a) b) c). In Ruby, Perl, usually they have postfix operator desguised as calling object's methods. In perl, it's ->, in Ruby, it's just a dot ..

For detail, see:

Also note, although Haskell and OCaml have postfix and prefix operators, but these lang's syntax in general are syntax soups. That is, it's one bunch of ad hoc designs with no consistancy, no systematic grammar, no mathematical foundation. They are not much better than the syntax soup of C-like langs. The symbols are used promiscuously (see: Problems of Symbol Congestion in Computer Languages (ASCII Jam; Unicode; Fortress)) and the forms are idiosyncratic, e.g. i++, ++i, for(;;){}, while(){}, 0x123, expr1 ? expr2 : expr3, sprint(…%s…,…), …. The only language i know whose syntax approaches a systematic grammar is Mathematica. See: The Concepts and Confusions of Prefix, Infix, Postfix and Fully Nested Notations and Math Notations, Computer Languages, and the “Form” in Formalism.

2011-09-14

the will to live

i have lost the will to live.

for about 4 months back now.

been wanting to write about it on and off, but every time i started to ramble and digress and wasn't too sure if i should post.

so, what i want to know is, what do you think about this?

2011-09-11

Why Doesn't Google Chrome Cache YouTube Videos?

being a efficiency nerd, i have this unhealthy obsession about the efficiency of internet bandwidth use.

for example, if i'm watching a youtube video, and if it so happens that i don't want to watch it anymore, i usually take the trouble of right-click and stop downloading, even i still want to stay on the page (say, reading the comments), as some kinda sense to reduce “waste”. (even though my internet bandwidth is fast, unlimited, and far underused)

as another example, when the tech of live audio broadcasting thru internet (aka internet radio) started to show up in ~1999, where people can listen to it just like radio, like, leaving it on all the time, my thought was that, “O my fucking god, who invented such a thing that is extremely inconsiderate in using resources”.

of course, i know that these are extremely silly concerns, but i simply just have it in me, and continuously trying to brush such idiotic thoughts away. (i should know, cuz i wrote a ton despising those “hacker” coders who habitually diddle their code for the “idiom” fuck, thinking that they'd squeeze a few cpu cycle out of it, e.g. in particular, the perl mongers peddles this idea, which i think died out gradually starting in ~2001 to ~2005.)

but anyway, i have a question, which prompted me to write this. When you watch a youtube video, after you finished watching, sometimes you went to watch others or do something but happened to land on the same page and want to watch it again. I'd thought that Google Chrome would have cached the video, so it doesn't have to re-download the 30 or so megabytes again. But apparently, it doesn't seem to be the case, because you can see the downloading progression bar going. Why's that? Is Chrome's behavior dependent on your net speed or it does always re-download? I can't figure why it won't cache.

Source plus.google.com

9/11, and Human Animal's Love for Excitement

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

9/11, and Human Animal's Love for Excitement

Xah Lee, 2011-09-11

So, over there at social policy activist Lauren Weinstein's post about politicians and the media abusing 9/11 to manipulate populace or whatnot. Here's excerpts:

With the media deeply engaged in an orgy of wall-to-wall 9/11 coverage today, one might imagine that the 10 year anniversary of another attack on the U.S. — the attack on Pearl Harbor — would have generated similar press reactions. Or is the media exploitation of such anniversaries a relatively new phenomenon?

I spent some time looking over newspaper archives from December 7, 1951 to try find out. The contrast with today's media was striking. …

In fact, you had to go to page 10 to find any mention — a brief editorial — regarding the anniversary, noting with confidence that there would never again be a similar attack on a well-prepared United States: …

Full post and comments at: How Did the Press “Commemorate” the 10 Year Anniversary of the Attack on Pearl Harbor? (2011-09-11) By Lauren Weinstein. @ Source plus.google.com

I have the idea of a solution to the ills of modern society, that's in me for a while. Here it is.

tend to agree with +Lauren Weinstein on this one. Am in general against any activism or emotional stimulation. Instead, resources should be spend on general education.

the problem with the good old education line of thinking is that nobody cares for such boring “solution”. The human animals want new things, chantable phrases, actions, especially when some big news incident just happened. I thought of this problem, and a fantasy solution i thought is to fight these idiotic human nature or greasy politicians with the same, lies, or marketing, social psychology, suave, whatever one'd call them.

so, in this fantasy scenario, when some major disaster happened (e.g. Katrina), or 9/11, instead of politician jump to action with cries of retribution, slogans such as “united we standard”, blood donation, and so on, the politician of my school should equally respond to the public with EXTREME agitation and reaction, but instead of some reaction such as warmongering, he would enact things that are seemingly completely irrelevant, such as for the next year, all books sold in US on shakespeare, poetry, books on paintings of classic masters, will be FREE, paid by government. Or, the government will henceforth pay 10 thousand dollars to each and every teachers across US that are teaching subjects of humanities (or, to all teachers, period.). Or, the government will immediately start projects that build free internet in all major cities, wholly paid by government.

in this scenario, the essence is that no extra dollar or attention should be paid to whatever disaster or incident of current. Instead, such heart-wrenching incident will be used to spur and channel the populace's emotion to the immediate funding of spreading knowledge, in particular, “useless” knowledge such as arts and letters.

also, any non-profit organization should be axed, such as Red Cross or some help Africa fuck. Instead, help should be in the form of immediate, concrete, human touch, from you, that can be felt by another human animal directly and physically. For example, if you are the bleeding heart type, then, when 9/11 happened, instead of donating say $10 bucks to red cross with the complex channel of credit card and so on of modern society that you hardly know how exactly money works or what complex route it actually go thru and how the fund are spent by the board of directors shit… Instead, immediately, walk out of your house to the street, and hand a $10 dollar bill to that neighbor kid you knew is poor. Tell him, you love him, and advice him to spend the money well, and leave it at that.

The $10 that went to Red Cross, is love of yourself, your ego. The $10 that went to the neighbor kid, is love of humanity.

why such line of thinking? Roughly, these disasters, wars, never ends. It happens thru-out history, today, and not likely to end anytime soon. Human animal's been like that, despite so-felt love and humanity and such. (aww, how sad is 9/11, let's have a group-hug) Even at individual level, look at the nym war going on here. A rather insignificant issue, but the proponents spend inordinate amount of time, going into great lengths fighting about it, likening Google to Nazi, and so on, so that they can WIN, they can feel they are USEFUL. This is a small scale of things. In bigger scale in the complex society, we have Iraq War, Congo War, and all other wars around the globe. So, in my view, which is a view of Bertrand Russell, that a good life require 2 things: love and knowledge. Nothing else. I think war, and much problem of society will decrease, if say every US citizen have at least knowledge equivalent to a college degree in humanities, but more to the point, that each of us college educated, should have knowledge equivalent of at least 3 degrees, 2 in humanities. The humanities knowledge is there to cater love. (btw, institutionalized education with its bureaucracy and knowledge certification (aka “Degree”) should be de-emphasized, but rather, a life-long learning system in society, preferably instigated by culture.)

because, you see, that the way society are is largely due to the way we are. The USA is the way it is today, all its political ills or whatnot, because each and every one of us, made it so. You, you did it. If each and everyone of us, all can drivel poetry or painting or esoteric ancient history, and assuming we have cultivated a society and culture such that we love these things just as today many of us love to have a say about politics from small (nym wars) to large (american left vs right), chances are, USA might be more rich and prosperous. (though, possibly might not be as powerful, not having so much nuclear weapons, and china might tell us what to do. That might be the Achilles' heel of my theory. lol)

See also: What Desires Are Politically Important? (by Bertrand Russell) and the Barbarism of Specialization (philosophy).

The Lonely Island - I Am On a Boat

Perm url with updates: http://xahlee.org/music/i_am_on_a_boat.html

Raw Spite, Motherfucker, I Am On a Boat

Xah Lee, 2011-09-10

I'm on a Boat (2009), a silly rap song. The song is extremely popular. Quote from Wikipedia: «The music video reached number one on YouTube in February 2009 and was number one on the U.S. iTunes music video chart.».

I'm On A Boat (ft. T-Pain)

Love the song. Pure swagger delivered raw.

shawty ⇒ or “shorty”. Young attractive female. Shawty (slang)
five knots ⇒ one knot is 1.852 km per hour. 5 knots is thus 9.26 km/h. Knot (unit)
(shawty) Aww shit
Get your towels ready it's about to go down (yeah, shawty)
Everybody in the place hit the fuckin deck (yeah, shawty)
But stay on your motherfuckin toes
We runnin this, let's go

I'm on a boat (I'm on a boat)
I'm on a boat (I'm on a boat)
Everybody look at me cause I'm sailin on a boat (sailin on a boat)
I'm on a boat (I'm on a boat)
I'm on a boat
Take a good hard look at the motherfuckin boat (boat, yeah)

I'm on a boat motherfucker take a look at me
Straight floatin on a boat on the deep blue sea
Bustin five knots, wind whippin at my coat
You can't stop me motherfucker cause I'm on a boat
Kinko ⇒ Kinko, a popular chain store in US that provides services such as printing, faxing, copying, mailing packages, etc.
Seaworld ⇒ A amusement park featuring dolphins etc.
Take a picture, trick (trick) I'm on a boat, bitch (bitch)
We drinking Santana champ, cause it's so crisp (crisp)
I got my swim trunks, and my flippie-floppies
I'm flippin burgers, you at Kinko's straight flippin copies
I'm ridin on a dolphin, doin flips and shit
This dolphin's splashin, gettin everybody all wet
But this ain't Seaworld, this is real as it gets
I'm on a boat motherfucker, don't you ever forget
pashmina ⇒ Fine, downy wool growing beneath the outer hair of feral Himalayan goats. (AHD) Pashmina
afghan ⇒ Afghan (blanket)
Leo ⇒ Reference to a popular epic romance film Titanic (1997), starring Leonardo DiCaprio.
I'm on a boat and, it's goin fast and
I got a nautical themed pashmina afghan
I'm the king of the world, on a boat like Leo
If you're on the shore, then you're sho' not me-oh
Get the fuck up, this boat is real
Fuck land, I'm on a boat, motherfucker (motherfucker)
Fuck trees, I climb buoys, motherfucker (motherfucker)
I'm on the deck with my boys, motherfucker (yeah)
The boat engine make noise, motherfucker
starboard ⇒ right side of a ship. starboard. Bow is the front of ship
Kevin Garnett ⇒ Kevin Garnett (b1976), American basketball player.
Poseidon ⇒ The god of sea in Greek mythology. Poseidon. See also: A Love of Mythology of the Greeks.
all hands on deck ⇒ idiom, meaning all the staff is ready (for crisis, etc.).
Hey ma, if you could see me now (see me now)
Arms spread wide on the starboard bow (starboard bow)
Gonna fly this boat to the moon somehow (moon somehow)
Like Kevin Garnett, anything is possible

Yeah, never thought I'd be on a boat
It's a big blue watery road (yeah)
Poseidon, look at me, oh (all hands on deck)
Never thought I'd see the day
When a big boat comin my way
Believe me when I say, I fucked a mermaid

I'm on a boat
I'm on a boat
Everybody look at me cause im sailin on a boat
I'm on a boat
I'm on a boat
Take a good hard look at the motherfuckin boat

Whoahhh
Sha-sha-shorty, shawty
Yeah yeah yeahhh