Thursday, August 12, 2010

Tera-WURFL PHP Mobile Phone Database

SkyHi @ Thursday, August 12, 2010
Fatal error: Class ‘ZipArchive’ not found in

這個問題是因無php沒有支援zip所造成,在網路上搜尋後,找到筆記:CentOS 5.2上php5如何安裝zipArchive extension (PECL) 以下轉載解決方法:


1.安裝yum的plugin: yum-priorities 


#yum install yum-priorities



2.編輯priorities.conf


#vi /etc/yum/pluginconf.d/priorities.conf


將以下內容


enabled = 1


修改成


enable = 1
check_obsoletes=1
priority=N


:wq



3.設定EPEL


#rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-3.noarch.rpm



4.安裝zipArchive


#yum install php-pecl-zip



5.重新啟動httpd


#service httpd restart



REFERENCES

http://plus-now.com/?p=427


Wednesday, August 11, 2010

PHP Articles

SkyHi @ Wednesday, August 11, 2010

Currently Browsing: PHP
Launch Increase PHP security with phpsecinfo TIP: This article also appears in our wiki. Help us keep our "Increase PHP security with phpsecinfo" article updated by joining the wiki. Click on the link to get started. PHPSecInfo provides the security equivalent of the phpinfo() function. It is not a replacement for secure development tech ... Applies To: All Service Types
Launch How can I install ionCube loader libraries on the (gs) Grid-Service? TIP: This article also appears in our wiki. Help us keep our "How can I install ionCube loader libraries on the (gs) Grid-Service?" article updated by joining the wiki. Click on the link to get started. Things you will need: IonCube loader libraries located at http://www.ioncube.com/loade ... Applies To: (gs)
Launch PHP Power Mode TIP: This article also appears in our wiki. Help us keep our "PHP Power Mode" article updated by joining the wiki. Click on the link to get started. PHP Power Mode allows customers to run their php scripts without most of the restrictions imposed by safe_mode ( PHP Safe Mode, problems and work ... Applies To: (ss)
Launch How can I turn off safe_mode on an (dv) Dedicated-Virtual Server with Plesk? TIP: This article also appears in our wiki. Help us keep our "How can I turn off safe_mode on an (dv) Dedicated-Virtual Server with Plesk?" article updated by joining the wiki. Click on the link to get started. This article with tell you how to turn off safe_mode globally (through the php.ini ... Applies To: (dpv) Nitro, All (dv)
Launch PHP Safe Mode, problems and work-arounds TIP: This article also appears in our wiki. Help us keep our "PHP Safe Mode, problems and work-arounds" article updated by joining the wiki. Click on the link to get started. This article explains (mt) Media Temple's position regarding running PHP in Safe Mode and offers some possible work-aro ... Applies To: All Service Types
Launch How can I specify the version of php for web applications on the (gs) Grid-Service? Table of Contents: PHP Settings in the AccountCenter Specify a different PHP version Notes/Supplemental Resources PHP Settings in the AccountCenter You can provide a specific version of php from within your (ac) AccountCenter. Sign on to your (ac) AccountCenter Click on your Primary Domain ... Applies To: (gs)
Launch Determining the source domain for emails generated from PHP scripts This article has been mirrored from the Parallels Knowledge Base as a courtesy to our (dv) Dedicated-Virtual Server customers. As they are the authoritative source of the information covered in this topic we encourage you to check their original article since this content is subject to change. ... Applies To: All (dv)
Launch I'm getting an upload_tmp_dir error when using PHP. How do I fix this error? This article has been mirrored from the Parallels Knowledge Base as a courtesy to our (dv) Dedicated-Virtual Server customers. As they are the authoritative source of the information covered in this topic we encourage you to check their original article since this content is subject to change. ... Applies To: All (dv)
Launch How can I Enable Zend Optimizer (php4/5) on the (gs) Grid-Service? The (gs) Grid-Service comes with support for the Zend Optimizer and is fully ready to use when you get the server. As this is a very flexible system, users may choose to implement custom directives through the means of a custom php.ini file. In such cases as these, the Zend Optimizer functional ... Applies To: (gs)
Launch How can I create a phpinfo.php page? DETAILS: The phpinfo file outputs a large amount of information about the current state of PHP. This includes information about PHP compilation options and extensions, the PHP version, server information and environment (if compiled as a module), the PHP environment, OS version information, pat ... Applies To: All Service Types
Launch (gs) Using SetHandler to process other extensions as PHP There might be times when you want your webpages to appear like they are html but are actually being processed as PHP. This article briefly describes three ways to accomplish this. Method 1 - Process all files with the same extension as PHP Create an .htaccess file (What is an .htaccess file ... Applies To: (gs)
Launch (gs) PHP Sessions do not work as expected Symptoms: Randomly being logged out of your PHP application. Sessions are not saving when transitioning from HTTP to HTTPS protocols. If a PHP session needs to begin in HTTP and switch to HTTPS, there will be some issues where the session is not maintained across that transition. General probl ... Applies To: (gs)
Launch Why is allow_url_fopen disabled on the (gs) Grid-Service? DETAILS: The PHP parameter allow_url_fopen has been disabled in both our PHP4 and PHP5 environments for the (gs) Grid-Service. BACKGROUND: If enabled, allow_url_fopen allows PHP's file functions to retrieve data from remote locations such as an FTP server or web site, and could lead to code i ... Applies To: (gs)
Launch Reverting PHP5 for (dv) 3.0 after migrating to a (dv) 3.5 This article provides a general walkthrough on how to remove the upgrade to PHP5 on a (dv) 3.0 Dedicated-Virtual Server after you have migrated to a (dv) 3.5 Dedicated-Virtual Server. NOTE: Text in this color is used as an example. Please be sure to replace this text with the proper informat ... Applies To: (dpv) Nitro, (dv) 3.5
Launch How can I edit php.ini on the (gs) Grid-Service? Details: Each (gs) Grid-Service has it's own editable php.ini. This makes it possible for administrators to change php values independent of our default php values. As a courtesy we have provided a sample php.ini file in: /home/#####/etc/php.ini.sample where '#####' is substituted by your actu ... Applies To: (gs)
Launch How do I enable .phps file to be color highlighted? Because of the way PHP is configured on our (gs) platform there is a work around to get a .phps file displaying colorized. You will need to add the following to your .htaccess and create the source.php file somewhere in you path. Edit or create a .htaccess file in the root of the domain you wa ... Applies To: (gs)
Launch How can I edit php.ini on the (dv) & (dpv) Dedicated-Virtual Servers? DETAILS: NOTE: To edit your php.ini you will need to login via SSH as the root user. The most common parameters changed in the php.ini file are: safe_mode register_globals upload_max_filesize post_max_size max_execution_time Use the following command at the command prompt to start edit ... Applies To: (dpv) Nitro, All (dv)

REFERENCES
http://kb.mediatemple.net/categories/Browse+by+Category/Web+Technologies/PHP/

Why is allow_url_fopen disabled

SkyHi @ Wednesday, August 11, 2010

allow_url_fopen


Test Description

This test checks to see if allow_url_fopen is enabled.

Security Implications

If enabled, allow_url_fopen allows PHP's file functions -- such as file_get_contents() and the include and require statements -- can retrieve data from remote locations, like an FTP or web site. Programmers frequently forget this and don't do proper input filtering when passing user-provided data to these functions, opening them up to code injection vulnerabilities. A large number of code injection vulnerabilities reported in PHP-based web applications are caused by the combination of enabling allow_url_fopen and bad input filtering.
allow_url_fopen is on by default.

Recommendations

You should disable allow_url_fopen in the php.ini file:
; Disable allow_url_fopen for security reasons
allow_url_fopen = 'off'
The setting can also be disabled in apache's httpd.conf file:
# Disable allow_url_fopen for security reasons
php_flag  allow_url_fopen  off
For remote file access, consider using the cURL functions that PHP provides.

More Information


REFERENCES
http://phpsec.org/projects/phpsecinfo/tests/allow_url_fopen.html
http://www.google.ca/#q=allow_url_fopen+on&hl=en&prmd=df&ei=bjJjTMTmDszGOP6CpbsK&start=0&sa=N&fp=e6a957a020d2d8f6 






Tuesday, August 10, 2010

I never really understood: what is CGI?

SkyHi @ Tuesday, August 10, 2010

CGI is a Comman Gateway Interface. As the name says, it is a "common" gateway interface for everything. It is so trivial and naive from the name. I feel that I understood this and I felt this every time I encountered this word. But frankly, I didn't. I'm still confused.



I am a PHP programmer. I did lot of web development.



user (client) request for page ---> webserver(->embedded PHP interpreter) ----> Server side(PHP) Script ---> MySQL Server.



Now say my PHP Script can fetch results from MySQL Server && MATLAB Server && Some other server.



So, now PHP Script is the CGI? because its interface for the between webserver & All other servers? I don't know. Sometimes they call CGI, a technology & othertimes they call CGI a program or someother server.



  • What exactly is CGI?

  • Whats the big deal with /cgi-bin/*.cgi? Whats up with this? I don't know what is this cgi-bin directory on the server for. I don't know why they have *.cgi extensions.

  • Why does Perl always comes in the way. CGI & Perl (language). I also don't know whats up with these two. Almost all the time I keep hearing these two in combination "CGI & Perl". This book is another great example CGI Programming with Perl Why not "CGI Programming with PHP/JSP/ASP". I never saw such things.

  • CGI Programming in C this confuses me a lot. in C?? Seriously?? I don't know what to say. I"m just confused. "in C"?? This changes everything. Program needs to be compiled and executed. This entirely changes my view of web programming. When do I compile? How does the program gets executed (because it will be a machine code, so it must execute as a independent process). How does it communicate with the web server? IPC? and interfacing with all the servers (in my example MATLAB & MySQL) using socket programming? I'm lost!!

  • They say that CGI is depreciated. Its no more in use. Is it so? What is its latest update?




Once, I ran into a situation where I
had to give HTTP PUT request access to
web server (Apache HTTPD). Its a long
back. So, as far as I remember this is
what I did:



  1. Edited the configuration file of Apache HTTPD to tell webserver to pass
    all HTTP PUT requests to some
    put.php ( I had to write this PHP
    script)

  2. Implement put.php to handle the request (save the file to the location
    mentioned)



People said that I wrote a CGI Script.
Seriously, I didn't have clue what
they were talking about.




  • Did I really write CGI Script?


I hope you understood what my confusion is. (Because I myself don't know where I'm confused). I request you guys to keep your answer as simple as possible. I really can't understand any fancy technical terminology. At least not in this case.



EDIT:



I found this amazing tutorial "CGI Programming Is Simple!" - CGI Tutorial Which explains the concepts in simplest possible way. After reading this article you may want to read Getting Started with CGI Programming in C to supplement your understanding with actual code samples. I've also added these links to this tutorial to Wikipedia's article : http://en.wikipedia.org/wiki/Common_Gateway_Interface



9 Answers

CGI is an interface which tells the webserver how to pass data back and forth to and from an application. More specifically, it describes how request information is passed in environment variables (such as request type, remote IP address), how the reqeust body is passed in via standard input, and how the response is passed out via standard output. You can refer to the CGI specification for details.



To use your image:



user (client) request for page ---> webserver ---[CGI]----> Server side Program ---> MySQL Server.



Most, if not all, webservers can be configured to execute a program as a 'CGI'. This means that the webserver, upon receiving a request, will forward the data to a specific program, setting some environment variables and marshalling the parameters via standard input and standard output so the program can know where and what to look for.



The main benefit is that you can run ANY executable code from the web, given that both the webserver and the program know how CGI works. That's why you could write web programs in C or Bash or Brainfuck with a regular CGI-enabled webserver. That, and that most programming environments can easily use standard input, standard output and environment variables.



In your case you most likely used another, specific for PHP, means of communication between your scripts and the webserver, this, as you well mention in your question, is an embedded interpreter called mod_php.



So, answering your questions:




What exactly is CGI?




See above.




Whats the big deal with /cgi-bin/*.cgi? Whats up with this? I don't know what is this cgi-bin directory on the server for. I don't know why they have *.cgi extensions.




That's the traditional place for cgi programs, many webservers come with this directory pre configured to execute all binaries there as CGI programs. The .cgi extension denotes an executable that is expected to work through the CGI.




Why does Perl always comes in the way. CGI & Perl (language). I also don't know whats up with these two. Almost all the time I keep hearing these two in combination "CGI & Perl". This book is another great example CGI Programming with Perl Why not "CGI Programming with PHP/JSP/ASP". I never saw such things.




Because Perl is ancient (older than PHP, JSP and ASP which all came to being when CGI was already old, Perl existed when CGI was new) and became fairly famous for being a very good language to serve dynamic webpages via the CGI. Nowadays there are other alternatives to run Perl in a webserver, mainly mod_perl.




CGI Programming in C this confuses me a lot. in C?? Seriously?? I don't know what to say. I"m just confused. "in C"?? This changes everything. Program needs to be compiled and executed. This entirely changes my view of web programming. When do I compile? How does the program gets executed (because it will be a machine code, so it must execute as a independent process). How does it communicate with the web server? IPC? and interfacing with all the servers (in my example MATLAB & MySQL) using socket programming? I'm lost!!




You compile the executable once, the webserver executes the program and passes the data in the request to the program and outputs the received response. CGI specifies that one program instance will be launched per each request. This is why CGI is inefficient and kind of obsolete nowadays.




They say that CGI is deprecated. Its no more in use. Is it so? What is its latest update?




CGI is still used when performance is not paramount and a simple means of executing code is required. It is inefficient for the previously stated reasons and there are more modern means of executing any program in a web enviroment. Currently the most famous is FastCGI.


REFERENCES
http://stackoverflow.com/questions/2089271/i-never-really-understood-what-is-cgi/2089297#2089297




How to use TextMate like snippets in vim?

SkyHi @ Tuesday, August 10, 2010

Snippet is a piece of text which can be pasted into the document. Parts of it can be parametrized or calculated while pasting. Snippets can increase your productivity by letting you to write common chunks of code faster and without mistakes. One of the most famous snippet implementations is included in TextMate editor. In vim we have some of TextMate's snippet features bundled in snipMate script.




Installation

Get snipMate from vim website and unpack it to your ~/.vim directory.

How does it work?

Basically you need to write a keyword (called trigger) and press the key to replace it with full snippet. For example typing 'for ' and pressing while editing a PHP file:

for

expands to:

for ($i=0; $i < count; $i++)
{
}

Pressing key continuously moves you to the next defined tab stop. In this case you are able to adapt all expressions in 'for' loop and the last moves you to the position inside it.

Creating custom snippets

SnipMate comes with many predefined snippets but once you start using it, you need more. Fortunately it's easy to extend. Snippets are stored in ~/.vim/snippets directory. I started with reviewing the existing ones and adapted them to my coding standards. While doing this I got the idea about the snippets' structure and started with creating my own ones.
vim html snippets
Snippets are grouped by the file type. It is specified by a prefix in the snippet file name or a directory it was placed in (php.snippets vs php/foreach.snippet). The first version lets you to keep all file type related snippets in one place. The later is used to split your snippets into separate files. Format is slightly different between these two, so to make it simple I'll stick to the first one.

To define a new PHP snippet which expands 'get' keyword into a getter method put the code below into your ~/.vim/snippets/php.snippets file:

snippet get
$this->get${1}();${2}

Note: Snippets are indented with hard tabs. First tab is not expanded in the actual snippet.

Our snippet is run by 'get' trigger and has two tab stops defined. Firstly cursor is placed after '$this->get' to let you fill the getter's name. Second tab moves the cursor after the completed statement.

Tab stops and placeholders

Tab stop is a place where cursor goes next after pressing key. The format is:

${1}

The number defines the order of navigation through the snippet.

Note: It's possible to go back to the previous position with +.

Tab stop can have a placeholder with default value:

${2:default}

Default value is pasted into the snippet. You can either change it or leave it by moving to the next position.

Placeholder's value can be copied throughout the snippet:

Value of ${1:value} is copied here: $1 and here: $1 and snippet ends here: ${2}

All occurrences of the $1 variable will be replaced by the provided value. It's also possible to use a variable in an another variable:

${3}

Once you fill in the id value, it is copied to the name attribute. However, you can still change it if you want.

Multiple matches

Sometimes its needed to have few versions of the snippet. Good example here is the PHP's foreach statement which I use at least in two variations:

  • in regular PHP code:
    foreach ($values as $key => $value)
    {
    // code here
    }
  • in templates:
     $value): ?>
    // code here

Taking into account that $key variable can be omitted, in fact I use four different variations of foreach statement. So I defined all four of them:

snippet fore value
foreach ($${1:variable} as $${2:value})
{
${3}
}

snippet fore key => value
foreach ($${1:variable} as $${2:key} => $${3:value})
{
${4}
}

snippet fore value (template)

${3}


snippet fore key => value (template)
$${3:value}): ?>
${4}

Once I run 'fore' trigger vim lets me to choose which version of snippet I would like to use.

vim multi choice snippet

Learn it

There are some things about snipMate I didn't mention. For more knowledge visit its homepage and read the documentation in ~/.vim/doc/snipMate.txt. There are also many snippets available on the Internet which are a good reference.

Make it your habit

Making usage of snippets a habit for sure will boost your productivity. To take full advantage of it you need to extend your snippet library. I think it's best to create a new snippet once you feel one is missing and directly start using it. Waiting till "next time" lasts through the eternity.

REFERENCES

http://www.zalas.eu/how-to-use-textmate-like-snippets-in-vim

http://www.zalas.eu/tag/vim

http://www.catonmat.net/blog/vim-plugins-snipmate-vim/


The Secret to Learning Anything

SkyHi @ Tuesday, August 10, 2010
Some of the most important lessons I learned in college came from one professor,
Michael Mitzenmacher. Now,
this was a guy with a lot of papers to his name, tenured at Harvard,
working on some pretty darn complicated computer science theory (I took his
algorithms class). So you'd expect that I'd learn something important. But as
it turned out, the biggest lessons I learned from him weren't on the topics he
taught. I learned a secret that helped me learn much more effectively.


At one point when describing the problem sets in the class, he gave some advice
that stuck with me:


Don't suffer from Math Major syndrome

So, what you ask, is Math Major syndrome? Well, think of it this
way--if you are studying a hard problem, what's your first tendency? To get
lost in thought? To start at it, mulling over ideas in your head, waiting for
a flash of insight? If so, that's math major syndrome. It's the idea that you
can (or have to) solve problems entirely through a brilliant flash of insight,
without doing any actual work.




The alternative is quite simple:

Hard problems become easier by working through them with diagrams, effort and patience

In other words, don't just wait for answers to come to you--go out and find
them. Don't just use what's in your head--use paper, or the computer, or a
whiteboard, to draw out the ideas, try experiments, make the patterns
visible rather than waiting for a flash of insight.


I remember really learning this lesson during the first problem set--I'd
started it when it was handed out, but the night before it was due I still had
one problem left. I spent hours on that problem, but I spent it drawing out
equations, working through possiblities. Each one ended in failure, until I
had a flash of insight in the middle of writing out an equation. If I hadn't
worked through (and discarded) all those possibilities, I'd have had no hope of
solving that problem.


So how do you apply this principle in practice?

Program Program Program

If you're learning to program, you should be programming. Work practice problems while you
read tutorials--in fact,
you're probably better off in most cases working practice problems than
you are reading about programming. (You will need to read, but without
practice, that reading means nothing.)


In fact, if you're just learning to program, then I suggest that you stop
reading this article right now and go write some code (or get yourself
set up with a compiler and
then go write some code). But not something you know how to solve--try to
write a program that is just a little bit scary or hard. You should feel just
a bit scared that you won't be able to do it.

Draw it Out

A second corollary to the principle is that you're better off using paper than
trying to imagine everything. In fact, I can't say enough about the importance
of drawing diagrams. A lot of things in programming sound very abstract or
difficult to describe in words, but they can be quickly shown with a picture.
Computer memory, for example, can be thought of as a long block of cells
(almost like in an Excel spreadsheet). Drawing out each piece of memory in
your program (when dealing with pointers or data structures) can really help
visualize what is going on. You can also write out recursion manually by
showing each recursive call with its arguments and return value.


But even simpler concepts become clear when you draw them or work through them
step by step--having trouble understanding a complex piece of code? Write out
the different variables and how they are modified. For example, the boolean
expression

! a || b


(in other words, NOT a OR b)

has a very specific meaning in English: "if a is true, then b must be true";
this could be useful for checking user inputs ("if the user pressed exit, then
the game must be over--otherwise, print out an error"). But it's not
at all obvious what ! a || b means unless you actually work through it. What
do I mean?

The statement "if a is true, then b must be true" requires that:

if a = true, b must be true<br />if a = false, b can be either true or false<br />

How does that work for the expression "! a || b? You can draw out the table by
writing a in one column, b in a second, and whether the condition is satisfied
result in a third:

ab! a || b
001
011
111
100

Now you can more quickly see that the table expresses the English condition.
The condition is satisfied in all the cases except when a is true and b is
false (clearly, that can't satisfy an expression that says, "if as is true,
then b is true"!)



Being able to look at the data really helps!

Related Articles


Monday, August 9, 2010

Apache Tips & Tricks

SkyHi @ Monday, August 09, 2010

Here you can find various tips & tricks for configuring and administrating Apache that I found to be useful. Once I will add a new tip, I’ll link it here so you can use this page as a main placeholder for all the tips I will post in the future. Each tip will consist in a very short description, what is it used for, where can you apply it (globally, per directory or per virtual hosts, if it can be activated without administrative privileges in .htaccess) and of course a how to implement it. I will try to keep each tip as short as possible and on a single topic so you can go directly to what you are looking for.
If you would like to submit your own tip in this section, please feel free to contact me, and if I will like your post I will publish it.


REFERENCES
http://www.ducea.com/2006/06/08/apache-tips-tricks/

Color Bash Prompt

SkyHi @ Monday, August 09, 2010

There are a variety of possibilities for Bash's prompt (PS1), and customizing it can help you be more productive at the command line. You can add additional information to your prompt, or you can simply add color to it to make the prompt stand out.

Contents

[hide]

Basic prompts

The following settings are useful for distinguishing the root prompt from non-root users.

  • Edit Bash's personal configuration file:
$ nano ~/.bashrc
  • Comment out the default prompt:
#PS1='[\u@\h \W]\$ '
  • Add the following green prompt for regular users:
[chiri@zetsubou ~]$ _
PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\] '
  • Edit root's .bashrc file; copy it from /etc/skel if the file is not present:
# nano /root/.bashrc
  • Assign a red prompt for root:
[root@zetsubou ~]# _
PS1='\[\e[1;31m\][\u@\h \W]\$\[\e[0m\] '

Slightly fancier prompts

  • A green and blue prompt for regular users:
chiri ~/docs $ echo "sample output text"

sample output text

chiri ~/docs $ _
PS1='\[\e[0;32m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[1;32m\]\$\[\e[m\] \[\e[1;37m\]'

This will give a very pleasing, colorful prompt and theme for the console with bright white text.

The string above contains color-set escape sequences (start coloring: \[\e[color\], end coloring: \[\e[m\]) and information placeholders:

  • \u - Username. The original prompt also has \h, which prints the host name.
  • \w - Current absolute path. Use \W for current relative path.
  • \$ - The prompt character (eg. '#' for root, '$' for regular users).

The last color-set sequence, "\[\e[1;37m\]", is not closed, so the remaining text (everything typed into the terminal, program output and so on) will be in that (bright white) color. It may be desirable to change this color, or to delete the last escape sequence in order to leave the actual output in unaltered color.

  • A red and blue prompt for root:
root ~/docs # echo "sample output text"

sample output text

root ~/docs # _
PS1='\[\e[0;31m\]\u\[\e[m\] \[\e[1;34m\]\w\[\e[m\] \[\e[0;31m\]\$ \[\e[m\]\[\e[0;32m\]'

This will give you a red designation and green console text.

Advanced prompts

Load/Mem Status for 256colors

This isn't even pushing the limits.. other than using 'sed' to parse the memory and load average (using the -u option for non-buffering), and the builtin history to save your history to your HISTFILE after every command, which I have found incredibly useful when dealing with crashing shells or subshells, this is essentially just making BASH print variables it already knows, making this extremely fast compared to prompts with non-builtin commands.

This prompt is from AskApache.com's BASH Power Prompt article, which goes into greater detail. It is especially helpful for those wanting to understand 256 color terminals, ncurses, termcap, and terminfo.

This is for 256 color terminals, which is where the \033[38;5;22m terminal escapes come from.

802/1024MB 1.28 1.20 1.13 3/94 18563

[5416:17880 0:70] 05:35:50 Wed Apr 21 [srot@host.sqpt.net:/dev/pts/0 +1] ~

(1:70)$ _
 PROMPT_COMMAND='history -a;echo -en "\033
[m\033[38;5;2m"$(( `sed -nu "s/MemFree:[\t ]\+\([0-9]\+\) kB/\1/p"
/proc/meminfo`/1024))"\033[38;5;22m/"$((`sed -nu "s/MemTotal:[\t ]\+\([0-9]\+\) kB/\1/Ip"
/proc/meminfo`/1024 ))MB"\t\033[m\033[38;5;55m$(< /proc/loadavg)\033[m"'
PS1='\[\e[m\n\e[1;30m\][$$:$PPID \j:\!\[\e[1;30m\]]\[\e[0;36m\] \T \d \[\e
[1;30m\] [\[\e[1;34m\]\u@\H\[\e[1;30m\]:\[\e[0;37m\]${SSH_TTY} \[\e
[0;32m\]+${SHLVL}\[\e[1;30m\]] \[\e[1;37m\]\w\[\e[0;37m\] \n($SHLVL:\!)\$ '


List of colors for prompt and Bash

Add this to your Bash file(s) to define colors for prompt and commands:

txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
bldblk='\e[1;30m' # Black - Bold
bldred='\e[1;31m' # Red
bldgrn='\e[1;32m' # Green
bldylw='\e[1;33m' # Yellow
bldblu='\e[1;34m' # Blue
bldpur='\e[1;35m' # Purple
bldcyn='\e[1;36m' # Cyan
bldwht='\e[1;37m' # White
unkblk='\e[4;30m' # Black - Underline
undred='\e[4;31m' # Red
undgrn='\e[4;32m' # Green
undylw='\e[4;33m' # Yellow
undblu='\e[4;34m' # Blue
undpur='\e[4;35m' # Purple
undcyn='\e[4;36m' # Cyan
undwht='\e[4;37m' # White
bakblk='\e[40m' # Black - Background
bakred='\e[41m' # Red
badgrn='\e[42m' # Green
bakylw='\e[43m' # Yellow
bakblu='\e[44m' # Blue
bakpur='\e[45m' # Purple
bakcyn='\e[46m' # Cyan
bakwht='\e[47m' # White
txtrst='\e[0m' # Text Reset

To use in commands from your shell environment:

$ echo -e "${txtblu}test"
test
$ echo -e "${bldblu}test"
test
$ echo -e "${undblu}test"
test
$ echo -e "${bakblu}test"
test

To use in a prompt (note double quotes and \[ \] used by the shell to count proper length):

PS1="\[$txtblu\]foo\[$txtred\] bar\[$txtrst\] baz : "

Prompt escapes

The various Bash prompt escapes listed in the manpage:

Bash allows these prompt strings to be customized by inserting a
number of backslash-escaped special characters that are
decoded as follows:

\a an ASCII bell character (07)
\d the date in "Weekday Month Date" format (e.g., "Tue May 26")
\D{format} the format is passed to strftime(3) and the result
is inserted into the prompt string an empty format
results in a locale-specific time representation.
The braces are required
\e an ASCII escape character (033)
\h the hostname up to the first `.'
\H the hostname
\j the number of jobs currently managed by the shell
\l the basename of the shell's terminal device name
\n newline
\r carriage return
\s the name of the shell, the basename of $0 (the portion following
the final slash)
\t the current time in 24-hour HH:MM:SS format
\T the current time in 12-hour HH:MM:SS format
\@ the current time in 12-hour am/pm format
\A the current time in 24-hour HH:MM format
\u the username of the current user
\v the version of bash (e.g., 2.00)
\V the release of bash, version + patch level (e.g., 2.00.0)
\w the current working directory, with $HOME abbreviated with a tilde
\W the basename of the current working directory, with $HOME
abbreviated with a tilde
\! the history number of this command
\# the command number of this command
\$ if the effective UID is 0, a #, otherwise a $
\nnn the character corresponding to the octal number nnn
\\ a backslash
\[ begin a sequence of non-printing characters, which could be used
to embed a terminal control sequence into the prompt
\] end a sequence of non-printing characters

The command number and the history number are usually different:
the history number of a command is its position in the history
list, which may include commands restored from the history file
(see HISTORY below), while the command number is the position in
the sequence of commands executed during the current shell session.
After the string is decoded, it is expanded via parameter
expansion, command substitution, arithmetic expansion, and quote
removal, subject to the value of the promptvars shell option (see
the description of the shopt command under SHELL BUILTIN COMMANDS
below).

Positioning the cursor

The following sequence sets the cursor position:

\[\033[;f\]

The current cursor position can be saved using:

\[\033[s\]

To restore a position, use the following sequence:

\[\033[u\]

The following example uses these sequences to display the time in the upper right corner:

PS1=">\[\033[s\]\[\033[1;\$((COLUMNS-4))f\]\$(date +%H:%M)\[\033[u\]"

The environment variable COLUMNS contains the number of columns of the terminal. The above example substracts 4 from its value in order to justify the five character wide output of date at the right border.

Return value visualisation

WARNING WARNING WARNING WARNING
This seemed to me to have some bugs, see the entry I added to the discussion page.

Add this line if you want to see the return value of the last executed command. This should work with any kind of prompt as long as it does not need PROMPT_COMMAND:

PROMPT_COMMAND='RET=$?; if [[ $RET -eq 0 ]];
then echo -ne "\033[0;32m$RET\033[0m ;)";
else echo -ne "\033[0;31m$RET\033[0m ;("; fi; echo -n " "'

It will look like this:

0 ;) harvie@harvie-ntb ~/ $ true
0 ;) harvie@harvie-ntb ~/ $ false
1 ;( harvie@harvie-ntb ~/ $

Zero is green and non-zero is red. There is also the smiley indication (replace it with anything you want); so your prompt will smile if the last operation was succesful.

Advanced return value visualisation

If you want colors, you need to set $RED and $GREEN values:

RED='\e[0;31m'
GREEN='\e[0;32m'

You have to specify these values in Bash's configuration files:

#return value visualisation
PROMPT_COMMAND='RET=$?;'
RET_VALUE='$(echo $RET)' #Ret value not colorized - you can modify it.
RET_SMILEY='$(if [[ $RET = 0 ]]; then echo -ne "\[$GREEN\];)"; else echo -ne "\[$RED\];("; fi;)'

Then you can use $RET_VALUE and $RET_SMILEY variables in the prompt. Note that you need use double quotes:

#prompt
PS1="$RET_VALUE $RET_SMILEY : "

This will give you basic prompt:

0 ;) : true
0 ;) : false
1 ;( :

But you will probably want to use $RET_VALUE or $RET_SMILEY in your own prompt, like this:

PS1="\[$WHITE\]$RET_VALUE $RET_SMILEY \[$BLUE\]\u\[$RED\]@\[$EBLUE\]\h\[$WHITE\] \W
\[$ERED\]\\$\[$EWHITE\] "

Wolfman's

After reading through most of the Bash Prompt Howto, the author developed a color bash prompt that displays the last 25 characters of the current working directory. This prompt should work well on terminals with a black background. The following code goes in file ~/.bashrc.

  • Add the bash_prompt_command function. If you have a couple directories with long names or start entering a lot of subdirectories, this function will keep the command prompt from wrapping around the screen by displaying at most the last pwdmaxlen characters from the PWD. This code was taken from the Bash Prompt Howto's section on Controlling the Size and Appearance of $PWD and modified to replace the user's home directory with a tilde.
##################################################
# Fancy PWD display function
##################################################
# The home directory (HOME) is replaced with a ~
# The last pwdmaxlen characters of the PWD are displayed
# Leading partial directory names are striped off
# /home/me/stuff -> ~/stuff if USER=me
# /usr/share/big_dir_name -> ../share/big_dir_name if pwdmaxlen=20
##################################################
bash_prompt_command() {
# How many characters of the $PWD should be kept
local pwdmaxlen=25
# Indicate that there has been dir truncation
local trunc_symbol=".."
local dir=${PWD##*/}
pwdmaxlen=$(( ( pwdmaxlen < ${#dir} ) ? ${#dir} : pwdmaxlen ))
NEW_PWD=${PWD/#$HOME/\~} local pwdoffset=$(( ${#NEW_PWD} - pwdmaxlen ))
if [ ${pwdoffset} -gt "0" ] then NEW_PWD=${NEW_PWD:$pwdoffset:$pwdmaxlen}
NEW_PWD=${trunc_symbol}/${NEW_PWD#*/} fi }
  • The next fragment generates the command prompt and various colors are defined. The user's color for the username, hostname, and prompt ($ or #) is set to cyan, and if the user is root (root's UID is always 0), set the color to red. The command prompt is set to a colored version of Arch's default with the NEW_PWD from the last function.
Also, make sure that your color variables are enclosed in double and not single quote marks. Using single quote marks seems to give Bash problems with line wrapping correctly.
bash_prompt() {
case $TERM in
xterm*|rxvt*)
local TITLEBAR='\[\033]0;\u:${NEW_PWD}\007\]'
;;
*)
local TITLEBAR=""
;;
esac
local NONE="\[\033[0m\]" # unsets color to term's fg color

# regular colors
local K="\[\033[0;30m\]" # black
local R="\[\033[0;31m\]" # red
local G="\[\033[0;32m\]" # green
local Y="\[\033[0;33m\]" # yellow
local B="\[\033[0;34m\]" # blue
local M="\[\033[0;35m\]" # magenta
local C="\[\033[0;36m\]" # cyan
local W="\[\033[0;37m\]" # white

# emphasized (bolded) colors
local EMK="\[\033[1;30m\]"
local EMR="\[\033[1;31m\]"
local EMG="\[\033[1;32m\]"
local EMY="\[\033[1;33m\]"
local EMB="\[\033[1;34m\]"
local EMM="\[\033[1;35m\]"
local EMC="\[\033[1;36m\]"
local EMW="\[\033[1;37m\]"

# background colors
local BGK="\[\033[40m\]"
local BGR="\[\033[41m\]"
local BGG="\[\033[42m\]"
local BGY="\[\033[43m\]"
local BGB="\[\033[44m\]"
local BGM="\[\033[45m\]"
local BGC="\[\033[46m\]"
local BGW="\[\033[47m\]"

local UC=$W # user's color
[ $UID -eq "0" ] && UC=$R # root's color

PS1="$TITLEBAR ${EMK}[${UC}\u${EMK}@${UC}\h ${EMB}\${NEW_PWD}${EMK}]${UC}\\$ ${NONE}"
# without colors: PS1="[\u@\h \${NEW_PWD}]\\$ "
# extra backslash in front of \$ to make bash colorize the prompt
}
  • Finally, append this code. This ensures that the NEW_PWD variable will be updated when you cd somewhere else, and it sets the PS1 variable, which contains the command prompt.
PROMPT_COMMAND=bash_prompt_command
bash_prompt
unset bash_prompt

KitchM's

These prompts offer a little more flash and visual clarity. Note that the use of red in the root user's prompt should provide ample warning. That's not to say someone couldn't use flashing text or arrow to do even more, but these will give you a good starting point.

First, change the default background in your terminal preferences (this example uses Xfce's Terminal program) to #D2D2D2, and the text color to #000000. The font is listed as DejaVu Sans Mono Book 12. The cursor color is #00AA00, and the tab activity color is #AF0000.

Second, in ~/.bashrc and right after the PS1= line, enter a new line with the following:

PS1='\e[1;33;47m\u \e[1;32;47mon \h \e[1;35;47m\d \@\e[0;0m\n\e[1;34m[dir.= \w] \# > \e[0;0m'

And then place a # in front of the first PS1 line to remark it out.

Third, for root user, edit /root/.bashrc in the same manner to include:

PS1='\e[1;31;47m\u \e[1;32;47mon \h \e[1;35;47m\d \@\e[0;0m\n\e[1;31m[dir.= \w] \# > \e[0;0m'

Don't forget to comment out the old line.

These are double-line prompts, and they should look something like these:

User-

                                           
Username on myhost Sun Jan 15 12:30 PM
[dir.= /home/username] 1 >

Root-

                                           
Root on myhost Sun Jan 15 12:30 PM
[dir.= /etc/rc.d] 1 >

You'll note that the background colors make them easier to read, and the text colors just keep things interesting. There's a lot of leeway to make them personalized, just with the use of colors. Enjoy!

Set xterm window title

You can use the ${XTERM_TITLE} variable at the beginning of the prompt to set xterm title (if available) to directory@user@hostname. Or you can modify it using regular prompt escape sequences:

#set xterm title
case "$TERM" in
xterm | xterm-color)
XTERM_TITLE='\[\033]0;\W@\u@\H\007\]'
;;
esac;

Different colors for text entry and console output

If you don't reset the text color at the end of your prompt, both the text you enter and the console text will simply stay in that color. If you want to edit text in a special color but still use the default color for command output, you'll need to reset the color after you press enter, but still before any commands get run. To do this, install a DEBUG trap in your ~/.bashrc like this:

trap 'echo -ne "\e[0m" > $(tty)' DEBUG

And add yourself to the tty group:

sudo gpasswd -add  tty

Now bash will execute the DEBUG trap every time before running a command. We have to echo the reset sequence directly to the terminal device (as reported by tty), otherwise the sequence would become part of the command output (and thus part of any redirected data). To be able to write to the terminal device we need to be part of the tty group.

This is a bit of a hack, so use it at your own risk.

External links

Sunday, August 8, 2010

Learn Python The Hard Way

SkyHi @ Sunday, August 08, 2010

This is the site for the book "Learn Python The Hard Way". The book is a very beginner book for people who want to learn to code. If you can already code then the book will probably drive you insane. It's intended for people who have no coding chops to build up their skills before starting a more detailed book.



For Learners



You can download the book here:





The book is very simple:



  • 52 exercises in all.
  • 26 cover just input/output, variables, and functions.
  • 26 cover logic (boolean algebra, if-statements, while-loops, etc.)


Each exercise is one or two pages and follows the exact same format. You type each one in (no copy-paste!), make it run, do the extra credit, and then move on. If you get stuck, at least type it in and skip the extra credit for later.



Other Books



You might also want to check out these other books if you find this book too boring or annoying:





For Potential Contributors



The book is currently a work in progress, but I'm looking for people to contribute proposed lessons using this wiki. You can also submit tickets with errors you find.



This repository is also available as a fossil repository. Fossil is a distributed version control that includes the wiki, tickets, source, and everything you need to get the whole site. You can use fossil to grab the whole thing and access it offline and contribute to the book.



Writing Proposed Exercises



Use this wiki to start writing your own exercises. You should get the latest version of the book and read it. You should then try the exercises yourself so you get a feel for them.



Next you just write an exercise on the Proposed Exercises page. Just add your exercise as a bullet point with a link and then write it. I leave it to you to figure out how to find the wiki formatting and make the page. If you can't then you probably shouldn't be writing exercises right now.



Finally, make sure your name is on the Exercise so that we know who to blame...credit for its creation.


REFERENCES
http://learnpythonthehardway.org/index




Common Programmer Health Problems

SkyHi @ Sunday, August 08, 2010


I'm currently working on the last few lessons in Learn Python The Hard
Way
and I want to include a lesson
on general health problems programmers run into during their careers. I
find many programmers seem to ignore their body's physical state when
they're coding, most likely due to the intense concentration required.
I'm hoping other people could benefit by simply understanding a few
health related problems programming has almost caused me or caused many
other people I know, and how I avoided them.



I probably won't put this whole blog post into LPTHW since it's a bit
much, but I will make a shorter version of it. Please feel free to let
me know if you hate it or like it or if you have some additional
resources I could reference.



My Background And Qualifications



In the past I was a top qualified soldier in the US Army, and I have
studied many martial arts. These days I'm not as into working out and
studying martial arts as I used to be, instead focusing on yoga,
meditation, and simpler activities. When I was younger I was incredibly
fit, and still am because of habits and practices I ingrained in myself
from an early age.



First a quick list of martial arts I've studied for various periods of
time: Ninjitsu, Aikido, Judo, Muay Thai, Wing Tsung, Capoeira, and
Arnis in no particular order. I would say only Muay Thai is the one I
studied most consistently, for probably about 6 years. The others I
studied for about 1 or 2 years if I could. I moved around a lot so the
only way to study was whatever was in the area.



Also, in the US Army I was at the top of my physical fitness exam, going
from barely passing to maximum scores consistently in about 2 years.
This involved about 2-4 hours of working out nearly every day if I
remember it correctly, which in the Army isn't that difficult. There's
really nothing else to do.



Finally, I've been the exact same weight, flexibility, and nearly the
same strength my whole life, whether I worked out or not, which means
that I probably can't tell you about how to lose weight. I'm most
likely genetically predisposed to be this way. That means you should
adapt my advice to fit your life and what you've found healthy.



With all that being said, as I've gotten older I much more enjoy the
less violent and more "supple" forms of exercise. I feel Yoga is
excellent exercise because it's deceptively difficult. I'd also vote
for Pilates, swimming, dance, and anything that doesn't cause direct
impact on my body. I especially have to watch out for my hands for
reasons I'll explain in a bit.



Alright, that should give you an idea that I know something, but more
importantly, while doing all of these things, I also wrote software
professionally. After getting out of the Army I averaged about 8-16
hours of coding and study a day. I also touch type and I play guitar,
yet I've mostly avoided carpel tunnel and other RSI problems.



Hopefully, my experience maintaining my physical health will help you
gain some or keep yours.



Common Problems Programmers Face



Programming is a deceptively damaging field to be in, partly because it
doesn't seem like you're doing much, and also because of the attitude
many programmers have toward their body. You should care about keeping
yourself healthy because, when your body is in good shape, that removes
"friction" from your mental capacity so that it can focus on important
things rather than annoying little problems with your physical wellness.



Obviously the advice on eating right, going outside, getting exercise
has been said by everyone. I'm not really going to tell you how to eat,
or work out, or how to do a martial art or something else to stay
healthy. If you are interested in those things, then please find a
professional who can train you and help you.



What I do want to cover are a set of particular problems programmers
have from their daily profession. These are just simple really obvious
things that for some reason programmers don't realize aren't supposed to
be happening:



  • Pain in your wrists from Repetitive Strain Injury (RSI).
  • Problems with your eyes from staring at moving print for extended periods.
  • Back problems from poor posture, especially in the lower back and upper shoulders.
  • Bowel and urinary issues from not crapping and pissing when you should.
  • Dehydration from drinking too much caffeine and not enough water.
  • Problems with hemorrhoids and the prostate for guys from sitting too much. Yep, I'm gonna go there.
  • Vitamin D deficiency from lack of sunshine.
  • Sleeping disorders from staying up late and drinking too much coffee.
  • General stiffness and soreness from a lack of stretching in general.


I've had to struggle with all of these problems at one point in my life
because of programming, guitar, or actually from lifting weights wrong.
In each case I was able to get healthy and then avoid it the rest of my
life, and really only deal with a few problems periodically. You may
think some of these are stupid, but believe me, many programmers have
these problems for various reasons even if you might not.



The General Cause



Overall the general cause of all of these problems can be summarized as
treating programming as an obsession. You may want to be very good at
it, like I did, so you exclude everything else in your life in order to
master it. You don't go to the bathroom, you have macho 10 hour coding
sessions, you don't eat right, and all manner of mythological beliefs
about "real programmers".



Truth is real programmers are kind of idiots. They don't eat right.
They don't have sex on a regular basis. They can't run without gasping
for breath. They have huge problems with their internal organs not
caused by disease. Really, it's just not worth it if you have to kill
yourself to be good at something.



So, as you read through each of these problems and how I've cured them,
remember that it's all about just having a balanced life and not being
obsessed with coding or your business. Trust me when I say you will
actually become better if you take it easy on yourself and stay
healthy.



Wrist Pain



This is probably the one I struggle with the most, because I code and
play guitar quite frequently and for long periods of time. I've had
pain in my wrists periodically since I started coding professionally at
22, but I always had a set of Aikido exercises I did to get my wrists
straight.



You see, Aikido has these fantastic wrist exercises that make your
wrists strong and supple at the same time. They developed the exercises
to avoid injuries during practice since many of the Aikido techniques
involve wrenching, ripping, and breaking the joints in the arms, wrists,
and shoulders.



For me these exercises have always fixed any misalignment and pain, and
they've allowed me to code for long periods of time without much
trouble. Typically the only time I'll have problems is if I've switched
keyboards and have a new odd keyboard layout, but if I do I simply do
the exercises for about a week every time I go to code and they get
strong again.



Now, if you have serious carpel tunnel or another kind of RSI then
consult your physician before trying these. If you do them, then start
very slowly, and do not try to make them hurt. Stretching should not
hurt, it should just be "mildly uncomfortable". If it hurts, then you
are straining to do the stretch.



What you actually want to do is relax into every stretch you do. It's
hard to explain, but instead of forcing your joint to a certain
position, bring it to that position and then think about relaxing it or
"letting" it move a bit further.



Keep this in mind, and then here's a set of videos that show you how to
do each exercise:





Here's how you use these exercises before you sit down to type (every
time!):



  1. First, you need to warm up, so put your hands out in front of you and
    grab at the air as fast as you can 20 times. Then shake your hands,
    then rotate your wrists 10 times one direction and 10 times another.
  2. Start with the first exercise you're best at, and do 5-10 of them at
    a medium speed.
  3. Continue through each one, but after each one shake your hands and
    arms and rotate your wrists to realign them. These exercises do some
    moving of the bones in your wrist, so shaking them sort of makes them
    settle back in.
  4. NEVER do too much strain on your wrists. Do just enough to get them
    going and feeling supple and relaxed, but the motto "no pain no gain"
    will only damage you.


Do these each time you go to type, every day, and any time you stop. It
doesn't take long to do them, and after a bit of discomfort as your
wrists start to adapt and get realigned, you'll start to feel better.



One more time though: DO NOT DO THIS WITHOUT CONSULTING A DOCTOR
FIRST
You do these at your own risk, so don't sue me if you fuck up
your wrists because you didn't pay attention. These exercises have been
done for maybe thousands of years in various martial arts, so I know
they aren't dangerous but everyone is different. You could screw
yourself up bad if you do them wrong, so if it hurts stop doing them
and talk to a doctor!



Guitarists Are Worse



Programmers will get RSI but it's nothing compared to what guitarists
and bassists get. For various stupid reasons there's myths around many
of the big name musicians and their claims of studying "8 hours a day"
or "16 hours a day!". Because of this guitarists will kill themselves
and damage their hands making it impossible to play.



Guitar is a hard instrument on your hands, so even a little pain can put
you out of commission. I learned this the hard way in school because,
like an idiot, I believe my instructors when they said I had to study 8
hours a day. I literally thought they meant 8 hours straight, so I did
that for about a month and then BAM!



Fucked up my thumb and gave it a bone spur and all my fingers hurt like
crazy. My wrists were solid, but my fingers just couldn't take it.
Like an idiot I didn't listen to what I already knew which is any new
activity has to be gradually increased like any other work out.



The only way I could fix this, and it took nearly 1.5 years, was to do
the following:



  1. Find guitars that didn't hurt my hands. The idea that you can "play
    any guitar" is crap. Get the best guitar you can that doesn't hurt you.
  2. Do the above exercises, and then some more for my fingers.
  3. Start slowly rebuilding my fingers and thumb by doing a set of
    exercises to improve their strength and relaxation.
  4. Constantly focus on relaxing while playing so that I could use a
    lighter touch.
  5. Avoid bends as they hurt my hands and caused me injuries.
  6. Changed my position and playing style so that I'm able to move around
    quickly without having to grip the guitar, instead my thumb is on the
    back of the guitar where it's comfortable.
  7. Adjusted the height of my guitar so that it was comfortable
    on my shoulder and hands to play.
  8. Always play standing up now, rarely sitting down for long periods of
    time because the position is awkward, and if I do I keep the same
    position.


After doing that for the last year my hands are finally feeling good and
have healed up, and I've not got good habits that prevent me from
injuring myself. I'm an old guy so these things are important, but that
also means I can't do anything that might hurt my hands.



My hands are my life right now, so that means no boxing, capoeira, or
anything else I really want to study. I have to much riding on my hands
to waste it on a punching bag.



Eye Strain



I think this isn't as much of a problem as it was for me, but you have
to watch out for your eyes. I had perfect better than 20/20 vision when
I was younger, but from decades of computer use my eyes are "slightly
off". I have a minor correction in glasses and these days I just wear
them all the time even if I only need them a little bit. The world is
just annoyingly fuzzy without them.



Back in the bad old days we stared at CRT screens all day, which had
horrible annoying flicker and screwed up quite a few eyes. These days
it's not the flicker so much as the poor font rendering on most LCD
screens. Thanks to patents owned by Apple (I think) many computers
can't render fonts well on an LCD screen. Some folks though think
Apple's font rendering looks "fuzzy" so your mileage may vary
considerably.



In my case I try to get out for about 2 hours a day and not look at a
computer. Either I do something that doesn't involve reading like play
guitar, or I go for a walk or to the park. I may not do this for a full
2 hours but I try to not start at a computer screen for at least 2 hours
a whole day.



This will also help with headaches you might have. Frequently
programmers will think that the lighting in a room is what gives them
headaches from using a computer, but really it's bad posture, shitty
fonts, not drinking enough water, and just using the computer for too
long at a stretch.



Instead of doing some extreme thing like turning out all the lights in
your office, just have good lighting and use a color scheme that fits
the type of LCD you have and the room's lighting. It's the combination
of room/area lighting, LCD brightness, LCD quality, fonts, and your
color scheme that will make you feel better.



But most importantly, just take a break.



Back Problems



I've been extremely luck to have a good solid back most of my life.
Even though I've been sitting in a chair for a good portion of that
life, I still have a good flexible and strong back.



For me, the problem is in my upper back, neck, and shoulders. I tend to
hunch over the keyboard and have to force myself to sit up straight.
In fact right when I started typing this section I noticed I wasn't
sitting up straight and had to correct it.



Now, the choice of chair matters, and I tend to like either Aeron chairs
of some kind of solid small stool or bench. I'm currently very much
liking my little $40 piano bench I used to sit on to practice piano.
It doesn't have a back so it forces me to sit up straight more often and
engage my core muscles (stomach and back muscles).



For my shoulders though it's entirely stress. I tend to "scrunch up" my
shoulders when I'm focused intensely and that causes my whole upper back
to hurt, sending pain all the way up my neck and head. It gets really
bad if I practice guitar for long periods at a time.



What I've found helps the most is stretching your upper arms and doing
push-ups. Stretching your upper arms is as simple as grabbing a door
jam, grabbing it, and pulling each arm or both arms in a different
direction. Try these if you're feeling stiff:



  1. Grab a door jam with one arm so your palm faces the front of your
    body, then pull your shoulder out so you stretch your chest and the
    front of your shoulder.
  2. Grab the door jam with one arm so that your arm crosses your body,
    and again with your palm facing the front (kind of backwards), then pull
    so your shoulder at the back is stretched.
  3. Put both arms on the door jam in front of you, right above your head,
    and stand away from it a bit so that you lean down and pull your arms
    above you and back.


If you do that, and also rotate your shoulders and shake your body out
you'll start to feel much better. Maybe combine this with your wrist
stretches before you work each day.



Another big help is doing some push-ups. I wouldn't do these at work or
before you work because it will make you tired and make it hard to work.
I'd instead just do 10 a night before you go to sleep. Just 10 will do
a lot for your chest, back, wrists, and neck. Don't do them very fast,
but do them slowly and focus on balancing your body when you do them.



Dehydration



This one is simple, and I'm guilty of it quite frequently. I find I
drink a ton of coffee, and because of that I have to make sure I drink
some water too. If I don't I get headaches and really don't feel right.
The problem with dehydration is it's hard for you to tell you're
suffering from it until it's too late.



What I suggest, and what I've started doing more, is that you drink a
bottle or cup of water with every non-water beverage you drink. I also
recommend you ditch the sodas. They're just full of nasty fake sugar
that make you fat and cause diabetes, and they're not rehydrating you.
If you gotta drink something then plain black coffee is pretty damn
good, but again drink some water with it.



Bowel And Urinary Problems



Alright the next two are kinda gross so I won't go into what happened to
me, but I'll say this:




Go to the fucking bathroom right when you have to go. Don't wait.




You wouldn't believe how useful this advice is and I really wish I'd
been told it when I was younger. Because I would code non-stop like a
"real programmer" I would skip bathroom breaks and hold it in for far
too long. The problem is with bowel movements your body just stops
telling you to crap, and then it builds up.



This eventually leads to constipation and it's a motherfucker on your
health. For your urinary tract it causes problems that are less
important, but you can get infections and other nice little surprises.



If you've already screwed up, the best thing to do is go get some fiber
tablets and take them then stay home 'cause it's gonna get ugly.



Then, when you feel you need to go, just get up and go for the love of
god. I'm telling you, your brilliant idea will come more naturally
after you poop.



Hemorrhoids and Prostate Health



The other problem you have from not using the restroom when you should
is that you get hemorrhoids. Yeah yeah, I know, really gross and I
promise this is the only time I'm gonna mention them ever. But, many
programmers have them and are ashamed to talk about them or even know
what causes them so I'm going to lay it out for you. I've actually done
all of these but only had them once or twice:



  1. Sitting for a long period of time.
  2. Lifting heavy weights without proper equipment.
  3. Not taking a dump when you actually need to.
  4. Forcing a dump when you don't need to.
  5. The worst one though: Sitting on the toilet reading.


This last one is the killer let me tell you. If you don't have to go,
then do not sit on the can hanging out. What this does is put all the
weight of your body and bowels on your already probably screwed up rectum
and then pushes it out. Nasty. That also then causes hemorrhoids
because the pressure increases in your blood vessels unnaturally.



These are just freaking gross, but they're also potentially harmful.
Yes, you can get some that are so bad you bleed all over the place. If
you have some, please go see your doctor and deal with it. You may need
surgery, so just do it. I didn't but man it was close. One year I was
lifting weights, working in a warehouse, coding non-stop, and not using
the bathroom.



Yep, I was idiot, so don't make the same mistake. Make sure you do
these three things to keep your ass healthy:



  1. Eat some veggies regularly, or eat some fiber tablets at least.
  2. Go to the bathroom right when you have to go.
  3. Don't force pressure down there in any way.


This can also damage your prostate if you aren't careful, but usually
that's from sitting on your ass all day. Just get up and walk around or
take breaks and you'll fix that problem. If you find blood in your
urine or you have problems peeing, go see a doctor because it might be
more serious. If you pee a lot it can also be bad, so again see a
doctor.



Vitamin D Deficiency



Vitamin D is weird. You really only get it from the Sun but you don't
need much direct sunlight to get it. Maybe like 5-30 minutes depending
on how strong it is. It's also tied to your calcium levels, and a lack
of phosphate, but if you eat regularly and something other than potato
chips that shouldn't be a big problem.



Some of the things you can get are depression, screwed up teeth, pain in
weird places like in the bones in your arms, cramping muscles, and just
generally feeling like crap. If you're really bad you might need to get
a prescription from a doctor, but usually you can just make a plan to go
outside for 30 minutes when the Sun is high in the sky.



In fact, I think this is one of the problems with catered food at many
startups here in the Valley. Since you are inclined to stay in the
office and eat food and constant leftovers, and because many offices
have poor lighting, you tend to not go outside when the Sun is out.
Combine that with poor sleeping habits and you can really be screwing up
your vitamin D levels without knowing it.



Just something as simple as not eating the catered lunches and walking
outside at noon to get your food could help more than you know. Anyway
the food is better.



I got minor vitamin D deficiency when I lived in Vancouver and Seattle.
Up there you just don't have sunshine for months on end, and for me that
was a killer. Some people can handle it, but for people like me who
lived on a tropical islands in his teens, this was just murder.



So, if you have sunshine, get out and grab some when you can.



Sleeping Disorders



I've always had a flexible sleep schedule, usually depending on the
season and the region. In some areas I trend toward a night owl persona
and stay up really late doing things then sleeping in. Lately since
moving to SF I've been getting up earlier and not staying up as late,
and I've actually been feeling really good lately.



Sometimes though, and I'm not sure why, I feel way more productive in
both music and coding late at night, or very early in the morning. I
think it's because I'm still in a tired state and so my brain is
relaxed. I also think it's because it's very quiet and I can just hang
out and think with no distractions.



Either way, this need to either get up very early or stay up very late
sort of screws with my sleep schedule. I find that I much prefer
getting up early as I get older. I feel more awake and rested during
the day. If I stay up late and sleep in I feel like I have a hangover
and I can get headaches.



If you have problems sleeping though, I have a very simple kind of
meditation that I've been using for years to help you crash. It takes a
bit of practice, but it totally works and works quickly.



First up, if you can, get the best damn bed you can afford. 2000+ dollars is
nothing for a great bed. I spent at least 2200 on a sweet Tempur-Pedic.
It's totally worth it.



Now with your awesome bed here's how you start practicing getting to
sleep easily. It's kind of a self-hypnosis trick:



  1. Make sure that you've killed all sounds and lights that might be in
    your room.
  2. Lay on your back and put your hands on your body somewhere
    comfortable, or at your sides.
  3. Start breathing in deeply and slowly and breathing out, as you do
    this imagine you can see the air flow in and out of your body.
  4. Once you start to see your breath, imagine that you're looking
    through a window and outside the window is a large huge open space with
    stars in it.
  5. As you breath feel yourself float through the window and slowly out
    into the massive expanse of stars, all floating softly around you.
  6. Keep this going and then just let this floating spread into your bed
    and out around you until there is nothing.


You probably will crash out at around 4 or 5, but if not just hang out
and keep letting yourself float and melt until you do.



If you have severe insomnia then definitely talk to a doctor about it,
but try this out, as well as exercising like crazy for about an hour or
two a day. Exercise will definitely make you sleep.



Stiffness And Flexibility



If you constantly feel "stiff" or unable to move well, then you probably
need to stretch regularly. Really the best thing you can do is go to
yoga about once a week, and then try to do the exercises on your own.
If you can't do that, then go get any number of books on basic
stretching from the library or from a book store. You really just need
a simple book on the subject, and you don't need to do too many.



I think if you did about 5-6 big stretching exercises a night before
sleeping you'd feel very relaxed and see a major improvement in your
general health and feeling.



Relaxing your body through stretching relaxes your mind as well, so a
great way to improve your creativity and boost your ideas is to do yoga
or stretching for about 30 minutes, then take your morning shower.
Combine this with some meditation and you'll start to see a major
improvement in your general ability to mentally adapt and start to see
yourself make odd connections you wouldn't have before.



I'm not sure why this is, but a relaxed mind is crucial to spontaneous
creativity and idea generation.



A Simple First Step



This is probably a lot of information for one person, and I seriously
hope that you don't have all of these problems. What I recommend though
if you don't have these issues is that you try to avoid them. If you're
just starting out then you need to maybe adopt a simple "coding warm-up"
routine you can go through before you code.



Here's what I do before I sit down to code, or before I play guitar, and
whenever I get stiff and need a break:



  1. Rotate all the joints in your body by just moving your wrists, arms,
    neck, back, and hips in a few little circles. Say 5 one direction, then
    5 in another direction.
  2. Do a small number of the wrist exercises and shake your wrists
    between each set.
  3. Stretch your arms above your head as high as you can, and then
    stretch them back as far as you can, and then pull them across the front
    of your body.
  4. Finally, carefully use your hand to pull your head to the right,
    left, forward, and back a bit.


If you just did this you would avoid quite a few programming injuries.
Since programming isn't really that physically taxing it's fairly easy
to avoid hurting yourself, so this is really all you need.



However, if you have a specific problem, then again consult a physician
and try some of my advice if they say it's alright. Nothing I'm
proposing here is radical or weird, just basic exercises and common
sense, so it should be alright with any doctor. I just don't want to
get sued so remember I told you to ask one first.



Hopefully that helps you out, and if not just remember the advice in
case you run into these. If you're lucky they won't be a problem but I
think every programmer I know has had something like this at least once.



If you have other problems along these lines, then feel free to email
me
and I'll reply with some advice.



Take care.




REFERENCES
http://sheddingbikes.com/posts/1281257293.html
http://news.ycombinator.com/item?id=1585085