<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-7279440494329912256</id><updated>2012-03-02T01:29:55.873-08:00</updated><category term='Python'/><category term='matlib'/><category term='ephem'/><category term='Numerial Methods'/><category term='hello'/><category term='word count'/><category term='Javascript'/><category term='C'/><category term='Ranking'/><category term='Dennis Ritchie'/><category term='Statistics'/><category term='Conjugate gradient'/><category term='Problems for Programmers'/><category term='Electrical Engineering'/><category term='Symmetrical Components'/><category term='parsing'/><category term='Y and Delta impedances'/><category term='language popularity'/><category term='Hello World'/><category term='Welcome'/><category term='floating point'/><category term='Algorithm'/><category term='comma separators in integers'/><category term='Assembler'/><category term='interpreter'/><category term='simple-forth'/><category term='data types'/><category term='Pickle'/><category term='combinatorics'/><category term='itertools'/><category term='processing names'/><category term='Forth'/><category term='k-subsets'/><category term='HTML'/><category term='colors'/><category term='ld'/><category term='integer'/><category term='Games and Puzzles'/><category term='Tiobe'/><title type='text'>My other life as Programmer</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>28</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-33131134091929836</id><published>2012-02-01T07:56:00.000-08:00</published><updated>2012-02-01T17:37:55.569-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='colors'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><category scheme='http://www.blogger.com/atom/ns#' term='HTML'/><title type='text'>Python, finding nearest matching color name for RGB values</title><content type='html'>&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;There are 147 standard color names for use in HTML. here is a simple Python code to find the nearest matching color name given input  R,G, B values (from 0-255). The minimization criterion is the sum of absolute vaues of the differences from the color r, g, b values of the colornames.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="Python"&gt;"""&lt;br /&gt;File    colornames.py&lt;br /&gt;Author  Ernesto P. Adorio, Ph.D&lt;br /&gt;Version 0.0.1 February 1, 2012&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;# Src: http://www.w3schools.com/html/html_colornames.asp&lt;br /&gt;lines = """AliceBlue  #F0F8FF   Shades Mix&lt;br /&gt;AntiqueWhite  #FAEBD7   Shades Mix&lt;br /&gt;Aqua  #00FFFF   Shades Mix&lt;br /&gt;Aquamarine  #7FFFD4   Shades Mix&lt;br /&gt;Azure  #F0FFFF   Shades Mix&lt;br /&gt;Beige  #F5F5DC   Shades Mix&lt;br /&gt;Bisque  #FFE4C4   Shades Mix&lt;br /&gt;Black  #000000   Shades Mix&lt;br /&gt;BlanchedAlmond  #FFEBCD   Shades Mix&lt;br /&gt;Blue  #0000FF   Shades Mix&lt;br /&gt;BlueViolet  #8A2BE2   Shades Mix&lt;br /&gt;Brown  #A52A2A   Shades Mix&lt;br /&gt;BurlyWood  #DEB887   Shades Mix&lt;br /&gt;CadetBlue  #5F9EA0   Shades Mix&lt;br /&gt;Chartreuse  #7FFF00   Shades Mix&lt;br /&gt;Chocolate  #D2691E   Shades Mix&lt;br /&gt;Coral  #FF7F50   Shades Mix&lt;br /&gt;CornflowerBlue  #6495ED   Shades Mix&lt;br /&gt;Cornsilk  #FFF8DC   Shades Mix&lt;br /&gt;Crimson  #DC143C   Shades Mix&lt;br /&gt;Cyan  #00FFFF   Shades Mix&lt;br /&gt;DarkBlue  #00008B   Shades Mix&lt;br /&gt;DarkCyan  #008B8B   Shades Mix&lt;br /&gt;DarkGoldenRod  #B8860B   Shades Mix&lt;br /&gt;DarkGray  #A9A9A9   Shades Mix&lt;br /&gt;DarkGrey  #A9A9A9   Shades Mix&lt;br /&gt;DarkGreen  #006400   Shades Mix&lt;br /&gt;DarkKhaki  #BDB76B   Shades Mix&lt;br /&gt;DarkMagenta  #8B008B   Shades Mix&lt;br /&gt;DarkOliveGreen  #556B2F   Shades Mix&lt;br /&gt;Darkorange  #FF8C00   Shades Mix&lt;br /&gt;DarkOrchid  #9932CC   Shades Mix&lt;br /&gt;DarkRed  #8B0000   Shades Mix&lt;br /&gt;DarkSalmon  #E9967A   Shades Mix&lt;br /&gt;DarkSeaGreen  #8FBC8F   Shades Mix&lt;br /&gt;DarkSlateBlue  #483D8B   Shades Mix&lt;br /&gt;DarkSlateGray  #2F4F4F   Shades Mix&lt;br /&gt;DarkSlateGrey  #2F4F4F   Shades Mix&lt;br /&gt;DarkTurquoise  #00CED1   Shades Mix&lt;br /&gt;DarkViolet  #9400D3   Shades Mix&lt;br /&gt;DeepPink  #FF1493   Shades Mix&lt;br /&gt;DeepSkyBlue  #00BFFF   Shades Mix&lt;br /&gt;DimGray  #696969   Shades Mix&lt;br /&gt;DimGrey  #696969   Shades Mix&lt;br /&gt;DodgerBlue  #1E90FF   Shades Mix&lt;br /&gt;FireBrick  #B22222   Shades Mix&lt;br /&gt;FloralWhite  #FFFAF0   Shades Mix&lt;br /&gt;ForestGreen  #228B22   Shades Mix&lt;br /&gt;Fuchsia  #FF00FF   Shades Mix&lt;br /&gt;Gainsboro  #DCDCDC   Shades Mix&lt;br /&gt;GhostWhite  #F8F8FF   Shades Mix&lt;br /&gt;Gold  #FFD700   Shades Mix&lt;br /&gt;GoldenRod  #DAA520   Shades Mix&lt;br /&gt;Gray  #808080   Shades Mix&lt;br /&gt;Grey  #808080   Shades Mix&lt;br /&gt;Green  #008000   Shades Mix&lt;br /&gt;GreenYellow  #ADFF2F   Shades Mix&lt;br /&gt;HoneyDew  #F0FFF0   Shades Mix&lt;br /&gt;HotPink  #FF69B4   Shades Mix&lt;br /&gt;IndianRed   #CD5C5C   Shades Mix&lt;br /&gt;Indigo   #4B0082   Shades Mix&lt;br /&gt;Ivory  #FFFFF0   Shades Mix&lt;br /&gt;Khaki  #F0E68C   Shades Mix&lt;br /&gt;Lavender  #E6E6FA   Shades Mix&lt;br /&gt;LavenderBlush  #FFF0F5   Shades Mix&lt;br /&gt;LawnGreen  #7CFC00   Shades Mix&lt;br /&gt;LemonChiffon  #FFFACD   Shades Mix&lt;br /&gt;LightBlue  #ADD8E6   Shades Mix&lt;br /&gt;LightCoral  #F08080   Shades Mix&lt;br /&gt;LightCyan  #E0FFFF   Shades Mix&lt;br /&gt;LightGoldenRodYellow  #FAFAD2   Shades Mix&lt;br /&gt;LightGray  #D3D3D3   Shades Mix&lt;br /&gt;LightGrey  #D3D3D3   Shades Mix&lt;br /&gt;LightGreen  #90EE90   Shades Mix&lt;br /&gt;LightPink  #FFB6C1   Shades Mix&lt;br /&gt;LightSalmon  #FFA07A   Shades Mix&lt;br /&gt;LightSeaGreen  #20B2AA   Shades Mix&lt;br /&gt;LightSkyBlue  #87CEFA   Shades Mix&lt;br /&gt;LightSlateGray  #778899   Shades Mix&lt;br /&gt;LightSlateGrey  #778899   Shades Mix&lt;br /&gt;LightSteelBlue  #B0C4DE   Shades Mix&lt;br /&gt;LightYellow  #FFFFE0   Shades Mix&lt;br /&gt;Lime  #00FF00   Shades Mix&lt;br /&gt;LimeGreen  #32CD32   Shades Mix&lt;br /&gt;Linen  #FAF0E6   Shades Mix&lt;br /&gt;Magenta  #FF00FF   Shades Mix&lt;br /&gt;Maroon  #800000   Shades Mix&lt;br /&gt;MediumAquaMarine  #66CDAA   Shades Mix&lt;br /&gt;MediumBlue  #0000CD   Shades Mix&lt;br /&gt;MediumOrchid  #BA55D3   Shades Mix&lt;br /&gt;MediumPurple  #9370D8   Shades Mix&lt;br /&gt;MediumSeaGreen  #3CB371   Shades Mix&lt;br /&gt;MediumSlateBlue  #7B68EE   Shades Mix&lt;br /&gt;MediumSpringGreen  #00FA9A   Shades Mix&lt;br /&gt;MediumTurquoise  #48D1CC   Shades Mix&lt;br /&gt;MediumVioletRed  #C71585   Shades Mix&lt;br /&gt;MidnightBlue  #191970   Shades Mix&lt;br /&gt;MintCream  #F5FFFA   Shades Mix&lt;br /&gt;MistyRose  #FFE4E1   Shades Mix&lt;br /&gt;Moccasin  #FFE4B5   Shades Mix&lt;br /&gt;NavajoWhite  #FFDEAD   Shades Mix&lt;br /&gt;Navy  #000080   Shades Mix&lt;br /&gt;OldLace  #FDF5E6   Shades Mix&lt;br /&gt;Olive  #808000   Shades Mix&lt;br /&gt;OliveDrab  #6B8E23   Shades Mix&lt;br /&gt;Orange  #FFA500   Shades Mix&lt;br /&gt;OrangeRed  #FF4500   Shades Mix&lt;br /&gt;Orchid  #DA70D6   Shades Mix&lt;br /&gt;PaleGoldenRod  #EEE8AA   Shades Mix&lt;br /&gt;PaleGreen  #98FB98   Shades Mix&lt;br /&gt;PaleTurquoise  #AFEEEE   Shades Mix&lt;br /&gt;PaleVioletRed  #D87093   Shades Mix&lt;br /&gt;PapayaWhip  #FFEFD5   Shades Mix&lt;br /&gt;PeachPuff  #FFDAB9   Shades Mix&lt;br /&gt;Peru  #CD853F   Shades Mix&lt;br /&gt;Pink  #FFC0CB   Shades Mix&lt;br /&gt;Plum  #DDA0DD   Shades Mix&lt;br /&gt;PowderBlue  #B0E0E6   Shades Mix&lt;br /&gt;Purple  #800080   Shades Mix&lt;br /&gt;Red  #FF0000   Shades Mix&lt;br /&gt;RosyBrown  #BC8F8F   Shades Mix&lt;br /&gt;RoyalBlue  #4169E1   Shades Mix&lt;br /&gt;SaddleBrown  #8B4513   Shades Mix&lt;br /&gt;Salmon  #FA8072   Shades Mix&lt;br /&gt;SandyBrown  #F4A460   Shades Mix&lt;br /&gt;SeaGreen  #2E8B57   Shades Mix&lt;br /&gt;SeaShell  #FFF5EE   Shades Mix&lt;br /&gt;Sienna  #A0522D   Shades Mix&lt;br /&gt;Silver  #C0C0C0   Shades Mix&lt;br /&gt;SkyBlue  #87CEEB   Shades Mix&lt;br /&gt;SlateBlue  #6A5ACD   Shades Mix&lt;br /&gt;SlateGray  #708090   Shades Mix&lt;br /&gt;SlateGrey  #708090   Shades Mix&lt;br /&gt;Snow  #FFFAFA   Shades Mix&lt;br /&gt;SpringGreen  #00FF7F   Shades Mix&lt;br /&gt;SteelBlue  #4682B4   Shades Mix&lt;br /&gt;Tan  #D2B48C   Shades Mix&lt;br /&gt;Teal  #008080   Shades Mix&lt;br /&gt;Thistle  #D8BFD8   Shades Mix&lt;br /&gt;Tomato  #FF6347   Shades Mix&lt;br /&gt;Turquoise  #40E0D0   Shades Mix&lt;br /&gt;Violet  #EE82EE   Shades Mix&lt;br /&gt;Wheat  #F5DEB3   Shades Mix&lt;br /&gt;White  #FFFFFF   Shades Mix&lt;br /&gt;WhiteSmoke  #F5F5F5   Shades Mix&lt;br /&gt;Yellow  #FFFF00   Shades Mix&lt;br /&gt;YellowGreen  #9ACD32"""&lt;br /&gt;&lt;br /&gt;def rgbfromstr(s):&lt;br /&gt;    # s starts with a #.&lt;br /&gt;    r, g, b = int(s[1:3],16), int(s[3:5], 16),int(s[5:7], 16)&lt;br /&gt;    return r, g, b&lt;br /&gt;&lt;br /&gt;def findnearestcolorname(R,G, B, colorD):&lt;br /&gt;    mindiff = None&lt;br /&gt;&lt;br /&gt;    for d in colorD:&lt;br /&gt;       r, g, b = rgbfromstr(colorD[d])&lt;br /&gt;       diff = abs(R -r)*256 + abs(G-g)* 256 + abs(B- b)* 256 &lt;br /&gt;       if mindiff is None or diff &lt; mindiff:&lt;br /&gt;          mindiff = diff&lt;br /&gt;          mincolorname = d&lt;br /&gt;    return mincolorname&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;if __name__ == "__main__":&lt;br /&gt;  D={}&lt;br /&gt;  for line in lines.split("\n"):&lt;br /&gt;    tokens = line.split()&lt;br /&gt;    if len(tokens) &gt; 1:&lt;br /&gt;        D[tokens[0]]= tokens[1]&lt;br /&gt;     &lt;br /&gt;  R, G, B = 0, 127, 127&lt;br /&gt;  colorname = findnearestcolorname(0, 127, 127, D)&lt;br /&gt;  print hex(R), hex(G), hex(B)&lt;br /&gt;  print colorname, D[colorname]&lt;br /&gt; &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;When the above program runs, it outputs &lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;$ python colornames.py&lt;br /&gt;0x0 0x7f 0x7f&lt;br /&gt;Teal #008080&lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Questions.&lt;br /&gt;&lt;br /&gt;1. Modify the minimizaiton criterion to use least sum of squares of the differences.&lt;br /&gt;&lt;br /&gt;2. Provide error checking for input R, G, B values to be within the interval [0, 255].&lt;br /&gt;&lt;br /&gt;3. Procide different ways to specify the input RGB values, aside from the (R, G, B) values as done in the program  above.&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-33131134091929836?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/33131134091929836/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/02/python-finding-nearest-matching-color.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/33131134091929836'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/33131134091929836'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/02/python-finding-nearest-matching-color.html' title='Python, finding nearest matching color name for RGB values'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-24793868202562893</id><published>2012-01-25T06:52:00.000-08:00</published><updated>2012-01-25T06:59:28.606-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C'/><category scheme='http://www.blogger.com/atom/ns#' term='Forth'/><category scheme='http://www.blogger.com/atom/ns#' term='simple-forth'/><category scheme='http://www.blogger.com/atom/ns#' term='interpreter'/><title type='text'>Simple floating point arithmetic for simple-forth</title><content type='html'>Here is our latest incarnation of simple-forth, a forth interpreter written in C.&lt;br /&gt;This time we add floating point arithmetic capabilities. There are two basic ways to incorporate floating point  capabilities. One is using the same integer stack and the other is using a separate foating point stack. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;We use a separate floating point stack with maximum 32 elements. in our newest version shown below for simplicity. The built-in integer stack is 32 bits wide. Floating point numbers  in our interpreter are 64 bit wide. The current stack element index is indicated by FP. The basic floating point operations are f+, f-, f*, f/ these Forth words are the equivalent floating point words corresponding to the built-in basic + - * / operator words &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="C"&gt;/*&lt;br /&gt;file     simple-forth-0.0.3.c&lt;br /&gt;author   Dr. Ernesto P. Adorio&lt;br /&gt;         UPDEPP (University of the Philippines,&lt;br /&gt;         Extension Program in Pampanga&lt;br /&gt;         Clarkfield, Pampanga&lt;br /&gt;email    ernesto.adorio@gmail.com&lt;br /&gt;version  0.0.1 January 14, 2012 basic interpreter.&lt;br /&gt;         0.0.2 January 16, 2012 interactivity added.&lt;br /&gt;         0.0.3 January 25, 2012 basic floating point.&lt;br /&gt;*/&lt;br /&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;#include &lt;ctype.h&gt;&lt;br /&gt;#include &lt;string.h&gt;&lt;br /&gt;#include &lt;stdlib.h&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;enum {E_STACKUNDERFLOW, E_FSTACKUNDERFLOW} ERRCODES;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;enum {L_EMIT, L_DOT,L_DOTT, L_SPACE, L_ADD, L_SUB, L_MUL, L_DIV, L_DROP, L_INT32, L_CR,&lt;br /&gt;      L_FNUM, L_FPLUS, L_FSUB, L_FMUL, L_FDIV, L_FDOT, L_FDOTT, L_FDROP,&lt;br /&gt;      L_BYE, L_EOS,L_ERROR} OPCODES;&lt;br /&gt;&lt;br /&gt;const char *stdwords[] = { "emit", ".",  ".t", "space", "+", "-", "*", "/", "drop", "int32", "cr",&lt;br /&gt;                           "fnum", "f+", "f-", "f*" ,"f/", "f.","f.t","fdrop",&lt;br /&gt;                           "bye",&lt;br /&gt;                           "\n",&lt;br /&gt;                         };&lt;br /&gt;// "int32" and "fnum" are dummies. &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;#define MAXSTKLEN 32&lt;br /&gt;#define MAXFSTKLEN 32&lt;br /&gt;#define MAXTOKENLEN 128&lt;br /&gt;&lt;br /&gt;int  LENSTDWORDS = sizeof(stdwords)/sizeof(stdwords[0]);&lt;br /&gt;char LINEBUFFER[256];&lt;br /&gt;char *goodbye= "bye";&lt;br /&gt;int  ERRCODE = 0;&lt;br /&gt;int SP = -1;   /* stack pointer index */&lt;br /&gt;int stack[MAXSTKLEN];&lt;br /&gt;&lt;br /&gt;int  opcode;&lt;br /&gt;char *tokstart;&lt;br /&gt;char *tokend;&lt;br /&gt;&lt;br /&gt;int FP = -1;   /* floating point stack index */&lt;br /&gt;double fstack[MAXFSTKLEN];&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;int numbertype(char *s) &lt;br /&gt;{&lt;br /&gt;   /*&lt;br /&gt;   Returns &lt;br /&gt;     0 - not a number!&lt;br /&gt;     1 - an integer&lt;br /&gt;     2 - a floating point number&lt;br /&gt;   */&lt;br /&gt;   &lt;br /&gt;   char *t = s;&lt;br /&gt;   while (isspace(*t)) t++;&lt;br /&gt;   if (*t == '\0') return 0;&lt;br /&gt;    &lt;br /&gt;   if (*t == '+' || *t == '-') t++;&lt;br /&gt;   if (*t == '\0') return 0;&lt;br /&gt;   while (isdigit(*t)) t++;&lt;br /&gt;   if (*t == '\0') {&lt;br /&gt;     return 1; // an integer!&lt;br /&gt;   }&lt;br /&gt;  &lt;br /&gt;   if (*t == '.') t++;&lt;br /&gt;   while (isdigit(*t)) t++;&lt;br /&gt;   if (*t == '\0') return 2;&lt;br /&gt;   &lt;br /&gt;   if (*t == 'e') t++;&lt;br /&gt;   if (*t == '\0') return 0; // error!&lt;br /&gt;   if (*t == '+' || *t == '-') t++;&lt;br /&gt;   if (*t == '\0') return 0; // error!&lt;br /&gt;   while (isdigit(*t)) t++;&lt;br /&gt;   if (*t == '\0') return 2; // a floating point number!&lt;br /&gt;   return 0; // not an integer or floating point.&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;int eval(int opcode)&lt;br /&gt;{&lt;br /&gt;    /* Evaluate opcode */&lt;br /&gt;    switch (opcode){&lt;br /&gt;    case L_EMIT: &lt;br /&gt;      //@@printf("opcode L_EMIT %s %d\n", tokstart, SP);&lt;br /&gt;      if (SP &lt; 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;      } else {&lt;br /&gt;        printf ("%c", stack[SP--]);&lt;br /&gt;      }&lt;br /&gt;      break;&lt;br /&gt;&lt;br /&gt;    case L_DOT:&lt;br /&gt;      printf("opcode L_EMIT %s %d\n", tokstart, SP);&lt;br /&gt;      if (SP &lt; 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;      } else {&lt;br /&gt;        printf ("%d", stack[SP--]);&lt;br /&gt;      }&lt;br /&gt;      break;&lt;br /&gt;&lt;br /&gt;    case L_DOTT:&lt;br /&gt;      //@@printf("opcode L_EMIT %s %d\n", tokstart, SP);&lt;br /&gt;      if (SP &lt; 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;      } else {&lt;br /&gt;        printf ("%d", stack[SP]);&lt;br /&gt;      }&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_SPACE:&lt;br /&gt;      printf ("%c", 32);&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_ADD:&lt;br /&gt;      //printf("opcode L_ADD %s\n", tokstart);&lt;br /&gt;      if (SP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      stack[SP-1] += stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_SUB:&lt;br /&gt;      //printf("opcode L_SUB %s\n", tokstart);&lt;br /&gt;      if (SP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      stack[SP-1] -= stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_MUL:&lt;br /&gt;      //printf("opcode L_MUL %s\n", tokstart);&lt;br /&gt;      if (SP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      stack[SP-1] *= stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_DIV:&lt;br /&gt;      //printf("opcode L_DIV %s\n", tokstart);&lt;br /&gt;      if (SP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      stack[SP-1] /= stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;  &lt;br /&gt;   case L_INT32:&lt;br /&gt;      //printf("opcode L_INT32 %s\n",tokstart);&lt;br /&gt;      stack[++SP]= atoi(tokstart);&lt;br /&gt;      // printf("@@@ pushing an integer!");&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_DROP:&lt;br /&gt;      //printf("opcode L_DROP %s \n", tokstart);&lt;br /&gt;      SP=SP -1;&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_CR:&lt;br /&gt;      // printf("opcode L_CR %s \n", tokstart);&lt;br /&gt;      printf("\n");&lt;br /&gt;      break;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;/* simple floating point features */&lt;br /&gt;    case L_FNUM:&lt;br /&gt;      //printf("floating point number %s\n",tokstart);&lt;br /&gt;      fstack[++FP]= atof(tokstart);&lt;br /&gt;      break;&lt;br /&gt;    &lt;br /&gt;    case L_FPLUS:&lt;br /&gt;      if (FP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_FSTACKUNDERFLOW;&lt;br /&gt;     printf("%s", "fstack underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      fstack[FP-1] += fstack[FP];&lt;br /&gt;      FP--;&lt;br /&gt;      break;&lt;br /&gt;&lt;br /&gt;    case L_FSUB:&lt;br /&gt;      if (FP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_FSTACKUNDERFLOW;&lt;br /&gt;     printf("%s", "fstack underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      fstack[FP-1] -= fstack[FP];&lt;br /&gt;      FP--;&lt;br /&gt;      break;&lt;br /&gt;&lt;br /&gt;    case L_FMUL:&lt;br /&gt;      if (FP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_FSTACKUNDERFLOW;&lt;br /&gt;     printf("%s", "fstack underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      fstack[FP-1] *= fstack[FP];&lt;br /&gt;      FP--;&lt;br /&gt;      break;&lt;br /&gt;&lt;br /&gt;    case L_FDIV:&lt;br /&gt;      if (FP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_FSTACKUNDERFLOW;&lt;br /&gt;     printf("%s", "fstack underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      fstack[FP-1] /= fstack[FP];&lt;br /&gt;      FP--;&lt;br /&gt;      break;&lt;br /&gt;&lt;br /&gt;    case L_FDOT:&lt;br /&gt;      printf("opcode FDOT %s\n", tokstart);&lt;br /&gt;      if (FP &lt; 0) {&lt;br /&gt;     ERRCODE = E_FSTACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;      } else {&lt;br /&gt;        printf ("%f", fstack[FP--]);&lt;br /&gt;      }&lt;br /&gt;      break;&lt;br /&gt;&lt;br /&gt;    case L_FDOTT:&lt;br /&gt;      //@@printf("opcode L_EMIT %s %d\n", tokstart, SP);&lt;br /&gt;      if (SP &lt; 0) {&lt;br /&gt;     ERRCODE = E_FSTACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;      } else {&lt;br /&gt;        printf ("%f", fstack[FP]);&lt;br /&gt;      }&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_BYE:&lt;br /&gt;      printf("Terminating... ");&lt;br /&gt;      break;&lt;br /&gt;    default:&lt;br /&gt;      ;&lt;br /&gt;      break;&lt;br /&gt;    }  &lt;br /&gt;   &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;void nexttoken()&lt;br /&gt;{   &lt;br /&gt;    tokstart = tokend;&lt;br /&gt;    //@ printf("inside nexttoken [%s]", tokstart);&lt;br /&gt;    &lt;br /&gt;    /* ignore leading white spaces */&lt;br /&gt;    while (isspace(*tokstart)) tokstart++;&lt;br /&gt;&lt;br /&gt;    /* find terminating space of end of string */&lt;br /&gt;    tokend = tokstart;&lt;br /&gt;    while (!isspace(*tokend) &amp;&amp; *tokend != '\0') tokend++;&lt;br /&gt;    &lt;br /&gt;    /* string terminator */&lt;br /&gt;    if (*tokend != '\0') {&lt;br /&gt;      *tokend = '\0';&lt;br /&gt;      tokend ++;&lt;br /&gt;    } &lt;br /&gt;&lt;br /&gt;    /* get opcode */&lt;br /&gt;    opcode = -1; &lt;br /&gt;    if (tokend == tokstart) {&lt;br /&gt;       opcode = L_EOS;&lt;br /&gt;       return;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    //@@@ printf("token [%s]\n", tokstart); &lt;br /&gt;    for (int i =0; i &lt; LENSTDWORDS; i++) {&lt;br /&gt;      if (strcmp(stdwords[i], tokstart) == 0){&lt;br /&gt; opcode = i;&lt;br /&gt;        break;&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    if (opcode != -1) {&lt;br /&gt;       return;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    int ntype = numbertype(tokstart); &lt;br /&gt;    if (ntype == 1){&lt;br /&gt;      /* is this a number ?*/&lt;br /&gt;      opcode = L_INT32;&lt;br /&gt;    } else if (ntype == 2) {&lt;br /&gt;      opcode = L_FNUM;&lt;br /&gt;    } else if (opcode == -1){&lt;br /&gt;      opcode = L_ERROR;&lt;br /&gt;    };&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;int main(){&lt;br /&gt;  while (1) {&lt;br /&gt;    printf("&gt; ");&lt;br /&gt;    if (fgets(LINEBUFFER, 250, stdin)!= NULL) {&lt;br /&gt;      tokend=LINEBUFFER;&lt;br /&gt;    } else {&lt;br /&gt;      tokend= goodbye;&lt;br /&gt;    }&lt;br /&gt;    while (1) {&lt;br /&gt;      nexttoken();&lt;br /&gt;      eval(opcode);&lt;br /&gt;      if (opcode == L_BYE) {&lt;br /&gt; return 0;&lt;br /&gt;      }&lt;br /&gt;      if (opcode ==L_EOS) {&lt;br /&gt; break;&lt;br /&gt;      }&lt;br /&gt;      if (ERRCODE != 0) {&lt;br /&gt; printf("ERRORCODE [%d]", ERRCODE);&lt;br /&gt; break;&lt;br /&gt;      };&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;  printf("\n");&lt;br /&gt;  return 0;&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Here is compilation and a simple execution run.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;gcc simple-forth-0.0.3.c -g -std=c99 -o simple-forth&lt;br /&gt;toto@toto-Aspire-4520:~/Blogs/my-other-life-as-programmer/forth$ ./simple-forth&lt;br /&gt;&gt; 23.34 -56.12 f* f. &lt;br /&gt;-1309.840800&gt; bye&lt;br /&gt;Terminating... &lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Dont forget: a floating point number has a comma or an exponent in our simple-forth implementation.&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-24793868202562893?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/24793868202562893/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/01/simple-floating-point-arithmetic-for.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/24793868202562893'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/24793868202562893'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/01/simple-floating-point-arithmetic-for.html' title='Simple floating point arithmetic for simple-forth'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-4102015031023047133</id><published>2012-01-24T17:52:00.000-08:00</published><updated>2012-01-24T17:52:52.840-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Forth'/><category scheme='http://www.blogger.com/atom/ns#' term='interpreter'/><title type='text'>Terminal interactivity added to simple-forth.</title><content type='html'>Our previous Forth interpreter processed only fixed strings. To add interactivity from a console or terminal, we have to read an input string to a buffer. There is more than one way, we may use scanf. Another one, much better is fgets which avoids buffer overruns. Here is our version 0.0.2 with terminal interactivity.&lt;br /&gt;&lt;br /&gt;&lt;pre  name="code" class="C"&gt;&lt;br /&gt;/*&lt;br /&gt;file     simple-forth-0.0.2.c&lt;br /&gt;author   Dr. Ernesto P. Adorio&lt;br /&gt;         UPDEPP (University of the Philippines,&lt;br /&gt;         Extension Program in Pampanga&lt;br /&gt;         Clarkfield, Pampanga&lt;br /&gt;email    ernesto.adorio@gmail.com&lt;br /&gt;version  0.0.1 January 14, 2012 basic interpreter.&lt;br /&gt;         0.0.2 January 16, 2012 interactivity added.&lt;br /&gt;*/&lt;br /&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;#include &lt;ctype.h&gt;&lt;br /&gt;#include &lt;string.h&gt;&lt;br /&gt;#include &lt;stdlib.h&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;enum {E_STACKUNDERFLOW} ERRCODES;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;enum {L_EMIT, L_DOT,L_DOTT, L_SPACE, L_ADD, L_SUB, L_MUL, L_DIV, L_DROP, L_INT32, L_CR,  L_BYE, L_EOS,L_ERROR} OPCODES;&lt;br /&gt;const char *stdwords[] = { &lt;br /&gt;"emit",&lt;br /&gt;".", &lt;br /&gt;".t",&lt;br /&gt;"space",&lt;br /&gt;"+",&lt;br /&gt;"-",&lt;br /&gt;"*",&lt;br /&gt;"/",&lt;br /&gt;"drop",&lt;br /&gt;"int32",&lt;br /&gt;"cr",&lt;br /&gt;"bye",&lt;br /&gt;"\n",&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;#define MAXSTKLEN 32&lt;br /&gt;#define MAXFSTKLEN 32&lt;br /&gt;#define MAXTOKENLEN 128&lt;br /&gt;&lt;br /&gt;int  LENSTDWORDS = sizeof(stdwords)/sizeof(stdwords[0]);&lt;br /&gt;char LINEBUFFER[256];&lt;br /&gt;char *goodbye= "bye";&lt;br /&gt;int  ERRCODE = 0;&lt;br /&gt;int SP = -1;   /* stack pointer index */&lt;br /&gt;&lt;br /&gt;int    stack[MAXSTKLEN];&lt;br /&gt;double fstack[MAXFSTKLEN];&lt;br /&gt;&lt;br /&gt;int  opcode;&lt;br /&gt;char *tokstart;&lt;br /&gt;char *tokend;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;int eval(int opcode)&lt;br /&gt;{&lt;br /&gt;    /* Evaluate opcode */&lt;br /&gt;    switch (opcode){&lt;br /&gt;    case L_EMIT: &lt;br /&gt;      //@@printf("opcode L_EMIT %s %d\n", tokstart, SP);&lt;br /&gt;      if (SP &lt; 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;      } else {&lt;br /&gt;        printf ("%c", stack[SP--]);&lt;br /&gt;      }&lt;br /&gt;      break;&lt;br /&gt;&lt;br /&gt;    case L_DOT:&lt;br /&gt;      //@@printf("opcode L_EMIT %s %d\n", tokstart, SP);&lt;br /&gt;      if (SP &lt; 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;      } else {&lt;br /&gt;        printf ("%d", stack[SP--]);&lt;br /&gt;      }&lt;br /&gt;      break;&lt;br /&gt;&lt;br /&gt;    case L_DOTT:&lt;br /&gt;      //@@printf("opcode L_EMIT %s %d\n", tokstart, SP);&lt;br /&gt;      if (SP &lt; 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;      } else {&lt;br /&gt;        printf ("%d", stack[SP]);&lt;br /&gt;      }&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_SPACE:&lt;br /&gt;      printf ("%c", 32);&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_ADD:&lt;br /&gt;      //printf("opcode L_ADD %s\n", tokstart);&lt;br /&gt;      if (SP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      stack[SP-1] += stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_SUB:&lt;br /&gt;      //printf("opcode L_SUB %s\n", tokstart);&lt;br /&gt;      if (SP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      stack[SP-1] -= stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_MUL:&lt;br /&gt;      //printf("opcode L_MUL %s\n", tokstart);&lt;br /&gt;      if (SP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      stack[SP-1] *= stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_DIV:&lt;br /&gt;      //printf("opcode L_DIV %s\n", tokstart);&lt;br /&gt;      if (SP &lt;= 0) {&lt;br /&gt;     ERRCODE = E_STACKUNDERFLOW;&lt;br /&gt;     printf("%s", "underflow!");&lt;br /&gt;     break;&lt;br /&gt;      } &lt;br /&gt;      stack[SP-1] /= stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;    case L_INT32:&lt;br /&gt;      //printf("opcode L_INT32 %s\n",tokstart);&lt;br /&gt;      stack[++SP]= atoi(tokstart);&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_DROP:&lt;br /&gt;      //printf("opcode L_DROP %s \n", tokstart);&lt;br /&gt;      SP=SP -1;&lt;br /&gt;      break;&lt;br /&gt;      &lt;br /&gt;    case L_CR:&lt;br /&gt;      // printf("opcode L_CR %s \n", tokstart);&lt;br /&gt;      printf("\n");&lt;br /&gt;      break;&lt;br /&gt;    default:&lt;br /&gt;      ;&lt;br /&gt;      break;&lt;br /&gt;    }  &lt;br /&gt;   &lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;void nexttoken()&lt;br /&gt;{   &lt;br /&gt;    tokstart = tokend;&lt;br /&gt;    //@ printf("inside nexttoken [%s]", tokstart);&lt;br /&gt;    &lt;br /&gt;    /* ignore leading white spaces */&lt;br /&gt;    while (isspace(*tokstart)) tokstart++;&lt;br /&gt;&lt;br /&gt;    /* find terminating space of end of string */&lt;br /&gt;    tokend = tokstart;&lt;br /&gt;    while (!isspace(*tokend) &amp;&amp; *tokend != '\0') tokend++;&lt;br /&gt;    &lt;br /&gt;    /* string terminator */&lt;br /&gt;    if (*tokend != '\0') {&lt;br /&gt;      *tokend = '\0';&lt;br /&gt;      tokend ++;&lt;br /&gt;    } &lt;br /&gt;&lt;br /&gt;    /* get opcode */&lt;br /&gt;    opcode = -1; &lt;br /&gt;    if (tokend == tokstart) {&lt;br /&gt;       opcode = L_EOS;&lt;br /&gt;       return;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;    /*@@@ printf("token [%s]\n", tokstart); */&lt;br /&gt;    for (int i =0; i &lt; LENSTDWORDS; i++) {&lt;br /&gt;      if (strcmp(stdwords[i], tokstart) == 0){&lt;br /&gt; opcode = i;&lt;br /&gt; //@ printf("opcde [%d]", opcode);&lt;br /&gt;        break;&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    if (opcode == -1){&lt;br /&gt;      opcode = L_INT32;&lt;br /&gt;    }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;int main(){&lt;br /&gt;  while (1) {&lt;br /&gt;    // read string.&lt;br /&gt;    printf("&gt; ");&lt;br /&gt;    if (fgets(LINEBUFFER, 250, stdin)!= NULL) {&lt;br /&gt;      tokend=LINEBUFFER;&lt;br /&gt;      // @@@ printf("input string [%s]", LINEBUFFER);&lt;br /&gt;    } else {&lt;br /&gt;      tokend= goodbye;&lt;br /&gt;    }&lt;br /&gt;    // eval&lt;br /&gt;    // printf ("Entering evaluation loop.\n");&lt;br /&gt;    while (1) {&lt;br /&gt;      nexttoken();&lt;br /&gt;      //@ printf ("[%d] %s", opcode, tokstart);&lt;br /&gt;      eval(opcode);&lt;br /&gt;      if (opcode== L_BYE) {&lt;br /&gt; //printf ("%% opcode is L_BYE");&lt;br /&gt; return 0;&lt;br /&gt;      }&lt;br /&gt;      if (opcode ==L_EOS) {&lt;br /&gt; break;&lt;br /&gt;      }&lt;br /&gt;      if (ERRCODE != 0) {&lt;br /&gt; printf("ERRORCODE [%d]", ERRCODE);&lt;br /&gt; break;&lt;br /&gt;      };&lt;br /&gt;    }&lt;br /&gt;    // loop back unless BYE!&lt;br /&gt;  }&lt;br /&gt;  printf("\n");&lt;br /&gt;  return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Save file to simple-forth-0.0.2.c, then compile it using the following command:&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;: gcc simple-forth.c -std=c99 -o simple-forth-0.0.2&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;Then run it by issuing ./simple-forth00.0.2 Here is an uninspired terminal run:&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&gt; 2 3 - 1 + .&lt;br /&gt;0&gt; 56 emit&lt;br /&gt;8&gt; 97 emit&lt;br /&gt;a&gt; 64 emit&lt;br /&gt;@&gt; &lt;br /&gt;&gt; &lt;br /&gt;&gt; bye&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Next, we will add add a floating point computation capabilities using a separate stack.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-4102015031023047133?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/4102015031023047133/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/01/terminal-interactivity-added-to-simple.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/4102015031023047133'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/4102015031023047133'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/01/terminal-interactivity-added-to-simple.html' title='Terminal interactivity added to simple-forth.'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-8113520227658881858</id><published>2012-01-17T04:20:00.000-08:00</published><updated>2012-01-17T04:20:38.507-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='language popularity'/><category scheme='http://www.blogger.com/atom/ns#' term='Tiobe'/><title type='text'>Tiobe rankings of programming languages</title><content type='html'>Click on &lt;a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html"&gt;&lt;/a&gt; for the latest popularity rankings of  programming languages. It is not based on absolute value but on the relative change of market share.&lt;br /&gt;&lt;br /&gt;For January 2012, Objective C showed the fastest growth. Click on the link for the the definition of the &lt;a href="http://www.tiobe.com/content/paperinfo/tpci/tpci_definition.htm"&gt;Tiobe index&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The next popular is C# followed by C and Javascript. On the other hand, based on absolute market share, the top languages are Java, C, C#, C++, Objective-C, PHP and Visual Basic. Our favorite language Python is at #8. Interesting to note that the statistical software R is at #19.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-8113520227658881858?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/8113520227658881858/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/01/tiobe-rankings-of-programming-languages.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/8113520227658881858'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/8113520227658881858'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/01/tiobe-rankings-of-programming-languages.html' title='Tiobe rankings of programming languages'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-1127389585267231400</id><published>2012-01-14T06:13:00.000-08:00</published><updated>2012-01-24T17:38:51.760-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C'/><category scheme='http://www.blogger.com/atom/ns#' term='parsing'/><category scheme='http://www.blogger.com/atom/ns#' term='integer'/><category scheme='http://www.blogger.com/atom/ns#' term='floating point'/><title type='text'>Does a number string represents an integer or a floating value in C?</title><content type='html'>I got the shock of my blogging life when I cannot access an old post about the evils of the C function atof. Here is a code which return 1 for integers and 2 for floating point and 0 if not a valid integer or a valid float.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="C"&gt;/*&lt;br /&gt;author  Ernesto P. Adorio&lt;br /&gt;        UPDEPP (University of the &lt;br /&gt;        Philippines, Extension Program&lt;br /&gt;        in Pampanga, Clarkfield, Pampanga&lt;br /&gt;email   ernesto. adorio@ gmail.com [remove spaces]&lt;br /&gt;version 0.0.1 january 14, 2012&lt;br /&gt;*/&lt;br /&gt;&lt;br /&gt;#include &lt;ctype.h&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;int numbertype(char *s) &lt;br /&gt;{&lt;br /&gt;   char *t = s;&lt;br /&gt;   while (isspace(*t)) t++;&lt;br /&gt;   if (*t == '\0') return 0;&lt;br /&gt;    &lt;br /&gt;   // number sign&lt;br /&gt;   printf("ltrimmed [%s]", t);&lt;br /&gt;   if (*t == '+' || *t == '-') t++;&lt;br /&gt;   if (*t == '\0') return 0;&lt;br /&gt;   printf("after sign [%s]", t);&lt;br /&gt;   while (isdigit(*t)) t++;&lt;br /&gt;   printf("after digits [%s]", t);&lt;br /&gt;   if (*t == '\0') return 1; // an integer!&lt;br /&gt;   &lt;br /&gt;   // floating point??&lt;br /&gt;   printf ("decimal point? [%s] ", t);  &lt;br /&gt;   if (*t == '.') t++;&lt;br /&gt;   printf ("fractional digits?");&lt;br /&gt;   while (isdigit(*t)) t++;&lt;br /&gt;   if (*t == '\0') return 2;&lt;br /&gt;   &lt;br /&gt;   // exponent part.&lt;br /&gt;   printf ("testing exponent part %s", t); &lt;br /&gt;   if (*t == 'e') t++;&lt;br /&gt;   printf ("after 'e' ");  &lt;br /&gt;   if (*t == '\0') return 0; // error!&lt;br /&gt;   printf ("sign after e?", t);  &lt;br /&gt;   if (*t == '+' || *t == '-') t++;&lt;br /&gt;   printf("%s", t);  &lt;br /&gt;   if (*t == '\0') return 0; // error!&lt;br /&gt;   while (isdigit(*t)) t++;&lt;br /&gt;   if (*t == '\0') return 2; // a floating point number!&lt;br /&gt;   return 0; // not an integer or floating point.&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() &lt;br /&gt;{&lt;br /&gt;  printf("numtype =[%d]", numbertype("-123.34")); &lt;br /&gt;};&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Remove the deubgging printf statements when you use it for applications.&lt;br /&gt;&lt;br /&gt;When the program is run, it returns a code of 2 to denote a floating point number, a 1 for an integer, and a 0 if not a number.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-1127389585267231400?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/1127389585267231400/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/01/does-number-string-represents-integer.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/1127389585267231400'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/1127389585267231400'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/01/does-number-string-represents-integer.html' title='Does a number string represents an integer or a floating value in C?'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-4973345628286415081</id><published>2012-01-14T03:00:00.000-08:00</published><updated>2012-01-14T03:00:02.976-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C'/><category scheme='http://www.blogger.com/atom/ns#' term='Forth'/><category scheme='http://www.blogger.com/atom/ns#' term='interpreter'/><title type='text'>A basic  Forth language interpreter (non-interactive)</title><content type='html'>Last time we showed a simple tokenizer for a Forth interpreter. We find it easier to combine the ideas in that post to create a simple Forth engine which process a simple string. &lt;br /&gt;&lt;br /&gt;We will expound further on this until we successfully build a compiler for a non-standard Forth language.&lt;br /&gt;&lt;br /&gt;Have fun working on this. The current version works on simple strings but specified on the source code itself. We will introduce interactivity and expand the capabilities of this simple Forth interpreter.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="C"&gt;/*&lt;br /&gt;file     simple-forth.c&lt;br /&gt;author   Dr. Ernesto P. Adorio&lt;br /&gt;         UPDEPP (University of the Philippines,&lt;br /&gt;         Extension Program in Pampanga&lt;br /&gt;         Clarkfield, Pampanga&lt;br /&gt;email    ernesto.adorio@gmail.com&lt;br /&gt;version  0.0.1 January 14, 2012&lt;br /&gt;*/&lt;br /&gt;&lt;br /&gt;#include &lt;stdio.h&gt;&lt;br /&gt;#include &lt;ctype.h&gt;&lt;br /&gt;#include &lt;string.h&gt;&lt;br /&gt;#include &lt;stdlib.h&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;#define MAXSTKLEN 32&lt;br /&gt;#define MAXTOKENLEN 128&lt;br /&gt;&lt;br /&gt;enum {L_EMIT, L_ADD, L_SUB, L_MUL, L_DIV, L_POP, L_INT32, L_CR, L_ERROR} OPCODES;&lt;br /&gt;const char *stdwords[] = { &lt;br /&gt;".", &lt;br /&gt;"+",&lt;br /&gt;"-",&lt;br /&gt;"*",&lt;br /&gt;"/",&lt;br /&gt;"pop",&lt;br /&gt;"int32",&lt;br /&gt;"cr",&lt;br /&gt;};&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;int LENSTDWORDS = 8;&lt;br /&gt;&lt;br /&gt;int stack[MAXSTKLEN];&lt;br /&gt;int SP = 0;   /* stack pointer index */&lt;br /&gt;&lt;br /&gt;int main(){&lt;br /&gt;  char tokens[] = "   123 34 + . cr 567 -3456 * . cr";&lt;br /&gt;  char *tokstart = tokens;&lt;br /&gt;  char *tokend = tokstart;&lt;br /&gt;  int  opcode;&lt;br /&gt;&lt;br /&gt;  /* @@@ printf("tokstart: %s\n", tokstart);*/&lt;br /&gt;&lt;br /&gt;  tokend = tokens;&lt;br /&gt;&lt;br /&gt;  while (1) {&lt;br /&gt;    tokstart = tokend;&lt;br /&gt;    /* ignore leading white spaces */&lt;br /&gt;    while (isspace(*tokstart)) tokstart++;&lt;br /&gt;&lt;br /&gt;    /* find terminating space of end of string */&lt;br /&gt;    tokend = tokstart;&lt;br /&gt;    while (!isspace(*tokend) &amp;&amp; *tokend != '\0') tokend++;&lt;br /&gt;    &lt;br /&gt;    /* string terminator */&lt;br /&gt;    if (*tokend != '\0') {&lt;br /&gt;      *tokend = '\0';&lt;br /&gt;      tokend ++;&lt;br /&gt;    } else {&lt;br /&gt;      break;&lt;br /&gt;    } &lt;br /&gt;&lt;br /&gt;    /* get opcode */&lt;br /&gt;    opcode = -1; &lt;br /&gt;    /*@@@ printf("token [%s]\n", tokstart); */&lt;br /&gt;    for (int i =0; i &lt; LENSTDWORDS; i++) {&lt;br /&gt;      if (strcmp(stdwords[i], tokstart) == 0){&lt;br /&gt; opcode = i;&lt;br /&gt;        break;&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;    if (opcode == -1){&lt;br /&gt;      opcode = L_INT32;&lt;br /&gt;    }&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;    /* Evaluate opcode */&lt;br /&gt;    switch (opcode){&lt;br /&gt;    case L_EMIT: &lt;br /&gt;      //printf("opcode L_EMIT %s \n", tokstart);&lt;br /&gt;      printf ("%d", stack[SP--] );&lt;br /&gt;      break;&lt;br /&gt;    case L_ADD:&lt;br /&gt;      //printf("opcode L_ADD %s\n", tokstart);&lt;br /&gt;      stack[SP-1] += stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;    case L_SUB:&lt;br /&gt;      //printf("opcode L_SUB %s\n", tokstart);&lt;br /&gt;      stack[SP-1] += stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;    case L_MUL:&lt;br /&gt;      //printf("opcode L_MUL %s\n", tokstart);&lt;br /&gt;      stack[SP-1] *= stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;    case L_DIV:&lt;br /&gt;      //printf("opcode L_DIV %s\n", tokstart);&lt;br /&gt;      stack[SP-1] /= stack[SP];&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;    case L_INT32:&lt;br /&gt;      //printf("opcode L_INT32 %s\n",tokstart);&lt;br /&gt;      stack[++SP]= atoi(tokstart);&lt;br /&gt;      break;&lt;br /&gt;    case L_POP:&lt;br /&gt;      //printf("opcode L_POP %s \n", tokstart);&lt;br /&gt;      SP--;&lt;br /&gt;      break;&lt;br /&gt;    case L_CR:&lt;br /&gt;      // printf("opcode L_CR %s \n", tokstart);&lt;br /&gt;      printf("\n");&lt;br /&gt;    }  &lt;br /&gt;  }&lt;br /&gt;  printf("\n");&lt;br /&gt;  return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Save the code to a file simple-forth.c, then compile using the following command line on the directory where the source file is stored.&lt;tt&gt;gcc simple-forth.c -std=c99 -o forth&lt;/tt&gt;It should compile cleanly, then execute the executible by issuing ./forthWhen the program runs, it prints out&lt;pre&gt;toto@toto-Aspire-4520:~/Blogs/my-other-life-as-programmer/forth$ ./forth&lt;br /&gt;157&lt;br /&gt;-1959552&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-4973345628286415081?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/4973345628286415081/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/01/basic-forth-language-interpreter-non.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/4973345628286415081'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/4973345628286415081'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2012/01/basic-forth-language-interpreter-non.html' title='A basic  Forth language interpreter (non-interactive)'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-1348671302714510341</id><published>2011-10-18T07:22:00.001-07:00</published><updated>2012-01-25T07:05:43.787-08:00</updated><title type='text'></title><content type='html'>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;&lt;br /&gt;Testing latex server by watchmath.com.&lt;br /&gt;&lt;br /&gt;The are of a triangle is $\frac{1}{2}b*h$.&lt;br /&gt;&lt;br /&gt;I thought this was working already! Oh, I have to redo the installation.&lt;br /&gt;&lt;br /&gt;January 15, 2012: This is making me sick! this does not work anymore!  I changed to mathjax latex server. For instructions, refer to &lt;a href="http://tex.stackexchange.com/questions/13865/how-to-use-latex-on-blogspot"&gt;tex.stackexchange.com&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-1348671302714510341?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/1348671302714510341/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/10/testing-latex-server-by-watchmath.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/1348671302714510341'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/1348671302714510341'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/10/testing-latex-server-by-watchmath.html' title=''/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-577230967588700388</id><published>2011-10-13T17:14:00.000-07:00</published><updated>2011-10-13T17:14:40.425-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C'/><category scheme='http://www.blogger.com/atom/ns#' term='Dennis Ritchie'/><title type='text'>Dennis Ritchie (September 9, 1941 – October 8, 2011: inventor of C programming language</title><content type='html'>One of my regrets in life is not having to meet in person Dennis Ritichie, the developer of the C programmng language.&lt;br /&gt; &lt;br/&gt;&lt;br /&gt;&lt;br /&gt;I will never forget the time I have to understand pointers (I suspect my instructor did not understand much too!). C is like more a friendlier assembly language in English! C++, Java may be more "in" these days, but they owe their success to the pioneering path blazed by C.&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-577230967588700388?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/577230967588700388/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/10/dennis-ritchie-september-9-1941-october.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/577230967588700388'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/577230967588700388'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/10/dennis-ritchie-september-9-1941-october.html' title='Dennis Ritchie (September 9, 1941 – October 8, 2011: inventor of C programming language'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-6783445593438508098</id><published>2011-10-12T12:52:00.000-07:00</published><updated>2011-10-12T12:59:21.813-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='combinatorics'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><category scheme='http://www.blogger.com/atom/ns#' term='itertools'/><title type='text'>Python: Permutations, Combinations, Cartesian Products with Itertools module</title><content type='html'>Python itertools module has built-in functions for permutations, combinations, cycles and products.&lt;br /&gt;So the Python programmers can focus on building the next killer-apps :) which will dominate the whole world, instead&lt;br /&gt;of reading obtuse treatises, papers, and other publications on algorithms for generating combinatorial objects.&lt;br /&gt;&lt;br /&gt;Here we list the combinatorial capabilities of Python (versions 2.6+) in the itertools module.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;&lt;h4&gt;Permutations&lt;/h4&gt;&lt;br /&gt;itertools.permutation create a permutation object from an iterable input or string. You can list&lt;br /&gt;the successive permutations by using object.next() or by creating a list (a bad idea if the size of the object is large!)&lt;br /&gt;list(object). Here is an example:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="Python"&gt;x = itertools.permutation(range(7))&lt;br /&gt;   try:&lt;br /&gt;      while True:&lt;br /&gt;        print x.next()&lt;br /&gt;   except:&lt;br /&gt;      pass&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;You can also do:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="Python"&gt;x = itertools.permutation(range(7))&lt;br /&gt;   for i, e in enumerate(list(x)):&lt;br /&gt;       print i+1, e&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Converting to a list give rise to a dangerous situation where you can run out of memory!. but if you know that it can be safely stored,&lt;br /&gt;by all means use a list conversion.&lt;br /&gt;&lt;br /&gt;Permutations can also accept an extra parameter r so you can generate all permutations of size n of the object taken r at a time.&lt;br /&gt;The number of elements in such permutations is given by n!/(n-r)!. If r is not specified, then the number of permutations is n!&lt;br /&gt;which look innocous.(50! is nothing to sneeze at).&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;&lt;li&gt;&lt;h4&gt;combinations&lt;/h4&gt;&lt;/li&gt;itertools.combinations creates a combinatorial object. Here ordering does not matter. As an example, the combinations of    6 elements taken 3 at a time can be listed in two groups, as follows:  &lt;pre name="code" class="Python"&gt;import itertools&lt;br /&gt;&lt;br /&gt;seq = range(6)&lt;br /&gt;x = itertools.combinations(seq, 3)&lt;br /&gt;&lt;br /&gt;try:&lt;br /&gt;  for i, e in list(enumerate(x)):&lt;br /&gt;     f = [y for y in seq if y not in e]&lt;br /&gt;     print i+1, list(e), f&lt;br /&gt;except:&lt;br /&gt;   pass&lt;br /&gt;&lt;/pre&gt;The output of permutations and combinations are tuples for fast execution of the functions,  and have to be typecast to a list. Itertools also provide combinations with replacement. The best way to see the difference with the standard combinations is to see them in action from the command line:  &lt;pre name="code" class="Python"&gt;x = combinations_with_replacement([1,2,3,4], 2)&lt;br /&gt;y = combinations([1,2,3,4], 2)&lt;br /&gt;&lt;br /&gt;list(x)&lt;br /&gt;[(1, 1),&lt;br /&gt; (1, 2),&lt;br /&gt; (1, 3),&lt;br /&gt; (1, 4),&lt;br /&gt; (2, 2),&lt;br /&gt; (2, 3),&lt;br /&gt; (2, 4),&lt;br /&gt; (3, 3),&lt;br /&gt; (3, 4),&lt;br /&gt; (4, 4)]&lt;br /&gt;&lt;br /&gt;list(y)&lt;br /&gt;[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]&lt;br /&gt;&lt;/pre&gt;&lt;/li&gt;&lt;li&gt;&lt;h4&gt;Cartesion products&lt;/h4&gt;&lt;br /&gt;Itertools has cartesian products! So instead of writing (this from the documentation)&lt;br /&gt;&lt;br /&gt;((x,y) for x in A for y in B)&lt;br /&gt;&lt;br /&gt;we simply write product(A,B)&lt;br /&gt;&lt;br /&gt;Wait, how about the cartesian product of A with itself?&lt;br /&gt;you can write product(A,A) or if you want more, product(A,A,A,A). The latter can be written as&lt;br /&gt;product(A, repeat=4). Python programmers can be lazy as Perl programmers!&lt;br /&gt;&lt;br /&gt;&lt;li&gt;&lt;h4&gt;cycle&lt;/h4&gt;&lt;/li&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Not strictly referrring to a mathematical object. Rather it refers to the way an element in an&lt;br /&gt;iterable is accessed. Instead of stopping at the last element, the access is cycled back to the first element.&lt;br /&gt;Try this on the command line (not running in a script file)&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="Python"&gt;x = cycle((1,2,3,4))&lt;br /&gt;while True:&lt;br /&gt;   print x.next()&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;You will notice that this loop never terminates, and after the 4 is printed, the next element to be printed is the first element.&lt;br /&gt;Type Ctrl-C to abort the printing.&lt;br /&gt;&lt;br /&gt;&lt;/li&gt;&lt;/ul&gt;&lt;br /&gt;Aside from these basic combinatorial objects, Itertools provide now a  &lt;tt&gt;repeat &lt;/tt&gt; function! For example, a list of 100&lt;br /&gt;elements with all values equal to 5: [5] * 100 can now be written as itertools.repeat(5, 100). Easier to understand for beginners.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Dont you just love Python?&lt;br /&gt;&lt;br /&gt;Hopefully, Python will offer genuine cycle objects (where you can multiply two cycles) and derangements with basic functions such as nPr and nCr. These combinatorial features are solutions waiting for problems and applications!&lt;br /&gt;&lt;br /&gt;TO BE CONTINUED.&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-6783445593438508098?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/6783445593438508098/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/10/python-itertools-module-has-built-in.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/6783445593438508098'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/6783445593438508098'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/10/python-itertools-module-has-built-in.html' title='Python: Permutations, Combinations, Cartesian Products with Itertools module'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-2155441200220595681</id><published>2011-10-01T16:02:00.000-07:00</published><updated>2011-10-02T17:54:46.754-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Problems for Programmers'/><category scheme='http://www.blogger.com/atom/ns#' term='Games and Puzzles'/><title type='text'>Programming Problems: Replace numbers in a list by an increasing sequence.</title><content type='html'>Consider X = [1, 5, 7, 1, 34]. We want to replace this by X = [1,3,2,1,4]. &lt;br /&gt;Consider X = [1000, 500, 700, 5000, 700]. We want to replace this by [3, 1,2,4,2].  &lt;br /&gt;&lt;br /&gt;Criteria:&lt;br /&gt;1.  Use Python. Sorry no java.&lt;br /&gt;2.  Fewest lines of code.&lt;br /&gt;3.  Elegant, not to use a temporary copy and not  using a convoluted BRUTE force method as in the following example, yes I wrote it but that was a temporary solution.  I refuse to give a hint, but Python has a powerful discrete math function :)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;tempR = X[:]&lt;br /&gt;        for j in range(1, n+1):&lt;br /&gt;            minrank =  min(tempR)&lt;br /&gt;            for k in range(n):&lt;br /&gt;                if X[k] == minrank and k&lt; n+1:&lt;br /&gt;                    X[k] = j&lt;br /&gt;                    tempR[k] = n+1&lt;br /&gt;        return X   &lt;br /&gt;&lt;/pre&gt;4. Name your function, &lt;tt&gt;normalsequence(X). &lt;/tt&gt;. Here is what I believe a more elegant solution.&lt;pre class="Python" name="code"&gt;def normalsequence(X):&lt;br /&gt;      #ensure that  the ranks are in sequence!&lt;br /&gt;         for i, x in enumerate(sorted(list(set(R[:])))):&lt;br /&gt;             for j, y in enumerate(R):&lt;br /&gt;                 if y == x:&lt;br /&gt;                    R[j] = i+1  &lt;br /&gt;&lt;/pre&gt;Far more sophisticated (one-liners) for a similar problem is &lt;a href="http://stackoverflow.com/questions/3071415/efficient-method-to-calculate-the-rank-vector-of-a-list-in-python"&gt;stack overflow: efficient method to calculate the rank vector of a Python list&lt;/a&gt;.This solution is also part of the Python code for transforming raw scores to ranks in my other post &lt;a href="http://dr-adorio-adventures.blogspot.com/2011/10/there-are-some-nonparametric.html"&gt;Python, statistics: Ranking a single array of raw scores&lt;/a&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-2155441200220595681?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/2155441200220595681/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/10/programming-problems-replace-numbers-in.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/2155441200220595681'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/2155441200220595681'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/10/programming-problems-replace-numbers-in.html' title='Programming Problems: Replace numbers in a list by an increasing sequence.'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-5884322583141591365</id><published>2011-09-27T11:00:00.000-07:00</published><updated>2011-09-27T18:17:07.523-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ephem'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>Python: Computing sunrise sunset times with ephem</title><content type='html'>It is incredibly easy to find the sunrise and sunset for the city of Manila using Python and ephem libary. Here is for today, September 28, 2011&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code"  class="Python"&gt;import ephem&lt;br /&gt;&lt;br /&gt;manila = ephem.city("Manila")&lt;br /&gt;sun    = ephem.Sun()&lt;br /&gt;manila.date="2011/09/28"&lt;br /&gt;sunrise= manila.next_rising(sun)&lt;br /&gt;sunset = manila.next_setting(sun)&lt;br /&gt;&lt;br /&gt;print ephem.localtime(sunrise)&lt;br /&gt;print ephem.localtime(sunset )&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;When run within ipython, it results in &lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;In[xxx]: print ephem.localtime(sunrise)&lt;br /&gt;2011-09-29 05:45:16.000003&lt;br /&gt;&lt;br /&gt;In [xxx]: print ephem.localtime(sunset )&lt;br /&gt;2011-09-28 17:48:28.000002&lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Times returned by ephem are always in UTC, a point which puzzled me for more than 30 minutes, wondering what was wrong! We only have to explicitly call the localtime function.&lt;br /&gt;&lt;br /&gt;The ephem library knows some cities already. Here is information about Manila:&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;ephem.Observer date='2011/9/28 00:00:00' epoch='2000/1/1 12:00:00' long=120:58:56.0 lat=14:36:15.0&lt;br /&gt;&lt;br /&gt;elevation=7.9248m horizon=0:00:00.0 temp=15.0C pressure=1012.29834492mBar&lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;What if you live in Angeles City, the Philippines? Here is a modified Python code:&lt;br /&gt;&lt;br /&gt;&lt;pre name="code"  class="Python"&gt;import ephem&lt;br /&gt;&lt;br /&gt;# manila = ephem.city("Manila")&lt;br /&gt;# Angeles has longitude, latitude of 15°09'N	120°33'E respectively.&lt;br /&gt;mycity= ephem.Observer()&lt;br /&gt;mycity.long= "120:33"&lt;br /&gt;mycity.lat="15:09"&lt;br /&gt;&lt;br /&gt;sun    = ephem.Sun()&lt;br /&gt;mycity.date="2011/09/28"&lt;br /&gt;sunrise= mycity.next_rising(sun)&lt;br /&gt;sunset =mycity.next_setting(sun)&lt;br /&gt;print ephem.localtime(sunrise)&lt;br /&gt;print ephem.localtime(sunset )&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Here is the output for Angeles City.&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;In [xxx]: print ephem.localtime(sunrise)&lt;br /&gt;2011-09-29 05:47:04.000003&lt;br /&gt;&lt;br /&gt;In [xxx]: print ephem.localtime(sunset )&lt;br /&gt;2011-09-28 17:50:07.000002&lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;We shall put up an ephemeris data page shortly. To view instructions for installation of PyEphem, please visit&lt;br /&gt;&lt;a href="http://free-software-explorations.blogspot.com/2010/07/pyephem-ephemeris-computation-library.html"&gt;http://free-software-explorations.blogspot.com/2010/07/pyephem-ephemeris-computation-library.html&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-5884322583141591365?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/5884322583141591365/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/09/python-computing-sunrise-sunset-times.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/5884322583141591365'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/5884322583141591365'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/09/python-computing-sunrise-sunset-times.html' title='Python: Computing sunrise sunset times with ephem'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-8216694912375382205</id><published>2011-09-25T18:16:00.000-07:00</published><updated>2011-09-25T18:18:51.518-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Conjugate gradient'/><category scheme='http://www.blogger.com/atom/ns#' term='matlib'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><category scheme='http://www.blogger.com/atom/ns#' term='Numerial Methods'/><title type='text'>Python:  basic conjugate gradient linear solver</title><content type='html'>Visit &lt;a href="http://en.wikipedia.org/wiki/Conjugate_gradient_method"&gt;Wikipedia:Conjugate gradient method&lt;/a&gt; for a clear and succinct explanation of the conjugate gradient method for solving linear equations. We based our Python code on the algorithm described in this article. We are pleased that we were able to get the same results for the simple example involving a 2 by 2 system,&lt;pre name="code" class="Python"&gt;&lt;br /&gt;# -*- coding: utf-8 -*-&lt;br /&gt;&lt;br /&gt;"""&lt;br /&gt;File     conjgrad.py&lt;br /&gt;Author   Ernesto P. Adorio&lt;br /&gt;         UPDEPP Clarfield&lt;br /&gt;email    ernesto.adorio@gmail.com          &lt;br /&gt;ref.     http://en.wikipedia.org/wiki/Conjugate_gradient_method&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;from matlib import *&lt;br /&gt;&lt;br /&gt;def conjgrad(A, b, x = None, ztol = 1.0e-4, maxiter = None):&lt;br /&gt;    """&lt;br /&gt;    Solves the equation Ax = b by iteration using conjugate gradients.&lt;br /&gt;    Arguments &lt;br /&gt;      A- symmetric positive definite matrix.&lt;br /&gt;&lt;br /&gt;    """&lt;br /&gt;    print "input A=", A&lt;br /&gt;    print "input b=", b&lt;br /&gt;    print "input x=", x&lt;br /&gt;    if x is None:&lt;br /&gt;       x = [0] * len(b)&lt;br /&gt;    m, n = matdim(A)&lt;br /&gt;    if m != n or m!= len(b):&lt;br /&gt;       raise ValueError&lt;br /&gt;    if maxiter is None:&lt;br /&gt;       maxiter = m    &lt;br /&gt;    rk = vecsub(b, matvec(A, x))&lt;br /&gt;    print "r_0 =", rk&lt;br /&gt;    pk = rk[:]&lt;br /&gt;    num    = dot(rk, rk)&lt;br /&gt;&lt;br /&gt;    for k in range(1,maxiter):&lt;br /&gt;        print "iteration #", k&lt;br /&gt;        Apk    = matvec(A, pk)&lt;br /&gt;        den    = dot(pk, Apk)&lt;br /&gt;        alphak = num/float(den)&lt;br /&gt;        print "num/den=", num, den, alphak&lt;br /&gt;&lt;br /&gt;        #update x.&lt;br /&gt;        x  = [e  + alphak * p for (e,p) in zip(x, pk)]&lt;br /&gt;        print "x = ", x&lt;br /&gt;&lt;br /&gt;        #update rk.&lt;br /&gt;        rk    = [r - alphak * apk for r, apk in zip(rk, Apk)]&lt;br /&gt;        dotrk = dot(rk, rk)&lt;br /&gt;        if num &lt; ztol:&lt;br /&gt;           return x, k&lt;br /&gt;        print "rkp1=", rk&lt;br /&gt;&lt;br /&gt;        #update pk&lt;br /&gt;        betak = dotrk/num&lt;br /&gt;        num   = dotrk&lt;br /&gt;        pk    = [r + betak* p for r, p in zip(rk, pk)] &lt;br /&gt;        print "betak=", betak&lt;br /&gt;        print "pk=", pk&lt;br /&gt;        print&lt;br /&gt;    return x, maxiter  &lt;br /&gt;&lt;br /&gt;def vec2mat(x, nrows, ncols):&lt;br /&gt;    if nrows * ncols != len(x):&lt;br /&gt;       raise ValueError,"incompatible dimensions in vec2mat()"&lt;br /&gt;    M = []&lt;br /&gt;    for i in range(nrows):&lt;br /&gt;       M.append(x[i*ncols:(i+1)*ncols])&lt;br /&gt;&lt;br /&gt;    return M   &lt;br /&gt;&lt;br /&gt;     &lt;br /&gt;if __name__ == "__main__":&lt;br /&gt;   A = vec2mat([4,1,1,3],2,2)&lt;br /&gt;   b = [1,2]&lt;br /&gt;   x = [2,1]&lt;br /&gt;   sol = conjgrad(A,b, x,ztol = 1.0e-4, maxiter=5)&lt;br /&gt;   print "sol=", sol&lt;br /&gt;&lt;/pre&gt;   We will soon add the vec2mat() function included in the code above in the matlib.py function.Please note that this author recommends using the numpy and scipy Python modules. They are well tested and provide a wrapper to the linear algebra routines developed in EISPACK and  LINPACK. scientific libraries which were coded in C.Here are the results of running the above from the terminal:&lt;tt&gt;&lt;pre&gt;&lt;br /&gt;&lt;br /&gt;toto@toto-Aspire-4520:~/Blogs/lm$ python conjgrad.py &lt;br /&gt;input A= [[4, 1], [1, 3]]&lt;br /&gt;input b= [1, 2]&lt;br /&gt;input x= [2, 1]&lt;br /&gt;r_0 = [-8, -3]&lt;br /&gt;iteration # 1&lt;br /&gt;num/den= 73 331 0.220543806647&lt;br /&gt;x =  [0.2356495468277946, 0.33836858006042303]&lt;br /&gt;rkp1= [-0.2809667673716012, 0.7492447129909365]&lt;br /&gt;betak= 0.00877136937414&lt;br /&gt;pk= [-0.3511377223647101, 0.7229306048685207]&lt;br /&gt;&lt;br /&gt;iteration # 2&lt;br /&gt;num/den= 0.640309964312 1.55338036659 0.412204234122&lt;br /&gt;x =  [0.09090909090909094, 0.6363636363636365]&lt;br /&gt;rkp1= [5.551115123125783e-17, 0.0]&lt;br /&gt;betak= 4.81249407751e-33&lt;br /&gt;pk= [5.551115123125783e-17, 3.4790992543769425e-33]&lt;br /&gt;&lt;br /&gt;iteration # 3&lt;br /&gt;num/den= 3.08148791102e-33 1.23259516441e-32 0.25&lt;br /&gt;x =  [0.09090909090909095, 0.6363636363636365]&lt;br /&gt;sol= ([0.09090909090909095, 0.6363636363636365], 3)&lt;br /&gt;toto@toto-Aspire-4520:~/Blogs/lm$         &lt;br /&gt; &lt;/pre&gt;&lt;/tt&gt;  Of course remove the print statements to avoid the computational progress reports. Our aim here is mainly pedagogical. The Python code is easier to read and one can use a debugger (as in Eric4)  to walk through the code!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-8216694912375382205?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/8216694912375382205/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/09/python-basic-conjugate-gradient-linear.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/8216694912375382205'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/8216694912375382205'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/09/python-basic-conjugate-gradient-linear.html' title='Python:  basic conjugate gradient linear solver'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-7240697899624867986</id><published>2011-09-17T17:29:00.000-07:00</published><updated>2011-09-18T12:12:25.646-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='data types'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>Does a string represents a floating point number, an integer or a plain string?</title><content type='html'>I have been programming in Python a long long time, I have not  coded as a function one of the most common tests on a string, for the simple reason that it is easy to program directly. Here, we ask: does a string represents a floating point number(reals), an integer or if not these types, a plain string?&lt;br/&gt;Here are simple test cases: -123., -123e0, -123, . will be considered reals or floats. Numbers which do not contain a decimal point or dot or an exponentiation part will be considered integers. Here is our function.&lt;pre  class="Python" name="code"&gt;&lt;br /&gt;"""&lt;br /&gt;file            dtypeval.py&lt;br /&gt;&lt;br /&gt;author      Ernesto P. Adorio, PhD.&lt;br /&gt;                 UPDEPP at Clarkfield, Pampanga&lt;br /&gt;&lt;br /&gt;version    0.0.1 september 19, 2011&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def dtypeval(s, numericfloat=False):&lt;br /&gt;    """&lt;br /&gt;    Simple function to return the data type and value of a string.&lt;br /&gt;    """&lt;br /&gt;    try:&lt;br /&gt;        if numericfloat or ("." in s) or ("e" in s) or ("E" in s):&lt;br /&gt;           f = float(s)&lt;br /&gt;           return "float", f&lt;br /&gt;        return "int", int(s) &lt;br /&gt;    except:&lt;br /&gt;        # print "[%s] is not a number!" % s&lt;br /&gt;        return "str", s&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;if __name__ == "__main__":&lt;br /&gt;   teststring  = ["-123.", "-123", "1e5", "1E5", ".001", "ABC"]&lt;br /&gt;&lt;br /&gt;   for s in teststring:&lt;br /&gt;       print s,"==&gt;", dtypeval(s)&lt;br /&gt;&lt;/pre&gt;Save the above to dtypeval.py and run from the command line &lt;tt&gt;python dtype.val&lt;/tt&gt;. Here is the output:&lt;pre&gt;&lt;br /&gt;-123. ==&gt; ('float', -123.0)&lt;br /&gt;-123 ==&gt; ('int', -123)&lt;br /&gt;1e5 ==&gt; ('float', 100000.0)&lt;br /&gt;1E5 ==&gt; ('float', 100000.0)&lt;br /&gt;.001 ==&gt; ('float', 0.001)&lt;br /&gt;ABC ==&gt; [ABC] is not a number!&lt;br /&gt;('str', 'ABC')&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;Note that numericfloat is set to true if the function is to return float always even if the input sting  represents an integer.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-7240697899624867986?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/7240697899624867986/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/09/does-string-represents-floating-point.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/7240697899624867986'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/7240697899624867986'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/09/does-string-represents-floating-point.html' title='Does a string represents a floating point number, an integer or a plain string?'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-2942024509913098571</id><published>2011-08-31T23:39:00.000-07:00</published><updated>2011-08-31T23:42:21.308-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Statistics'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>Python: Sampling from a normal population</title><content type='html'>Here is code to create N samples of size n from a normal population with mean mu and standard deviation sigma.&lt;pre class="Python" name="code"&gt;&lt;br /&gt;"""&lt;br /&gt;File             normalsim.py&lt;br /&gt;Author           Dr. Ernesto P. Adorio&lt;br /&gt;Desc             Sampling from the normal distribution.&lt;br /&gt;Version          0.0.1 Sep. 1, 2011&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;import numpy as np&lt;br /&gt;import scipy.stats as stat&lt;br /&gt;from math import sqrt&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def  normalsim(mu, sigma, n, N, statistic="mean"):&lt;br /&gt;    out = [0] * N&lt;br /&gt;    for i in range(N):&lt;br /&gt;        sample = stat.norm.rvs(mu, sigma, size=n)&lt;br /&gt;        #print sample, &lt;br /&gt;        if statistic=="mean":&lt;br /&gt;           out[i] = np.mean(sample)&lt;br /&gt;        elif statistic=="svar":&lt;br /&gt;           out[i] = np.var(sample, ddof=1)&lt;br /&gt;        elif statistic=="pvar":&lt;br /&gt;           out[i] = np.var(sample)&lt;br /&gt;        elif statistic=="ssdev":&lt;br /&gt;           out[i] = sqrt(np.var(sample, ddof=1))&lt;br /&gt;        elif statistic=="psdev":&lt;br /&gt;           out[i] = np.var(sample)&lt;br /&gt;        elif statistic== "min":&lt;br /&gt;           out[i] = min(sample)&lt;br /&gt;        elif statistic == "max":&lt;br /&gt;           out[i] = max(sample)&lt;br /&gt;        else:&lt;br /&gt;           raise ArgumentError,"bad statistic."&lt;br /&gt;        #print out[i]&lt;br /&gt;    return out&lt;br /&gt;&lt;br /&gt;v = normalsim(10, 4, 10, 1000, statistic="svar")&lt;br /&gt;print np.mean(v), np.var(v)&lt;br /&gt;&lt;/pre&gt;When  I run the program under the time command, time python normalsim.py, the shell outputted&lt;pre&gt;&lt;br /&gt;15.7770857263 55.2458134956&lt;br /&gt;&lt;br /&gt;real    0m2.681s&lt;br /&gt;user    0m1.080s&lt;br /&gt;sys     0m0.070s&lt;br /&gt;&lt;/pre&gt;Problem: Can you rewrite the code so it will be faster? HINT: a comparison is always used inside the loop!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-2942024509913098571?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/2942024509913098571/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/08/python-sampling-from-normal-population.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/2942024509913098571'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/2942024509913098571'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/08/python-sampling-from-normal-population.html' title='Python: Sampling from a normal population'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-4005790748247274164</id><published>2011-07-27T06:04:00.000-07:00</published><updated>2011-07-27T06:14:11.812-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='processing names'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>Python: converting names to surname, firstname format.</title><content type='html'>&lt;div dir="ltr" style="text-align: left;" trbidi="on"&gt;&lt;br /&gt;we want to convert names like&lt;br /&gt;&lt;br /&gt;Jose P. Rizal to Rizal, Jose P.&lt;br /&gt;Jose P. Rizal Jr. to Rizal Jr., &amp;nbsp; Jose P.&lt;br /&gt;Ma. Jose P. Rizal III to Rizal III, Ma. Jose P.&lt;br /&gt;&lt;br /&gt;Here is Python code to perform the conversion. I am wondering if one can write a more elegant version, where by elegant, it does the conversion in a faster, shorter way!&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="Python" name="code"&gt;"""&lt;br /&gt;file &amp;nbsp; &amp;nbsp; lastfirstname.py&lt;br /&gt;author &amp;nbsp; Ernesto P. Adorio, PhD.&lt;br /&gt;desc &amp;nbsp; &amp;nbsp; Converts name to last name, first name format.&lt;br /&gt;version &amp;nbsp;0.0.1 july 27, 2011&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;def makestr(sarray, lastindex):&lt;br /&gt;&amp;nbsp; &amp;nbsp; """&lt;br /&gt;&amp;nbsp; &amp;nbsp;&lt;br /&gt;&amp;nbsp; &amp;nbsp; """&lt;br /&gt;&amp;nbsp; &amp;nbsp; output = ""&lt;br /&gt;&amp;nbsp; &amp;nbsp; for s in sarray[:lastindex]:&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;output += (" " + s )&lt;br /&gt;&amp;nbsp; &amp;nbsp; return output&lt;br /&gt;&lt;br /&gt;def surnamefirstname(name):&lt;br /&gt;&amp;nbsp; &amp;nbsp; """&lt;br /&gt;&amp;nbsp; &amp;nbsp; Translates a name in firstname surname to&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; surname, firstname format.&lt;br /&gt;&amp;nbsp; &amp;nbsp; Complications arise because surname can include "Jr." or romanized numbers "III"&lt;br /&gt;&amp;nbsp; &amp;nbsp; """&lt;br /&gt;&amp;nbsp; &amp;nbsp; parts = name.split()&lt;br /&gt;&amp;nbsp; &amp;nbsp; n = len(parts)&lt;br /&gt;&amp;nbsp; &amp;nbsp; if n == 2:&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;# easiest case&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;return parts[1] + ", " + parts[0]&lt;br /&gt;&amp;nbsp; &amp;nbsp; elif n &amp;gt; 2:&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;if parts[-1].lower() in ["jr.", "jr"]:&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return parts[-2] +" Jr.," + makestr(parts, -2)&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;elif parts[-1].lower() in ["ii", "iii", "iv", "v"]:&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return parts[-2] + " " +parts[-1].upper()+ "," &amp;nbsp;+ makestr(parts, -2)&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp;else:&lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return parts[-1] + "," + makestr(parts, -1)&lt;br /&gt;&amp;nbsp;&lt;br /&gt;print surnamefirstname("Ma. Jose P. Rizal III")&lt;br /&gt;&lt;/pre&gt;&amp;nbsp; &lt;br /&gt;&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &lt;br /&gt;&lt;br /&gt;Post you own better version in the comments. We shall learn together to improve our Python skills.&lt;br /&gt;&lt;br /&gt;&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-4005790748247274164?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/4005790748247274164/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/07/python-converting-names-to-surname.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/4005790748247274164'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/4005790748247274164'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/07/python-converting-names-to-surname.html' title='Python: converting names to surname, firstname format.'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-9102641697324896932</id><published>2011-07-08T02:11:00.000-07:00</published><updated>2011-07-08T02:17:15.115-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>A beginning Python programming challenge: replace slow array.index() calls.</title><content type='html'>&lt;br /&gt;For simplicity, consider the following arrays:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;&lt;blockquote&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;i &amp;nbsp; &amp;nbsp; &amp;nbsp;0 &amp;nbsp;1 &amp;nbsp; 2  3 &amp;nbsp;4 &amp;nbsp;5 &amp;nbsp;6 &amp;nbsp;7 &amp;nbsp;8 &amp;nbsp;9 &amp;nbsp;10&lt;br /&gt;&lt;br /&gt;order1 6 &amp;nbsp;9 &amp;nbsp; 7 10 &amp;nbsp;5 &amp;nbsp;8 3 &amp;nbsp;2 &amp;nbsp;4 &amp;nbsp; 0 &amp;nbsp;&amp;nbsp;1&lt;br /&gt;&lt;br /&gt;order2 7 &amp;nbsp;6 &amp;nbsp;10 &amp;nbsp;8 &amp;nbsp;5 &amp;nbsp;9 1 &amp;nbsp;4 &amp;nbsp;2 &amp;nbsp; 0 &amp;nbsp;&amp;nbsp;3&lt;/blockquote&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Now consider the following Python snippet of code:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre class="code" lang="Python"&gt;myindex = range(11)&lt;br /&gt;&lt;br /&gt;for i in range(11):&lt;br /&gt;&lt;br /&gt;&amp;nbsp; &amp;nbsp; myindex[i] = order2[order1.index[i]]&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;As an example consider a current i value of 0. The value of index1[0] is 6. The position of 6 in order2 is of 6 in index2 array is 1(first element has index0). Therefore myindex[0] = 1.&lt;br /&gt;&lt;br /&gt;On the other hand, the value of index1[1] is 9. The ordinal position of 9 in index2 is 5. Hence myindex[1] = 5.&lt;br /&gt;&lt;br /&gt;Problem 1. Can you replace the code without using dictionaries and the index function?&lt;br /&gt;You may not modify inplace the order1 and order2 arrays. You may create an additional extra array.&lt;br /&gt;&lt;br /&gt;Problem 2. &amp;nbsp;Rewrite the code to use a dictionary. This is much easier.&lt;br /&gt;&lt;br /&gt;Imagine your are doing the for loop of 1,000,000 array items! Have fun!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-9102641697324896932?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/9102641697324896932/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/07/beginning-python-programming-challenge.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/9102641697324896932'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/9102641697324896932'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/07/beginning-python-programming-challenge.html' title='A beginning Python programming challenge: replace slow array.index() calls.'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-5964185949248131643</id><published>2011-07-03T08:05:00.000-07:00</published><updated>2011-10-12T06:07:03.301-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='k-subsets'/><category scheme='http://www.blogger.com/atom/ns#' term='combinatorics'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>Python: Generating all subsets of size k for n objects.</title><content type='html'>In our main blog, we presented a routine for generating all subsets of set, expressed as an array or vector of indices to the n objects (0 to n-1).See &lt;a href="http://adorio-research.org/wordpress/?p=6791"&gt;Generating all subsets of a set with n objects&lt;/a&gt; In this article we present an "odometer" method of generating all subsets of specific size k where k &lt; n. For example, for n = 5 and k = 3, we expect the function to return the set containing the following vectors: [0,1,2], [0, 1,3], [0,1,4], [0,2,3] and so on up to [2,3,4].Here is our Python code.&lt;pre name="code" class="python"&gt;&lt;br /&gt;&lt;br /&gt;# -*- coding: utf-8 -*-&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;File      ksubsets.py&lt;br /&gt;&lt;br /&gt;Author    Ernesto P. Adorio, Ph.D.&lt;br /&gt;&lt;br /&gt;UPDEPP, UP Clarkfield  &lt;br /&gt;&lt;br /&gt;Universty of the Philippines Extension Program in Pampanga&lt;br /&gt;&lt;br /&gt;Desc      generates subsets (as indices) with k elements from a set of size n.&lt;br /&gt;&lt;br /&gt;Version   0.0.1  2011.07.03&lt;br /&gt;&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def  ksubsets (n,  k):&lt;br /&gt;&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;generates the list of subsets (as index array) of n elements&lt;br /&gt;&lt;br /&gt;chosen k at a time. Combinations actually!&lt;br /&gt;&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;#sanity check&lt;br /&gt;&lt;br /&gt;if n &lt;0 or k &lt;0 or n - k &lt; 0:&lt;br /&gt;        return None&lt;br /&gt;    N = range(k)&lt;br /&gt;    retval = [N[:]]&lt;br /&gt;    print "initial N=", N&lt;br /&gt;    &lt;br /&gt;    #update current N vector.&lt;br /&gt;    level = k-1&lt;br /&gt;    while level &gt;=0:&lt;br /&gt;&lt;br /&gt;d = N[level]&lt;br /&gt;&lt;br /&gt;#test if element is already  at maximum value.&lt;br /&gt;&lt;br /&gt;if d &lt; n - k + level:  &lt;br /&gt;            # No, increment the value.  &lt;br /&gt;            N[level]+= 1&lt;br /&gt;            #repair trailing elements.&lt;br /&gt;            for i in range(level+1,  k):&lt;br /&gt;                N[i] = N[i-1] + 1&lt;br /&gt;            #append newly generated subset.&lt;br /&gt;            retval.append(N[:])&lt;br /&gt;            level = k-1&lt;br /&gt;        else:&lt;br /&gt;            # position N[level] already at maximum value!&lt;br /&gt;            level -= 1&lt;br /&gt;    return retval&lt;br /&gt;    &lt;br /&gt;for i,  subset in enumerate(ksubsets(5,  3)):&lt;br /&gt;    print i,  subset&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;When the above program is run, it outputs the expected results:&lt;br /&gt;&lt;br /&gt;&lt;blockquote&gt;0 [0, 1, 2]&lt;br /&gt;1 [0, 1, 3]&lt;br /&gt;2 [0, 1, 4]&lt;br /&gt;3 [0, 2, 3]&lt;br /&gt;4 [0, 2, 4]&lt;br /&gt;5 [0, 3, 4]&lt;br /&gt;6 [1, 2, 3]&lt;br /&gt;7 [1, 2, 4]&lt;br /&gt;8 [1, 3, 4]&lt;br /&gt;9 [2, 3, 4]&lt;br /&gt;&lt;/blockquote&gt;&lt;br /&gt;How does the code work? First it initializes the first member of the set of subsets as&lt;br /&gt;[0, 1, ..., k-1]. Next, starting from the rightmost (level = k-1)position  it checks whether the current element is at maximum. If it is not it is incremented and any trailing positions adjusted to be 1 greater than at the preceding position. Otherwise the level is decremented and the process repeats.&lt;br /&gt;&lt;br /&gt;Exercise: write a generator version of the above code. We will present the solution on the next revision.&lt;br /&gt;&lt;br /&gt;The itertools module has a combinations function. After importing, one simply writes:&lt;br /&gt;&lt;tt&gt;list(combinations (range(5), 3)).&lt;/tt&gt;. Python just makes it TOO easy!&lt;br /&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-5964185949248131643?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/5964185949248131643/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/07/python-generating-all-subsets-of-size-k.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/5964185949248131643'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/5964185949248131643'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/07/python-generating-all-subsets-of-size-k.html' title='Python: Generating all subsets of size k for n objects.'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-3414054631952155335</id><published>2011-04-20T21:01:00.000-07:00</published><updated>2011-04-20T22:58:48.966-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Electrical Engineering'/><category scheme='http://www.blogger.com/atom/ns#' term='Y and Delta impedances'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>Python in Electrical Engineering: Converting between Y and Delta impedances</title><content type='html'>Given the branch impedances in delta configuration, what is the equivalent circuit impedance if connected in a Y configuration? the folowing short Python codes ease the conversion between Y and Delta impedances.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="python"&gt;"""&lt;br /&gt;file       deltay.py&lt;br /&gt;author     Ernesto P. Adorio, Ph.D.&lt;br /&gt;           UPDEPP (U.P. at Clarkfield)&lt;br /&gt;desc       translate delta impedances to Y impedances.&lt;br /&gt;version    0.0.1    04.21.2011&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def delta2yZ(Zab ,Zbc, Zca):&lt;br /&gt;    """&lt;br /&gt;    translate delta impedances to Y impedances.&lt;br /&gt;    Arguments&lt;br /&gt;       Zab, Zbc, Zca - complex impedances of Deta connection.&lt;br /&gt;    Output&lt;br /&gt;       Za, Zb, Zc - equivalent Y connection impedances to commom point.&lt;br /&gt;    """&lt;br /&gt;    denom = Zab + Zbc + Zca&lt;br /&gt;    return (Zca * Zab/denom,Zab* Zbc/denom, Zbc * Zca/ denom)&lt;br /&gt;&lt;br /&gt;def y2deltaZ(Za, Zb, Zc):&lt;br /&gt;    """&lt;br /&gt;    translate Y impedances to delta impedances.&lt;br /&gt;    Arguments&lt;br /&gt;       Za, Zb, Zc - complex Y connected impedances &lt;br /&gt;    Output&lt;br /&gt;       Zab, Zbc, Zca - equivalent delta connection branch impedances.&lt;br /&gt;    """&lt;br /&gt;    num = Za*Zb + Zb*Zc + Zc* Za&lt;br /&gt;    return (num/ Zc, num / Za, num/Zb)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;We will continue this with an example later. &lt;br /&gt;&lt;br /&gt;Exercise: State the formulas used by the above routines y2deltaZ(), delta2yZ() routines. It is so easy to write the functions that we did not bother to write the documentation for this first version, but we will later!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-3414054631952155335?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/3414054631952155335/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/04/python-in-electrical-engineering.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/3414054631952155335'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/3414054631952155335'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/04/python-in-electrical-engineering.html' title='Python in Electrical Engineering: Converting between Y and Delta impedances'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-1726708206719207553</id><published>2011-04-20T20:18:00.000-07:00</published><updated>2012-01-15T04:45:17.982-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Electrical Engineering'/><category scheme='http://www.blogger.com/atom/ns#' term='Symmetrical Components'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>Python in Elecrical Engineering: Computing Symmetrical Components.</title><content type='html'>Given three-phase voltages V1, V2, V3 in phasor (r, phi) form, where r is the magnitude of the phasor, and phi is the phase angle. the following formulas compute the corresponding symmetrical components:&lt;br /&gt;&lt;br /&gt;Null sequence component: $$E_0 = (1/3)(V1 + V2 + V3)$$.&lt;br /&gt;&lt;br /&gt;Positive sequence component: $$E_1 = (1/3)(V1 + aV2 + a^2 V3)$$.&lt;br /&gt;&lt;br /&gt;Negative sequence component: $$E_2 = (1/3)(V1 + a^2V2 + a V3)$$.&lt;br /&gt;&lt;br /&gt;Here the &lt;b&gt;a&lt;/b&gt; is the operator which rotates the phasor by 120 degrees. Power engineers usually specify the input voltages or current in phasor form. The formula shows we have to add phasors termwise and thus the routine to compute symmetrical components first convert them to complex numbers. Complex numbers are already handled naturally in Python! and here is the full source code:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="python"&gt;"""&lt;br /&gt;file    symcomp.py&lt;br /&gt;author  Ernesto P. Adorio, Ph.D.&lt;br /&gt;UPDEPP (U.P. Clarkfield)&lt;br /&gt;desc    basic symmetrical components for three phase phasors.&lt;br /&gt;Phasors are tuples of the form (r, phi) where r and phi are the&lt;br /&gt;magnitude(absolute value) and phi is the phase angle.&lt;br /&gt;version 0.0.1 april 20, 2011&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;from math  import *&lt;br /&gt;from cmath import *&lt;br /&gt;&lt;br /&gt;zTOL = 1.0e-8&lt;br /&gt;DTOR = pi / 180.0&lt;br /&gt;RTOD = 180.0 / pi&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;ONETWENTYRAD = 120 * DTOR&lt;br /&gt;_a_  = rect(1, 120 * pi/ 180.0)&lt;br /&gt;_a2_ = _a_.conjugate()&lt;br /&gt;&lt;br /&gt;def dtor(degree):&lt;br /&gt;"""&lt;br /&gt;Converts degree to radians.&lt;br /&gt;"""&lt;br /&gt;return degree * DTOR&lt;br /&gt;&lt;br /&gt;def rtod(radian):&lt;br /&gt;"""&lt;br /&gt;Converts radians to degree.&lt;br /&gt;"""&lt;br /&gt;return radian * RTOD&lt;br /&gt;&lt;br /&gt;def  z2pair(z):&lt;br /&gt;"""&lt;br /&gt;returns z in pair form.&lt;br /&gt;""" &lt;br /&gt;return (z.real, z.imag)&lt;br /&gt;&lt;br /&gt;def  pair2z(re, im):&lt;br /&gt;"""&lt;br /&gt;returns a complex number from the components. &lt;br /&gt;"""&lt;br /&gt;return re + im*1j&lt;br /&gt;&lt;br /&gt;def  polar2pair(v):&lt;br /&gt;"""&lt;br /&gt;(r, phi) to (re, im) pair form.&lt;br /&gt;"""&lt;br /&gt;# Special checking for zero imaginaries!&lt;br /&gt;# some computations result in an additional 0j&lt;br /&gt;r, phi = v&lt;br /&gt;if type(r) == type(1j):&lt;br /&gt;r =r.real&lt;br /&gt;if type(phi) == type(1j):&lt;br /&gt;phi = phi.real&lt;br /&gt;&lt;br /&gt;z = rect(r, phi)&lt;br /&gt;return z.real, z.imag&lt;br /&gt;&lt;br /&gt;def  pair2polar(re, im):&lt;br /&gt;return polar(pair2z(re,im))&lt;br /&gt;&lt;br /&gt;def  zround(v):&lt;br /&gt;if abs(v[0]) &lt; zTOL:&lt;br /&gt;        return (0.0, 0.0)&lt;br /&gt;&lt;br /&gt;def  a(v):&lt;br /&gt;     """&lt;br /&gt;     Applies the a operator to a phasor v in polar form.&lt;br /&gt;     It adds a 120 degree to the phase of the phasor v.&lt;br /&gt;     if v is real, the angle is zero.&lt;br /&gt;     """&lt;br /&gt;     if type(v) != type((0,0)):&lt;br /&gt;        v = (v, 0)&lt;br /&gt;     r     = abs(v[0])&lt;br /&gt;     theta = v[1]&lt;br /&gt;&lt;br /&gt;     newangle = theta + ONETWENTYRAD&lt;br /&gt;     return (r * cos(newangle), r * sin(newangle))&lt;br /&gt;&lt;br /&gt;def a2(v):&lt;br /&gt;     """&lt;br /&gt;     Applies the a operator to a phasor v in polar form.&lt;br /&gt;     It adds a 120 degree to the phase of the phasor v.&lt;br /&gt;     """&lt;br /&gt;     if type(v) != type((0,0)):&lt;br /&gt;        v = (v, 0)&lt;br /&gt;     r     = abs(v[0])&lt;br /&gt;     theta = v[1]&lt;br /&gt;&lt;br /&gt;     newangle = theta + 2*ONETWENTYRAD&lt;br /&gt;     return (r * cos(newangle), r * sin(newangle))&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def  symcomp(v1, v2, v3):&lt;br /&gt;     """&lt;br /&gt;     Returns the symmetrical components of the three phasors v1, v2, v3&lt;br /&gt;     which are in tuple (r, theta) form.&lt;br /&gt;     """&lt;br /&gt;     #Convert first to complex rectangular form.&lt;br /&gt;     v1z  = rect(v1[0], v1[1])&lt;br /&gt;     v2z  = rect(v2[0], v2[1])&lt;br /&gt;     v3z  = rect(v3[0], v3[1]) &lt;br /&gt;&lt;br /&gt;     av2  = _a_ * v2z&lt;br /&gt;     a2v2 = _a2_ * v2z&lt;br /&gt;     av3  = _a_* v3z&lt;br /&gt;     a2v3 = _a2_* v3z&lt;br /&gt;&lt;br /&gt;     #Null sequence  component.&lt;br /&gt;     E0 = polar((v1z.real+ v2z.real+  v3z.real)/3.0 +  (v1z.imag+ v2z.imag+ v3z.imag)/3.0*1j)&lt;br /&gt;&lt;br /&gt;     #Positive sequence component.&lt;br /&gt;     E1 = polar((v1z.real + av2.real +  a2v3.real)/3.0+ (v1z.imag+ av2.imag+ a2v3.imag)/3.0*1j)&lt;br /&gt;&lt;br /&gt;     #Negative sequence component.&lt;br /&gt;     E2 = polar((v1z.real + a2v2.real +  av3.real)/3.0+ (v1z.imag+ a2v2.imag+ av3.imag)/3.0*1j)&lt;br /&gt;&lt;br /&gt;     return (E0, E1, E2)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def  symcompz(v1, v2, v3):&lt;br /&gt;     """&lt;br /&gt;     Returns the symmetrical components of the three phasors v1, v2, v3&lt;br /&gt;     which are in tuple (r, theta) form.&lt;br /&gt;     """&lt;br /&gt;     av2  = _a_ * v2&lt;br /&gt;     a2v2 = _a2_ * v2&lt;br /&gt;     av3  = _a_* v3&lt;br /&gt;     a2v3 = _a2_* v3&lt;br /&gt;&lt;br /&gt;     #Null sequence  component.&lt;br /&gt;     E0 = polar((v1.real+ v2.real+  v3.real)/3.0 +  (v1.imag+ v2.imag+ v3.imag)/3.0*1j)&lt;br /&gt;&lt;br /&gt;     #Positive sequence component.&lt;br /&gt;     E1 = polar((v1.real + av2.real +  a2v3.real)/3.0+ (v1.imag+ av2.imag+ a2v3.imag)/3.0*1j)&lt;br /&gt;&lt;br /&gt;     #Negative sequence component.&lt;br /&gt;     E2 = polar((v1.real + a2v2.real +  av3.real)/3.0+ (v1.imag+ a2v2.imag+ av3.imag)/3.0*1j)&lt;br /&gt;&lt;br /&gt;     return (E0, E1, E2)&lt;br /&gt;&lt;br /&gt;def  symcomp2phasors(E0, E1, E2):&lt;br /&gt;     """&lt;br /&gt;     Recreates the phasors form the symmetrical components.&lt;br /&gt;     """&lt;br /&gt;     V1 = polar(rect(E0[0], E0[1]) + rect(E1[0], E1[1]) + rect(E2[0], E2[1]))&lt;br /&gt;     V2 = polar(rect(E0[0], E0[1]) + _a2_* rect(E1[0], E1[1]) + _a_ *rect(E2[0], E2[1]))&lt;br /&gt;     V3 = polar(rect(E0[0], E0[1]) + _a_* rect(E1[0], E1[1]) + _a2_ * rect(E2[0], E2[1]))&lt;br /&gt;     return V1, V2, V3&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;if __name__ == "__main__":&lt;br /&gt;   #extreme cases.&lt;br /&gt;   I1 = polar(10)&lt;br /&gt;   I2 = polar(0)&lt;br /&gt;   I3 = polar(0)&lt;br /&gt;   print symcomp(I1, I2, I3)   &lt;br /&gt;  &lt;br /&gt;  &lt;br /&gt;&lt;br /&gt;   #extreme cases, balanced system.&lt;br /&gt;   i1 = 1&lt;br /&gt;   i2 = -0.5+sqrt(3)/2.0 * 1j&lt;br /&gt;   i3 = -0.5-sqrt(3)/2.0 * 1j&lt;br /&gt;&lt;br /&gt;   I1 = polar(i1) &lt;br /&gt;   I2 = polar(i2)&lt;br /&gt;   I3 = polar(i3)&lt;br /&gt;   E0, E1, E2 = symcomp(I1, I2, I3)   &lt;br /&gt;   print "original phasors=", I1, I2, I3&lt;br /&gt;   print "symmetrical components:", E0, E1, E2&lt;br /&gt;   phasors = symcomp2phasors(E0, E1, E2)&lt;br /&gt;   print "recovered phasors:", phasors&lt;br /&gt;   #include more here! from published books or other sources.&lt;br /&gt;&lt;/pre&gt;We have not yet fully tested the above code, and we would appreciate it if our readers point out any any errors  in the program. When the current version 0.0.1 is run, it outputs the following:&lt;small&gt;&lt;pre&gt;&lt;blockquote&gt;$ python symcomp.py&lt;br /&gt;((3.3333333333333335, 0.0), (3.3333333333333335, 0.0), (3.3333333333333335, 0.0))&lt;br /&gt;original phasors= (1.0, 0.0) (0.99999999999999989, 2.0943951023931957) (0.99999999999999989, -2.0943951023931957)&lt;br /&gt;symmetrical components: (7.4014868308343765e-17, 3.1415926535897931) (1.295260195396016e-16, 0.0) (0.99999999999999989, 0.0)&lt;br /&gt;recovered phasors: ((1.0, 9.0639078007724287e-33), (0.99999999999999978, 2.0943951023931953), (0.99999999999999978, -2.0943951023931953))&lt;br /&gt;$&lt;br /&gt;&lt;/blockquote&gt;&lt;/pre&gt;&lt;/small&gt;&lt;br /&gt;&lt;br /&gt;Note that in the second example, the null-sequnce component is the zero vector (zero magnitude). Out routines are able to recover the original phasors from the computed symmetrical componsnts.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-1726708206719207553?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/1726708206719207553/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/04/python-in-elecrical-engineering.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/1726708206719207553'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/1726708206719207553'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/04/python-in-elecrical-engineering.html' title='Python in Elecrical Engineering: Computing Symmetrical Components.'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-8455755407690565306</id><published>2011-03-22T16:34:00.001-07:00</published><updated>2011-03-22T16:34:41.164-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Javascript'/><title type='text'>Using javascript for data visualization and animations.</title><content type='html'>Visit &lt;a href="http://www.neurosoftware.ro/programming-blog/facebook-web-design/web-resources/20-fresh-javascript-data-visualization-libraries/"&gt;neurosoftware.ro&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; We are still learning how to run jsxscript in our Wordpress blog.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-8455755407690565306?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/8455755407690565306/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/03/using-javascript-for-data-visualization.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/8455755407690565306'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/8455755407690565306'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/03/using-javascript-for-data-visualization.html' title='Using javascript for data visualization and animations.'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-1602572333934952281</id><published>2011-03-04T04:42:00.000-08:00</published><updated>2011-03-20T19:13:48.812-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='comma separators in integers'/><title type='text'>Adding commas to integer strings for readability</title><content type='html'>There ase many ways to make more human readable the string representation of an integer.&lt;br /&gt;Click on &lt;a href="http://code.activestate.com/recipes/498181-add-thousands-separator-commas-to-formatted-number/"&gt;Activestate.com thousands separator &lt;/a&gt;&lt;br /&gt;&lt;br /&gt;As an example, 1234567890 looks more humanly readable as 1,234,567,890.&lt;br /&gt;&lt;br /&gt;We normally use other people's tested and understood code to save time, but this is one good programming problem.&lt;br /&gt;&lt;br /&gt;The manual way to do this is to insert commas before blocks of contiguous three digits.&lt;br /&gt;Strings are supposed to be immutable in Python by design for simplicity. Every changes to a string must be done by a copy. So we convert a string to a list just so to insert characters!&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="python"&gt;def  withcommas(s):&lt;br /&gt;     p = len(s) -3&lt;br /&gt;     s = list(s)&lt;br /&gt;     while p &gt; 0:&lt;br /&gt;        s.insert(p, ",")&lt;br /&gt;        p -= 3&lt;br /&gt;     return "".join(s)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;But suppose that s starts with a '+" or "-" sign? Then the leftmost position for a comma is at the second character or index 1. We add a conditional test so that the code will not be put off by the leading sign.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="python"&gt;def  withcommas(s):&lt;br /&gt;     p = len(s) -3&lt;br /&gt;     s = list(s)&lt;br /&gt;     if s.startswith("+") or s.startswith("-"):&lt;br /&gt;        firstpos = 1&lt;br /&gt;     while p &gt; firstpos:&lt;br /&gt;        s.insert(p, ",")&lt;br /&gt;        p -= 3&lt;br /&gt;     return "".join(s)&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;and finally we include a trivial programming problem for the reader. Instead of 3, let the caller of withcommas() specify a blocklength to the function.  We are just getting ready for the time when we will concentrate on creating mathematical tables.&lt;br /&gt;&lt;br /&gt;Our aim is to create simple, working first prototypes. The reader again is encouraged to read and search the cited reference above for faster solutions.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-1602572333934952281?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/1602572333934952281/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/03/adding-commas-to-integer-strings-for.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/1602572333934952281'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/1602572333934952281'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/03/adding-commas-to-integer-strings-for.html' title='Adding commas to integer strings for readability'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-8135506262018831393</id><published>2011-03-03T17:24:00.000-08:00</published><updated>2011-03-03T18:41:34.291-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Pickle'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>Pickled objects in Python</title><content type='html'>The inventor of Python has given a catchy name to saving objects in files as "pickled objects". &lt;br /&gt;I often use the cPickle module and one can get by using only two  powerful functions load and dump in applications. &lt;br /&gt;&lt;br /&gt;1. Save a named object to a pickle file.&lt;br /&gt;&lt;br /&gt;import cPickle&lt;br /&gt;a = "The quick brown fox"&lt;br /&gt;b = "Hello world."&lt;br /&gt;c = 123&lt;br /&gt;&lt;br /&gt;D = { "a": a, "b": b}&lt;br /&gt;&lt;br /&gt;Note that we create a dictionary containing the assigned names of the objects, and their corresponding values. An object is stored in external file and it is possible to recover their contents (seconds, minutes, hours, days, even years later)! Now here is the code for storing in the pickfile.&lt;br /&gt;&lt;br /&gt;pickfilename = "tmp.pck"&lt;br /&gt;pickfile = open(pickfilename,"w")&lt;br /&gt;&lt;br /&gt;cPickle.dump(D, pickfile)&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The cPickle.dump() function expects an object and an open file in write mode. If you dump the contents of tmp.pck you will get something like this displayed on the screen:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The idea of using a dictionary is the most natural way of saving a set of variables you are interested at to save and look for values later. Of course if you only wanted to save the variable a, you can &lt;tt&gt;do cPickle.dump(a, pickfile)&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;The name of all active local variables can be accessed by the function vars() which is a dictionary. But it also includes loaded modules which you may not want to be included!&lt;br /&gt;&lt;br /&gt;2. Load saved object in pickle file&lt;br /&gt;&lt;br /&gt;Nowt that you have created a pickfile, "tmp.pck", let us take a look at it. Dumping it on the console gives&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;(dp1&lt;br /&gt;S'a'&lt;br /&gt;S'The quick brown fox'&lt;br /&gt;p2&lt;br /&gt;sS'b'&lt;br /&gt;S'Hello world.'&lt;br /&gt;p3&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;So at least we are at ease that the values are indeed stored for later access.&lt;br /&gt;&lt;br /&gt;myvars = cPickel.load(open(pickilename,"r"))&lt;br /&gt;&lt;br /&gt;We knew that the name of the dictionary variable stored was "D". But you dont have to use D.&lt;br /&gt;Instead above, we use a new label,  myvars.&lt;br /&gt;&lt;br /&gt;Now we can recover the values of the former variables by indexing using 'a' and 'b' as keys.Thus,&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;a = myvars["a"]&lt;br /&gt;b = myvars["b"]&lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;Notes. &lt;br /&gt;&lt;br /&gt;The cPickle functions has an additional parameter calle 'protocol'. At this point in time, we refer the interested reader to the &lt;a href="http://docs.python.org/library/pickle.html"&gt;Python&lt;br /&gt;tutorial&lt;/a&gt; on the Pickle and cPickle modules.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-8135506262018831393?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/8135506262018831393/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/03/pickled-objects-in-python.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/8135506262018831393'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/8135506262018831393'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/03/pickled-objects-in-python.html' title='Pickled objects in Python'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-3174953096844321832</id><published>2011-02-26T18:44:00.000-08:00</published><updated>2011-02-26T18:44:15.614-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='word count'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>Python: a high level word count program</title><content type='html'>&lt;h3&gt;Introduction&lt;/h3&gt;&lt;br /&gt;Python allows the beginning programmer to use powerful built-in powerful  routines, freeing the programmer from imlementing on his own (usually error prone versions)! Here, we use Python A dictionarie, convenient string splitting methods to do the non-trivial word counting problem. Non-trivial in the sense it does more than printing a message "Hello World" to the screen.&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;the Python code&lt;/h3&gt;&lt;br /&gt;&lt;pre name="code" class="python"&gt;"""&lt;br /&gt;"""&lt;br /&gt;file     wordcount.py&lt;br /&gt;author   Ernesto P. Adorio&lt;br /&gt;         U.P.Clarkfield&lt;br /&gt;version  0.0.1&lt;br /&gt;desc     counts words, lines&lt;br /&gt;         lines are setoff by new line character, "\n"&lt;br /&gt;         quoted strings are stripped off of quotes.   &lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;def wc(textfilename):&lt;br /&gt;    D = {}&lt;br /&gt;    nc = 0 # number of characters.&lt;br /&gt;    nw = 0 # number of words.&lt;br /&gt;    nl = 0 # number of lines.&lt;br /&gt;    for line in open(textfilename, "r").readlines():&lt;br /&gt;        # print line #decomment for debugging.&lt;br /&gt;        nc += len(line)&lt;br /&gt;        words = line.split()&lt;br /&gt;        for word in words:&lt;br /&gt;            if word in D:&lt;br /&gt;               D[word] += 1&lt;br /&gt;            else:&lt;br /&gt;               D[word] = 1&lt;br /&gt;            nw += 1&lt;br /&gt;        nl += 1&lt;br /&gt;    return nc, nw, nl&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;if __name__ == "__main__":&lt;br /&gt;   print wc("wordcount.py")&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Notice the code's compactness. In a lower level language such as C, the code will be far longer and complicated. The essence of the code is:&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;&lt;blockquote&gt;read in all lines and store in an array.&lt;br /&gt;&lt;br /&gt;process each line.&lt;br /&gt;   add length of line to number of characters.&lt;br /&gt;   split the line into words, which are tokens separated by whitespaces. &lt;br /&gt;   add number of words in line the number of total words.&lt;br /&gt;   update the line number.&lt;br /&gt;&lt;/blockquote&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;When the program is fed the code for itself, it printed the number of c&lt;br /&gt;haracters, words and lines as &lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;$ python wordcount.py &lt;br /&gt;(762, 104, 36)&lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;As a check the wc utility produces (&lt;tt&gt; wc wordcount.py&lt;/tt&gt;) in reverse order&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt; 36 104 762 &lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;h3&gt;Issues?&lt;/h3&gt;&lt;br /&gt;There may be instances when the number of lines is off by one. This happens if the last line does not contains a terminating line feed character.&lt;br /&gt;Another thing is that the code may be feed an extremely large file. If the working memory is small, it may run out of space!  This problem is easy to fix and we will revise the above initial working code later.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-3174953096844321832?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/3174953096844321832/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/python-high-level-word-count-program.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/3174953096844321832'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/3174953096844321832'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/python-high-level-word-count-program.html' title='Python: a high level word count program'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-1470077785265841379</id><published>2011-02-22T21:21:00.000-08:00</published><updated>2011-02-22T21:32:32.247-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='C'/><category scheme='http://www.blogger.com/atom/ns#' term='Hello World'/><title type='text'>A return to C programming: Hello world example</title><content type='html'>I took up C programming at Camp Aguinaldo in the mid 80's and got a certificate for it. but I never earned a centavo for my C programming skills in my later work since the oppurtunity to program was non-existent, instead I opted to enrol in an MS Applied Math, Major in Computer Science after work. &lt;br /&gt;&lt;br /&gt;C may be considered a higher level assembly language as the power constructs in assembly are also available in C; concepts such as pointers, unrestricted gotos, and the like. In fact a C compiler worth its salt should be able to generate assembly output! &lt;br /&gt;&lt;br /&gt;For the hello world example in C, we try to write in an undiciplined manner and see if we can get away it. As usual we write a function to do the actual writing of a  message "hello world!" to be closer in spirit to the previous Javascript example. Save the following to a file "hello.c" without the quotes.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;void showMessage(char *str)&lt;br /&gt;{&lt;br /&gt;   puts(str);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;main()&lt;br /&gt;{&lt;br /&gt;    showMessage("Hello World");&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;Every C program has a main function. The difference between a function and procedure is that the former exlicitly returns a value while a procedure does not and should be declared of type void. Now lets try to run the hello.c code in the console: type &lt;br /&gt;&lt;br /&gt;&lt;tt&gt;gcc -Wall hello.c&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;Notice the -Wall flag to output any warnings encountered in processing the source file. &lt;br /&gt;Here is the output from my Ubuntu 10.04 terminal (console):&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;gcc -Wall hello.c&lt;br /&gt;hello.c: In function ‘showMessage’:&lt;br /&gt;hello.c:4: warning: implicit declaration of function ‘puts’&lt;br /&gt;hello.c: At top level:&lt;br /&gt;hello.c:8: warning: return type defaults to ‘int’&lt;br /&gt;hello.c: In function ‘main’:&lt;br /&gt;hello.c:10: warning: control reaches end of non-void function&lt;br /&gt;toto@toto-laptop:~/Blogs/my-other-life-as-programmer/C$ &lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;In good C programs, all functions must be declared and return types should be explicit. Here the compiler complains that puts was implicitly declared and that the main function did not return any value! and yet in spite of these warnings, you will find that the gcc outputte an executible file hello. To run this ececutible, issue &lt;tt&gt;./hello&lt;/tt&gt;. The program outputs &lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;toto@toto-laptop:~/Blogs/my-other-life-as-programmer/C$ ./a.out&lt;br /&gt;Hello World&lt;br /&gt;toto@toto-laptop:~/Blogs/my-other-life-as-programmer/C$ &lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;Now a good C programmer tries to remove all warnings. So lets do some modifications to be in good terms with the gcc compiler.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;#include &lt;stdio.h&gt;&lt;br /&gt;&lt;br /&gt;void showMessage(char *str)&lt;br /&gt;{&lt;br /&gt;   puts(str);&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;int main() # explicit declaration.&lt;br /&gt;{&lt;br /&gt;    showMessage("Hello World");&lt;br /&gt;    return 0;&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;We have included the standard header "stdio.h", gcc knows where to find it (in "/usr/include") and this erases the warning on puts. We also explicitly declare the main function as type int and specifically return a zero (the usual value for successful execution.) The compilation is now successful without any complaints from the compiler.&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;toto@toto-laptop:~/Blogs/my-other-life-as-programmer/C$ gcc -Wall hello.c &lt;br /&gt;toto@toto-laptop:~/Blogs/my-other-life-as-programmer/C$ &lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;So the minor corrections removed all warnings. Now lets do some extra activities  for fun.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;ol&gt;&lt;li&gt; Create assembler listing&lt;/li&gt;Type &lt;tt&gt;gcc -S hello.c&lt;/tt&gt;  this outputs hello.s   &lt;pre&gt;        .file   "hello.c"&lt;br /&gt;&lt;br /&gt;        .text&lt;br /&gt;.globl showMessage&lt;br /&gt;        .type   showMessage, @function&lt;br /&gt;showMessage:&lt;br /&gt;.LFB0:&lt;br /&gt;        .cfi_startproc&lt;br /&gt;        pushq   %rbp&lt;br /&gt;        .cfi_def_cfa_offset 16&lt;br /&gt;        movq    %rsp, %rbp&lt;br /&gt;        .cfi_offset 6, -16&lt;br /&gt;        .cfi_def_cfa_register 6&lt;br /&gt;        subq    $16, %rsp&lt;br /&gt;        movq    %rdi, -8(%rbp)&lt;br /&gt;        movq    -8(%rbp), %rax&lt;br /&gt;        movq    %rax, %rdi&lt;br /&gt;        call    puts&lt;br /&gt;        leave&lt;br /&gt;        ret&lt;br /&gt;        .cfi_endproc&lt;br /&gt;.LFE0:&lt;br /&gt;        .size   showMessage, .-showMessage&lt;br /&gt;        .section        .rodata&lt;br /&gt;.LC0:&lt;br /&gt;        .string "Hello World"&lt;br /&gt;        .text&lt;br /&gt;.globl main&lt;br /&gt;        .type   main, @function&lt;br /&gt;main:&lt;br /&gt;.LFB1:&lt;br /&gt;        .cfi_startproc&lt;br /&gt;        pushq   %rbp&lt;br /&gt;        .cfi_def_cfa_offset 16&lt;br /&gt;        movq    %rsp, %rbp&lt;br /&gt;        .cfi_offset 6, -16&lt;br /&gt;        .cfi_def_cfa_register 6&lt;br /&gt;        movl    $.LC0, %edi&lt;br /&gt;        call    showMessage&lt;br /&gt;        movl    $0, %eax&lt;br /&gt;        leave&lt;br /&gt;        ret&lt;br /&gt;        .cfi_endproc&lt;br /&gt;.LFE1:&lt;br /&gt;        .size   main, .-main&lt;br /&gt;        .ident  "GCC: (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5"&lt;br /&gt;        .section        .note.GNU-stack,"",@progbits&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;The assembler file is one reason most programmers (run away) do not like assembly language! ha ha. Unless of course if the paying job  calls for using assmbly (or assembler) langauge. ! But this feature of the gcc to ouput assembler will come in handy when we program a Forth language translator.&lt;li&gt; Seek help in using gcc&lt;/li&gt;Try &lt;tt&gt;man gcc&lt;/tt&gt;. You will get an eyeful to the useful flags. Better yet, try the free forums or buy a book specifically on the gcc.&lt;/ol&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-1470077785265841379?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/1470077785265841379/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/return-to-c-programming-hello-world.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/1470077785265841379'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/1470077785265841379'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/return-to-c-programming-hello-world.html' title='A return to C programming: Hello world example'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-884998641044456517</id><published>2011-02-21T19:49:00.000-08:00</published><updated>2011-02-22T18:20:09.644-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Javascript'/><category scheme='http://www.blogger.com/atom/ns#' term='Hello World'/><title type='text'>Hello World in Javascript</title><content type='html'>I am a python fan but I have to come to grips with javascript since I am also programming an online solver site. Javascript can be processed by any browser unless the javascript engine has been turned off by the user,perhaps due to security concerns. &lt;br /&gt;&lt;br /&gt;Here we show a simple html file with embedded javascript code to write a message "Hello World!".This example is only useful in the sense that the aspiring javascript coder will be familiar with the standard practices of writing Java script.  We will later introduce more complex and useful examples.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Now open your editor, copy manually or just cut and paste the following contents.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="javascript"&gt;&amp;lt;html&amp;gt;&lt;br /&gt;&amp;lt;head&amp;gt;&lt;br /&gt;&amp;lt;title&amp;gt; Hello World Example&amp;lt;/title&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;script language="javascript"&amp;gt; &lt;br /&gt;function showMessage(message)&lt;br /&gt;{&lt;br /&gt;   document.getElementById('location').innerHTML= message;&lt;br /&gt;}&lt;br /&gt;&amp;lt;/script&amp;gt;&lt;br /&gt;&amp;lt;/head&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;body onload="showMessage('Hello World!')"&amp;gt;&lt;br /&gt;&amp;lt;h1&amp;gt;A first Javascript&amp;lt;/h1&amp;gt;&lt;br /&gt;&lt;br /&gt;A message to one and all:&lt;br /&gt;&lt;br /&gt;&amp;lt;span id="location"&amp;gt;&amp;lt;/span&amp;gt;&lt;br /&gt;&lt;br /&gt;&amp;lt;/body&amp;gt;&lt;br /&gt;&amp;lt;/html&amp;gt;&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Lets get this to work. Fire up your browser and enter the url, (uniform resource locator), of the file&lt;br /&gt;In my case, it was &lt;tt&gt;"file:///home/toto/Blogs/my-other-life-as-programmer/javascript/hello-world.html"&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;The output window should look like this:&lt;br /&gt;&lt;div class="separator" style="clear: both; text-align: center;"&gt;&lt;a href="http://3.bp.blogspot.com/-WpwNJLIvz0s/TWNB30DmEfI/AAAAAAAAAbY/v-9d8E-qU-A/s1600/hello-world.png" imageanchor="1" style="margin-left:1em; margin-right:1em"&gt;&lt;img border="0" height="300" width="320" src="http://3.bp.blogspot.com/-WpwNJLIvz0s/TWNB30DmEfI/AAAAAAAAAbY/v-9d8E-qU-A/s320/hello-world.png" /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;Note that you do not really need Javascript just to print a message which can be read by all browsers!&lt;br /&gt;A pure html will do, but in the above code, (based on Holzer's XML bible), the use of function is illustrated. So it is a little complicated.&lt;br /&gt;&lt;br /&gt;The function is declared inside the html header  &amp;lt;head&amp;gt;  block by the xml delimiters &amp;lt;script language="javascript"&amp;gt;....  function here!.... &amp;lt;/script&amp;gt.When your browser encounters this script block, it does not right away execute it but parses the contents, translates it into a form for faster execution and saves it for recall.&lt;br /&gt;&lt;br /&gt;Notice that the body of the function will find a named div block called "location" and it will insert &lt;br /&gt;any message specifid by function's input argument. The function is triggered  when the browser loads the html page (the body block). When it encounters the inline &amp;lt;span id="location" &amp;gt; block, the function replaces this block by message "Hello World". &lt;br /&gt;&lt;br /&gt;The main behavioral difference of a span and div block is that a line break is always inserted by the div block. whereas the span is inline.&lt;br /&gt;&lt;br /&gt;For more information, consult the introductory javascript chapter in &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;Steven Holzner: "AJAX Bible", John Wiley, 2007.&lt;br /&gt;&lt;br /&gt;The book book has a fast pace introduction to Javascript, for a more relaxing pace, perhaps the following is more suitable:&lt;br /&gt;&lt;br /&gt;Tom Negrino, Dori Smith: "JavaScript for the World Wide Web", Peachpit Press,2004.&lt;br /&gt;&lt;br /&gt;I have both books, bought at Booksale. I consider them bargains at this time, costing me 350 and 200 pesos respectively&lt;br /&gt;&lt;br /&gt;.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;javascript:void(0)&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-884998641044456517?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/884998641044456517/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/hello-world-in-javascript.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/884998641044456517'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/884998641044456517'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/hello-world-in-javascript.html' title='Hello World in Javascript'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://3.bp.blogspot.com/-WpwNJLIvz0s/TWNB30DmEfI/AAAAAAAAAbY/v-9d8E-qU-A/s72-c/hello-world.png' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-3274948730554667094</id><published>2011-02-18T05:23:00.000-08:00</published><updated>2011-10-02T18:00:16.229-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Algorithm'/><category scheme='http://www.blogger.com/atom/ns#' term='Ranking'/><category scheme='http://www.blogger.com/atom/ns#' term='Python'/><title type='text'>Python: Converting a matrix of raw scores to ranks.</title><content type='html'>There are instances where we have to convert a matrix of raw scores to ranking scores, for example in Statistics where we have to compute the Kruskal-Wallis statistics of a block of values. Although we have written a Kruskal Wallis routine previously, we shall write an independent function to return ranks based on raw scores.&lt;br /&gt;&lt;br /&gt;A complication in computing ranks is that of processing ties. An approach is to replace any tied scores with the mean of all ranks. For example if 4 values v1,v2,v3,v4 have ranks 5,6,7,8, then each value should have an associated rank of (5+6+7+8)/4.&lt;br /&gt;&lt;br /&gt;Here is an outline for converting raw scores to ranks:&lt;br /&gt;1. Create a list L containing tuples of the form (v, r,c) for value, row, column for each element in the input raw scores matrix.&lt;br /&gt;2. Sort the temporaty list L in ascending order.&lt;br /&gt;3. Process the list L to fill in the output Ranks matrix,&lt;br /&gt;&lt;br /&gt;Here is our python code for outputting ranks values, complete with an example from Berensonś Basic Business Statistics,  page 493.(We do have a local copy of the book) for testing the routine.&lt;br /&gt;&lt;br /&gt;&lt;pre name="code" class="python"&gt;"""&lt;br /&gt;File    matrix_scores_to_ranks.py&lt;br /&gt;Author  Dr. Ernesto P. Adorio&lt;br /&gt;        U.P. Clarkfield&lt;br /&gt;        ernesto.adorio@gmail.com&lt;br /&gt;"""&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def matrix_scores_to_ranks(M, break_ties = 1, start_rank = 1, ZTOL = 1.0e-5):&lt;br /&gt;    """&lt;br /&gt;    Args&lt;br /&gt;       M          - a list of lists of values.&lt;br /&gt;       break_ties - 1 if ties need special processing, otherwise zero&lt;br /&gt;       start_rank - 0 or 1&lt;br /&gt;       ZTOL       - equality comparison of two real numbers.&lt;br /&gt;    Return value&lt;br /&gt;       A list of lists of ranks of the values. &lt;br /&gt;    """&lt;br /&gt;    R=[]&lt;br /&gt;    L=[]&lt;br /&gt;    for i, row in enumerate(M):&lt;br /&gt;        R.append([0] * len(row))&lt;br /&gt;        for j, v in enumerate(row):&lt;br /&gt;    L.append((v, i, j))&lt;br /&gt;    L.sort()&lt;br /&gt;&lt;br /&gt;    if break_ties != 1:&lt;br /&gt;       for k, tup in enumerate(L):&lt;br /&gt;          v, i, j = tup&lt;br /&gt;   if break_ties != 1:   &lt;br /&gt;     R[i][j] = k + start_rank&lt;br /&gt;    else:&lt;br /&gt;        prevv = L[0][0]    &lt;br /&gt;        starti = 0 &lt;br /&gt;        endi   = 0 &lt;br /&gt;        for k, tup in enumerate(L):&lt;br /&gt;            v, i, j = tup&lt;br /&gt;            if abs(v- prevv) &lt; ZTOL: # a tie?&lt;br /&gt;               endi = k&lt;br /&gt;            else:&lt;br /&gt;               # print previous tied scores!&lt;br /&gt;               rank = sum(range(starti, endi+1))/(endi-starti + 1.0) + start_rank&lt;br /&gt;&lt;br /&gt;               for i in range(starti, endi+1):&lt;br /&gt;                   ii = L[i][1]&lt;br /&gt;                   jj = L[i][2]&lt;br /&gt;                   R[ii][jj] = rank&lt;br /&gt;               prevv = v&lt;br /&gt;               starti = endi = k   &lt;br /&gt;        # Final processing of any remaining ties.&lt;br /&gt;        rank = sum(range(starti, endi+1))/(endi-starti + 1.0) + start_rank&lt;br /&gt;        for i in range(starti, endi+1):&lt;br /&gt;            ii = L[i][1]&lt;br /&gt;            jj = L[i][2]&lt;br /&gt;            R[ii][jj] = rank&lt;br /&gt;    return R&lt;br /&gt;&lt;br /&gt;#Berenson p. 493.&lt;br /&gt;&lt;br /&gt;if __name__ == "__main__":&lt;br /&gt;  M = [[ 18.5, 24.0, 17.2, 19.9, 18.0],&lt;br /&gt;     [ 26.3, 25.3, 24.0, 21.2, 24.5],&lt;br /&gt;     [20.6,  25.2, 20.8, 24.7, 22.9],&lt;br /&gt;     [25.4,  19.9, 22.6, 17.5, 20.4]]&lt;br /&gt;&lt;br /&gt;  R = scores_to_ranks(M, break_ties = 1, start_rank = 1)&lt;br /&gt;&lt;br /&gt;  for row in R:&lt;br /&gt;     print row&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/pre&gt;When the above program runs, it outputs and matches with the results in the textbook.&lt;blockquote&gt;[4.0, 13.5, 1.0, 5.5, 3.0][20.0, 18.0, 13.5, 10.0, 15.0][8.0, 17.0, 9.0, 16.0, 12.0][19.0, 5.5, 11.0, 2.0, 7.0]&lt;/blockquote&gt;The above is for a matrix. We will post array_scores_to_ranks() with the next article posting.Of course, the output must be transposed to read properly. start_rank may be set to any starting value, usually a 1, but there may be occasion when a starting zero  rank may be appropriate.The above code is written for clarity. We may speed it up later, but there is no incentive to do so. We think most of the running time is spent on the sort, and Python sort routine is already fast enough!Feb. 18, 2011: I need to install the Syntax Highlighter addin immediately! Done. I refer a blogger user to &lt;a href="http://codingfreak.blogspot.com/2009/02/blogger-adding-syntax-highlighter-to.html"&gt;Coding Freak&lt;/a&gt;There are other strategies in breaking ties. See &lt;a href="http://dr-adorio-adventures.blogspot.com/2011/10/there-are-some-nonparametric.html"&gt;Python, statistics: Ranking a single array of raw scores&lt;/a&gt; and we will update the above code someday.&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-3274948730554667094?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/3274948730554667094/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/python-converting-raw-scores-to-ranks.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/3274948730554667094'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/3274948730554667094'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/python-converting-raw-scores-to-ranks.html' title='Python: Converting a matrix of raw scores to ranks.'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-711623327910829642</id><published>2011-02-12T18:42:00.000-08:00</published><updated>2012-01-15T01:55:38.483-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ld'/><category scheme='http://www.blogger.com/atom/ns#' term='hello'/><category scheme='http://www.blogger.com/atom/ns#' term='Assembler'/><title type='text'>Hello World in assembler (Ubuntu 64 bit)</title><content type='html'>We copy the following code, dated sep. 17, 2007,  from an old  &lt;a href="http://www.daniweb.com/forums/thread89518.html"&gt;daniweb discussion about using nasm&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;pre class="brush:asm"&gt;global _start&lt;br /&gt;&lt;br /&gt;section .data&lt;br /&gt; hello db "Hello, World!", 10&lt;br /&gt; length equ $-hello&lt;br /&gt;&lt;br /&gt;section .text&lt;br /&gt;&lt;br /&gt;_start:&lt;br /&gt; mov eax, 4  ; write to file&lt;br /&gt; mov ebx, 1  ; STDOUT handle&lt;br /&gt; mov ecx, hello ; our message&lt;br /&gt; mov edx, length ; size of message&lt;br /&gt; int 80h   ; execute the syscall&lt;br /&gt;&lt;br /&gt; xor ebx, ebx  ; send 0 as 'exit code'&lt;br /&gt; mov eax, 1  ; terminate process&lt;br /&gt; int 80h   ; execute the syscall&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;br /&gt;The only familiarity I had with assembler was way way back in 1992 when I was taking up my MS Applied Math, Major in Computer Science. We learned and have already forgotten how to do it directly in assembly, but we were also smart to use the ability of the Turbo C compiler to output  assembler(!),  using flag --S. Those were the days of mental exhiliration of seing what you typed is transformed into binary code and run as a tiny program.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;section .data&lt;br /&gt; hello db "Hello, World!", 10&lt;br /&gt; length equ $-hello&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;Here we allocate a sequence of bytes, with a label hello to hold the string Hello World! followed by a line feed.(Carriage Return is coded as 13). Next we store the length as the byte difference of the current address and the starting address of the string.&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;mov eax, 4  ; write to file&lt;br /&gt; mov ebx, 1  ; STDOUT handle&lt;br /&gt; mov ecx, hello ; our message&lt;br /&gt; mov edx, length ; size of message&lt;br /&gt; int 80h   ; execute the syscall&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The code above is just an assembler  sequence of making system calls to the OS. EAX, EBX, ECX and EDX are extended registers of the CPU. The 4 stored in EAX means to write to a file, and the 1 in EBX indicates that it is the stdout device (the console screen). In Ubuntu/Linux, all input ouput devices are abstracted as files! The code &lt;tt&gt;int 80h&lt;/tt&gt; is an interrupt system call. The routine for handling the 80h service will find the parameters stored the used registers.&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;pre&gt;xor ebx, ebx  ; send 0 as 'exit code'&lt;br /&gt; mov eax, 1  ; terminate process&lt;br /&gt; int 80h   ; execute the syscall&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;The last three assembler lines makes a clean exit to the console or whatever caller.&lt;br /&gt;&lt;br /&gt;Now let us "compile" the human readable to a more machine readable object code. We call the nasm assembler with the incantation&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;nasm -f elf hello.asm&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;The output is hello.o.  If you are curious, we can use hexdump to view the hello.o file&lt;br /&gt;&lt;br /&gt;&lt;small&gt;&lt;tt&gt;&lt;br /&gt;hexdump -C hello.o&lt;br /&gt;00000000  7f 45 4c 46 01 01 01 00  00 00 00 00 00 00 00 00  |.ELF............|&lt;br /&gt;00000010  01 00 03 00 01 00 00 00  00 00 00 00 00 00 00 00  |................|&lt;br /&gt;00000020  40 00 00 00 00 00 00 00  34 00 00 00 00 00 28 00  |@.......4.....(.|&lt;br /&gt;00000030  07 00 03 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|&lt;br /&gt;00000040  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|&lt;br /&gt;*&lt;br /&gt;00000060  00 00 00 00 00 00 00 00  01 00 00 00 01 00 00 00  |................|&lt;br /&gt;00000070  03 00 00 00 00 00 00 00  60 01 00 00 0e 00 00 00  |........`.......|&lt;br /&gt;00000080  00 00 00 00 00 00 00 00  04 00 00 00 00 00 00 00  |................|&lt;br /&gt;00000090  07 00 00 00 01 00 00 00  06 00 00 00 00 00 00 00  |................|&lt;br /&gt;000000a0  70 01 00 00 1f 00 00 00  00 00 00 00 00 00 00 00  |p...............|&lt;br /&gt;000000b0  10 00 00 00 00 00 00 00  0d 00 00 00 03 00 00 00  |................|&lt;br /&gt;000000c0  00 00 00 00 00 00 00 00  90 01 00 00 31 00 00 00  |............1...|&lt;br /&gt;000000d0  00 00 00 00 00 00 00 00  01 00 00 00 00 00 00 00  |................|&lt;br /&gt;000000e0  17 00 00 00 02 00 00 00  00 00 00 00 00 00 00 00  |................|&lt;br /&gt;000000f0  d0 01 00 00 70 00 00 00  05 00 00 00 06 00 00 00  |....p...........|&lt;br /&gt;00000100  04 00 00 00 10 00 00 00  1f 00 00 00 03 00 00 00  |................|&lt;br /&gt;00000110  00 00 00 00 00 00 00 00  40 02 00 00 1f 00 00 00  |........@.......|&lt;br /&gt;00000120  00 00 00 00 00 00 00 00  01 00 00 00 00 00 00 00  |................|&lt;br /&gt;00000130  27 00 00 00 09 00 00 00  00 00 00 00 00 00 00 00  |'...............|&lt;br /&gt;00000140  60 02 00 00 08 00 00 00  04 00 00 00 02 00 00 00  |`...............|&lt;br /&gt;00000150  04 00 00 00 08 00 00 00  00 00 00 00 00 00 00 00  |................|&lt;br /&gt;00000160  48 65 6c 6c 6f 2c 20 57  6f 72 6c 64 21 0a 00 00  |Hello, World!...|&lt;br /&gt;00000170  b8 04 00 00 00 bb 01 00  00 00 b9 00 00 00 00 ba  |................|&lt;br /&gt;00000180  0e 00 00 00 cd 80 31 db  b8 01 00 00 00 cd 80 00  |......1.........|&lt;br /&gt;00000190  00 2e 64 61 74 61 00 2e  74 65 78 74 00 2e 73 68  |..data..text..sh|&lt;br /&gt;000001a0  73 74 72 74 61 62 00 2e  73 79 6d 74 61 62 00 2e  |strtab..symtab..|&lt;br /&gt;000001b0  73 74 72 74 61 62 00 2e  72 65 6c 2e 74 65 78 74  |strtab..rel.text|&lt;br /&gt;000001c0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|&lt;br /&gt;*&lt;br /&gt;000001e0  01 00 00 00 00 00 00 00  00 00 00 00 04 00 f1 ff  |................|&lt;br /&gt;000001f0  00 00 00 00 00 00 00 00  00 00 00 00 03 00 01 00  |................|&lt;br /&gt;00000200  00 00 00 00 00 00 00 00  00 00 00 00 03 00 02 00  |................|&lt;br /&gt;00000210  0b 00 00 00 00 00 00 00  00 00 00 00 00 00 01 00  |................|&lt;br /&gt;00000220  11 00 00 00 0e 00 00 00  00 00 00 00 00 00 f1 ff  |................|&lt;br /&gt;00000230  18 00 00 00 00 00 00 00  00 00 00 00 10 00 02 00  |................|&lt;br /&gt;00000240  00 68 65 6c 6c 6f 2e 61  73 6d 00 68 65 6c 6c 6f  |.hello.asm.hello|&lt;br /&gt;00000250  00 6c 65 6e 67 74 68 00  5f 73 74 61 72 74 00 00  |.length._start..|&lt;br /&gt;00000260  0b 00 00 00 01 02 00 00  00 00 00 00 00 00 00 00  |................|&lt;br /&gt;00000270&lt;br /&gt;&lt;/tt&gt;&lt;/small&gt;&lt;br /&gt;&lt;br /&gt;The hello.o file, at 624 bytes  is actually larger than the original 366 bytes asm file.&lt;br /&gt;&lt;br /&gt;But hello.o is not executible! To make it one, we have to invoke the ld (or linker loader)&lt;br /&gt;as follows: &lt;tt&gt; ld -o hello   hello.o&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;This creates the hello ELF excutible  hello. But unfortunately, what we get instead is the error&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;$ ld -o hello hello.o&lt;br /&gt;ld: i386 architecture of input file `hello.o' is incompatible with i386:x86-64 output&lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;Of course, the linker loader which was installed by Ubuntu was for out 64 bit AMD Turion powered laptop and it  complained that our hello.asm was actually compiled for a 32 bit system!&lt;br /&gt;&lt;br /&gt;Just one of those complications in software development. :(&lt;br /&gt;&lt;br /&gt;The available output formats, obtained by typing nasm -hf for object files are shown below.&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;&lt;br /&gt;valid output formats for -f are (`*' denotes default):&lt;br /&gt;* bin       flat-form binary files (e.g. DOS .COM, .SYS)&lt;br /&gt;ith       Intel hex&lt;br /&gt;srec      Motorola S-records&lt;br /&gt;aout      Linux a.out object files&lt;br /&gt;aoutb     NetBSD/FreeBSD a.out object files&lt;br /&gt;coff      COFF (i386) object files (e.g. DJGPP for DOS)&lt;br /&gt;elf32     ELF32 (i386) object files (e.g. Linux)&lt;br /&gt;elf       ELF (short name for ELF32) &lt;br /&gt;elf64     ELF64 (x86_64) object files (e.g. Linux)&lt;br /&gt;as86      Linux as86 (bin86 version 0.3) object files&lt;br /&gt;obj       MS-DOS 16-bit/32-bit OMF object files&lt;br /&gt;win32     Microsoft Win32 (i386) object files&lt;br /&gt;win64     Microsoft Win64 (x86-64) object files&lt;br /&gt;rdf       Relocatable Dynamic Object File Format v2.0&lt;br /&gt;ieee      IEEE-695 (LADsoft variant) object file format&lt;br /&gt;macho32   NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (i386) object files&lt;br /&gt;macho     MACHO (short name for MACHO32)&lt;br /&gt;macho64   NeXTstep/OpenStep/Rhapsody/Darwin/MacOS X (x86_64) object files&lt;br /&gt;dbg       Trace of all info passed to output stage&lt;br /&gt;$ &lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;We will return to this after a short rest.&lt;br /&gt;&lt;br /&gt;We have returned!&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;nasm -f elf64 hello.asm&lt;/tt&gt;&lt;br /&gt;This command results in a larger 864 bytes object file. Now the linker-loader does not complain anymore and it outputs a green colored executible file hello at 943 bytes!&lt;br /&gt;If you are interested in making the output file smaller, try the strip command. This results in a smaller 504 bytes file.&lt;br /&gt;&lt;br /&gt;Typing &lt;tt&gt; ./hello &lt;/tt&gt; in the terminal resulted in&lt;br /&gt;&lt;br /&gt;&lt;tt&gt;$ ./hello&lt;br /&gt;Hello, World!&lt;br /&gt;&lt;/tt&gt;&lt;br /&gt;&lt;br /&gt;More details for the ELF format: &lt;a href="http://www.linuxjournal.com/article/1060"&gt;The ELF Object File Format by Dissection&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;Use synaptic to install nasm and other compiler for other languages or &lt;br /&gt;&lt;tt&gt;sudo apt-get install  nasm.&lt;/tt&gt;&lt;br /&gt;The era of downloading source codes and making configuration files has been eased out a bit by the  package managers, but you can do it if you need to.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-711623327910829642?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/711623327910829642/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/hello-world-in-assembler-ubuntu-64-bit.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/711623327910829642'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/711623327910829642'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/hello-world-in-assembler-ubuntu-64-bit.html' title='Hello World in assembler (Ubuntu 64 bit)'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-7279440494329912256.post-6002901643274562990</id><published>2011-02-11T00:20:00.000-08:00</published><updated>2011-02-11T00:26:36.326-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Welcome'/><title type='text'>Welcome to my new programming blog</title><content type='html'>I learned Cobol and C at the National Computer Center in Camp Aguinaldo, but let me tell you, that you can learn programming on your own, only it may take you longer. A former colleague who was into Physics learned Java on his own and now occupies a top position at a banking institution.&lt;br /&gt;&lt;br /&gt;I programmed for my MS thesis and PhD dissertation during my graduate days, both times on Crystallographic patterns. I have taught an introductory C programming  course for BS Mathematics students. &lt;br /&gt;&lt;br /&gt;I know a smattering of languages but my current favorite is Python. Am familiar with Forth,Cobol,  C++/C, Pascal and Fortran. If necessary, I can program in Perl, Lisp and other inscrutable languages.&lt;br /&gt;&lt;br /&gt;Programming involves an inquisitive, ordered and trained mind. Hard to believe but programing is applied Mathematics! Though janitors in India are supposed to know Java Enterprise programming, let us be productive in the days ahead in this blog. The blog will be a repository of ideas and daily experience in computer programming for the PC and other devices and for the web.&lt;br /&gt;&lt;br /&gt;And we may go into independent software development when the time arises.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/7279440494329912256-6002901643274562990?l=my-other-life-as-programmer.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://my-other-life-as-programmer.blogspot.com/feeds/6002901643274562990/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/welcome-to-my-new-programming-blog.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/6002901643274562990'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/7279440494329912256/posts/default/6002901643274562990'/><link rel='alternate' type='text/html' href='http://my-other-life-as-programmer.blogspot.com/2011/02/welcome-to-my-new-programming-blog.html' title='Welcome to my new programming blog'/><author><name>ernie</name><uri>http://www.blogger.com/profile/15904737296922954023</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='24' src='http://2.bp.blogspot.com/_UuDt8fZYCTg/Szl2aakZtVI/AAAAAAAAADk/TZ3bi7g3BHw/S220/myphoto.jpg'/></author><thr:total>0</thr:total></entry></feed>
