HCL Interview

March 28, 2017 at 11:16 am | Posted in Patterns, Programming | Leave a comment

Earlier I wrote about my interview experience with NetCloud Systems Bangalore. Recently I appeared for an interview with HCL Technologies. (HCL Technologies is on the Forbes Global 2000 list.[13] It is among the top 20 largest publicly traded companies in India with a market capitalisation of $22.1 billion as of May 2015.[14] As of August 2015, the company, along with its subsidiaries, had a consolidated revenue of $6.0 billion.[5]  — Source: Wikipedia )

Interviewer was quite younger than me. He asked me to write a program using a singly linked list where he wants to remove Nth element counting from last node you added. e.g if you added 10 elements in the list then 7th element from end is 4th element you added in beginning, hence 4th should be removed. If 1,2,3,4,5,6,7,8,9,10 are the elements you added then “./a.out 7” should remove 4 not 7.

I told him I can use singly list as stack where elements are always added in reverse order. From his looks I could make out he could not understand what I just said. So I asked him if can I use any method,he replied that I should use pointers and gave  a paper and pen to write. This is the full-fledged code with all the checks and added command-line input and string conversion etc. but algorithm/logic/data is exactly same I wrote there and he said this code will not remove 7th from end but 5th from end.   This is wrong code. I was shocked to hear that. Loot at it yourself and see the output:

/* HCL Interview Question (2017)
 *
 * A singly-linked-list (SLL) program to add nodes to SLL and remove Nth node
 * from the end
 *
 * e.g Add 10 nodes to a SLL & remove the 7th node starting from the end
 * 7th node from end is 4th node you added while building SLL
 *
 * I am using a Stack (LIFO). Last node (the end) is always the latest. So, we can
 * go down from there easily. The interviewer said it will not work.
 * Worked fine for me 🙂
 *
 ***/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include 				<limits.h>

struct node {
  long nn;
  struct node* next;
};

struct StPtr {
  struct node* head;
  long tn; /* totoal number of nodes */
};

struct StPtr* st;

void print_diagnostics(void);
void printStack(void);
void convert_to_long(long*, long*, const char*, const char*);
void addNodes(long, long);
void removeNode(long, long);

int main(int argc, char* argv[]) {
  if(3 != argc) {
    print_diagnostics();
    return EXIT_FAILURE;
  }

  st = malloc(sizeof*st);
  if(NULL == st) {
    printf("Out of Memory\n");
    return EXIT_FAILURE;
  }

  st->head = NULL;
st->tn = 0;
  long t = 0, r = 0;
  convert_to_long(&t, &r, argv[1], argv[2]);
  addNodes(t,r);
  printStack();
  removeNode(t, r);
  printStack();  

  return EXIT_SUCCESS;
}

void removeNode(long num, long rem) {
  if((0 >= num) || (0 >= rem) || (rem > num)){
    printf("Nothing to remove\n");
  }
  else {
    struct node* t = st->head;
    struct node* prev = st->head;
    long i = (t->nn - rem) + 1;
    /* IF we ar eremoving the head */
    if(i == st->head->nn) {
      st->head = st->head->next;
      st->tn--;
      printf("Removing node#: %ld \n", i);
      free(t);
    }
    else {
      while(i != t->nn) {
	prev = t;
	t = t->next;
      }
      prev->next = t->next;
      printf("Removing node#: %ld \n", i);
      st->tn--;
      free(t);
    }
  }
}

void addNodes(long num, long rem) {
  if((0 >= num) || (0 >= rem) || (rem > num)){
    printf("Nothing to add\n");
  }
  else {
    for(long i = 1; num >= i; ++i) {

      struct node* p = malloc(1 * (sizeof *p));
      if(NULL == p) {
	printf("Out of memory, will not add node\n");
      }
      else if(NULL == st->head) {
	printf("Adding 1st node\n");
	p->nn = i;
	p->next = NULL;
	st->head = p;
	st->tn++;
      }
      else {
	p->nn = i;
	p->next = st->head;
	st->head = p;
	st->tn++;
      }

    }
  }
}

void convert_to_long(long* num, long* rem, const char* numptr, const char* remptr) {
  errno = 0;  /* To distinguish success/failure after call */
  char* endptr;
  long temp = strtol(numptr, &endptr, 0);
  if( ((0 == temp) && (0 == strcmp(numptr, endptr)) && (errno == ERANGE))
      || ((LONG_MAX == temp) && (ERANGE == errno)) ) {
    *num = 0;
    *rem = 0;
  }
  else {
    *num = temp;
    temp = strtol(remptr, NULL, 0);
    if( ((0 == temp) || (LONG_MAX == temp)) && (ERANGE == errno) ) {
    *num = 0;
    *rem = 0;
    }
    else { *rem = temp; }
  }
}

void print_diagnostics(void) {
  printf("Invalid Number of Args\n");
  printf("Provide 2 arguments:\n");
  printf("\t1st arg is number of nodes\n\t2nd arg is nuber of node to be removed\n");
}

void printStack(){
  struct node* t = st->head;
  for(t = st->head; t; t = t->next) {
    printf("%ld, ", t->nn);
  }
  printf("\n\t---> Total %ld nodes\n", st->tn);
  printf("\n======================================\n\n\n");
}

OUTPUT:
[arnuld@arch64 programs]$ gcc -std=c99 -pedantic -Wall -Wextra ll.c
[arnuld@arch64 programs]$ ./a.out 10 7
Adding 1st node
10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
—> Total 10 nodes

======================================

Removing node#: 4
10, 9, 8, 7, 6, 5, 3, 2, 1,
—> Total 9 nodes

======================================

[arnuld@arch64 programs]$ ./a.out 10 5
Adding 1st node
10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
—> Total 10 nodes

======================================

Removing node#: 6
10, 9, 8, 7, 5, 4, 3, 2, 1,
—> Total 9 nodes

======================================

[arnuld@arch64 programs]$ ./a.out 10 1
Adding 1st node
10, 9, 8, 7, 6, 5, 4, 3, 2, 1,
—> Total 10 nodes

======================================

Removing node#: 10
9, 8, 7, 6, 5, 4, 3, 2, 1,
—> Total 9 nodes

======================================

[arnuld@arch64 programs]$ ./a.out 1 10
Nothing to add

—> Total 0 nodes

======================================

Nothing to remove

—> Total 0 nodes

======================================

[arnuld@arch64 programs]$

I don’t understand how could he say this code will not remove the Nth node from end , code behaves fine. May be he never wrote a Stack in his life. I did another mistake by trying to explain him that Stack is an implementation of a linked list and he shrugged it off. He asked me to write it using some other method (he meant another algorithm) but explain to him first and I did and he said same words again that this new method will not work either. Then I told him, there are several ways you can approach the problem that is why so many algorithms (methods 😉 ) exist and is there any specific method he is thinking of ?   He told me that he is done with me and I can leave for the day  🙂

After coming out I saw on the doors in capital letters, “ODC” was written. That means Offshore Development Center. Most of the ODCs in Indian companies are service based, there is not much development/coding involved. Companies in India, get freshers in a mass based campaigns from colleges and put them on work because they are dirt cheap to get when it comes to economy. These freshers have never worked before and most of engineering colleges here have non-ISO conforming compilers and code in their CS textbooks too does not conform to any ISO/ANSI standard. They have learned C and C++ using such resources, so it is expected that they wont know what is the definition of C language and how do ISO conforming compilers and non-forming compilers behave and what it costs in terms of bugs and maintenance.

Now lets get back to HCL, the company. What did they lose ?  I am just one programmer and what about others. There were 100 people for interview and I am sure at least 10 of them must be very good programmers. Will they get hired ?  I have been to interviews where I had to choose one answer out of 4 options given to me for   “int i = 0; prinf(“%d\n”, i++ + ++i)” and none of the options said “UB”. You were forced to choose an integer as an answer. What did I do ? I wrote “option5: UB” just below tho option 4 and of course I was not hired 🙂 . Can you imagine the quality of code in such a company, quality of hires ?   and what a nightmare it will be to fix bugs and add new features ?  HCL did not do much different from them in my interview. Whom to blame ?  Their hiring process which lets a person with low knowledge of Data-Structures interview a person with medium level of knowledge of Data-Structures. Who created such process. I know I am not that intelligent  because I have never written an AVL Tree and I can’t understand more than half of Maths Knuth writes in his Art of Computer Programming books. I just try to improve everyday and like to read definition of language, reference manuals and man pages and do what they advise. And I am still working on Knuth. In book Programming Interviews Exposed authors wrote that the more you stay away from coding and move towards business side, the more money you make and more secure your career will be (I did not know at that time that google’s machine learning department is working on making coding obsolete).  You make more money if you move from being programmer to business analyst and to software architect (A glassdoor search will tell you that it is really true). Now, how does a person who loves to program, who loves  to write code day and night, who loves to learn more languages, algorithms, more UNIX, Linux, DragonFlyBSD, NetBSD and more UNIX way of solving problems, data-structures, gcc libraries and learn more about programming paradigms,  loves Lisp and the idea behind its macros, loves to read why Eiffel was created and what problems it solves and why and how does it do it and wants to inculcate these as a part of his thinking, plus the shell he works in, and then mastering his text-editor etc. All that  just for the interest and liking. What that person can do to show his skill and get to work with MNC ? Not much if company is not even interested in having a skilled person and improving their software, tools and methodologies.  I think that challenge comes down to the programmer himself. Few companies want to improve, most don’t and you go and find those few companies.

Copyright © 2017 Arnuld Uttre, Hyderabd, Telangana – 500017 (INDIA)
Licensed Under Attribution-NoDerivs 3.0 United States (CC BY-ND 3.0 US)

Emacs way – copying text

December 9, 2014 at 12:47 pm | Posted in Patterns, Programming | Leave a comment
Tags: , , , ,

In Emcas if you want to copy a region of text from one file to another then you can just press {C-space} as beginning of copying and then take your cursor to the point till where you want to copy. Then you press {M-w}, M means meta/Alt key and then you will go to the file you want to paste to and put your cursor at the place and press {C-y} and its done. It may look complicated to people who have used Notepad/Wordpad/MS-Office for many years who can just use mouse to copy-paste. Well, it is same except that using keyboard gets much easier over time, plus it kinds of wires into your nervous system. Using mouse to do something never gets easier over time, it remains same.

Now behind the scene, Emacs uses a function called (append-to-buffer) and if you look at the pseudo-code or algorithm, this is how it looks like:

(let (bind-oldbuf-to-value-of-current-buffer)
   (save-excursion                           ; Keep track of buffer.
     change-buffer
     insert-substring-from-oldbuf-into-buffer)
   change-back-to-original-buffer-when-finished
let-the-local-meaning-of-oldbuf-disappear-when-finished

Compare this with how it works in C:

  1. open file for reading, the file you want to copy from
  2. if there was no error in step 1 then open file for writing, where you want to paste
  3.   if there was no error in step 2 then check if mark has lower value than point
  4. use fseek to go to the mark
  5. if there was no error in step 4 then read/copy one character and write/paste it
  6. check if copy/paste stopped because of end of work or because some error occurred in copying.
  7. check if copy/paste stopped because of end of work or because some error occurred in pasting.

Here is the code in both languages:

(defun append-to-buffer (buffer start end)
  "Append to specified buffer the text of the region.
     It is inserted into that buffer before its point.

     When calling from a program, give three arguments:
     BUFFER (or buffer name), START and END.
     START and END specify the portion of the current buffer to be copied."
  (interactive
   (list (read-buffer "Append to buffer: " (other-buffer
					    (current-buffer) t))
	 (region-beginning) (region-end)))
  (let ((oldbuf (current-buffer)))
    (save-excursion
      (let* ((append-to (get-buffer-create buffer))
	     (windows (get-buffer-window-list append-to t t))
	     point)
	(set-buffer append-to)
	(setq point (point))
	(barf-if-buffer-read-only)
	(insert-buffer-substring oldbuf start end)
	(dolist (window windows)
	  (when (= (window-point window) point)
	    (set-window-point window (point))))))))
int copy_buffer_richard(const char *w, const char *r, int pf, int pt)
{
  int rc = 0;
  FILE *fpi = fopen(r, "rb");
  if(fpi != NULL)
    {
      FILE *fpo = fopen(w, "wb");
      if(fpo != NULL)
	{
	  int len = pt - pf;
	  if(pt > 0 && pf >= 0 && len > 0)
	    {
	      /* Everything so far has been housekeeping.
		 The core of the code starts here... */

	      if(0 == fseek(fpi, len, SEEK_SET))
		{
		  int ch;

		  while((ch = getc(fpi)) != EOF)
		    {
		      putc(ch, fpo);
		    }

		  /* ...and ends here. From now on, it's
		     just a load more housekeeping. */

		  if(ferror(fpi))
		    {
		      rc = -5; /* input error */
		    }
		  else if(ferror(fpo))
		    {
		      rc = -6; /* output error */
		    }
		}
	      else {
		rc = -4; /* probably the in file is too short */
	      }
	    }
	  else {
	    rc = -3; /* invalid parameters */
	  }
	  fclose(fpo);
	}
      else {
	rc = -2; /* can't open output file */
      }
      fclose(fpi);
    }
  else {
    rc = -1; /* can't open input file */
  }
  return rc;
}
/* by Richard Heathfield */

Comparing both, to me Emacs Lisp code is much more easier to understand than C code. C code may look prettier but that is because of lot of extra whitespace around it where Emacs Lisp code in tightly placed. You should look at the pseudo-code of Emacs Lisp on how easier it make connection between pseudo-code and real code. It reads almost like English while C version is, as usual, strikingly odd, pseudo-code and real code look a lot different, typical of C. You may say that comparison is unfair because C is much faster comparing to Emacs Lisp and one file in Emacs Lisp was already opened and I am comparing a full fledged Lisp environment with just one single C program. Yeah, I get that, but then again Emacs Lisp code is real code directly taken from source code of Emacs while C code is just written a stand alone, small and short program. Real C program taken from a real life working software will be a lot creepy. In one glance at pseudo-code and real code, you can guess what Emacs Lisp code is doing and it is easier on head whereas real life C code will require lots of glances and will definitely be far from easier on head.

Emacs Lisp version is much more readable and this is a very important point. Ever heard of the sentence called “developer’s time is more important than the machine time” or “a computer program is written once and read 10,000 times” or “Programs must be written for people to read, and only incidentally for machines to execute (Abelson and Sussman, Preface to the First Edition, SICP) . Last quote is from one of the most respected books in computer science. If you think those ideas are quite academic or theoretical then you are completely missing the point. Good ideas are not only hard to grasp at first but it is difficult to notice the practical benefit of those too, especially if you are not having few years experience in programming. No matter how much industry is crying about changing customer requirements, good ideas are timeless. These changing customer requirements are nothing but problems that computer programmers solve everday. If, at your workplace,  you work mostly in C and C++, you must have noticed almost every company has moved to C++ while two decades back they used to develop mostly in C. More than 65% of the code in this entire world is still in C, but most of it is legacy-code.  There is a shift in the thinking that has happened. The programming world keeps on churning out new languages and almost everyone is moving towards the use of languages like C++, Java, Python, Ruby etc. Why is that ?  If you look at the new languages, you will notice they were designed more on the side of how to solve the problems in a better way, how can this new language work as a better and improved tool towards solving the problems in or of this world, and indirectly (and may be unknowingly) these language-creators have no interest solving the problems of the machine itself (space and time complexity) because problems of the machine and problems of this world are two points that lie on opposite ends. You can not brilliantly solve the one without ignoring the other by a good  amount. C++ was created to solve the problems of large scale software design and hence OO and generic programming paradigms were added. Rather than how to make it more efficient than C, the notion of how to make it better at solving larger problems was choosen. Ruby, Perl, Python and lot of others were created primarily to solve the problems that are not related to machine’s own problems. World is moving from machine towards abstraction. I call it moving to solving problems of this world, moving towards generlization and abstraction, Paul Graham calls it moving from C model to Lisp Model and he is right. Humans always evolve, no matter how many wars and world wars have been fought where humans swore to kill each other, no matter how much negativity and selfishness is there in this world, humans have always evolved and this shift from solving problems of machine to solving problems of this world is a step in further human evolution. Richard Stallman had already evolved to this level by 1984 (along with many other great progrmmers. Good thinking is timeless). He focused more on solving the problem and created this amazing piece of software called Emacs. Thanks to him again.

You should try this book by Robert J. Chassell, it is kind of addictive. When I get some free time it makes me think whether I should entertain myself with a movie or should I just enjoy reading his book  🙂

Copyright © 2014 Arnuld Uttre, Hyderabad, Telangana – 500017 (INDIA)
Licensed Under Creative Commons Attribution-NoDerivs 3.0 license (a.k.a. CC BY-ND)

How much math you need for programming

December 5, 2014 at 10:47 am | Posted in art, Hacking, Patterns, Programming | Leave a comment
Tags: , , , , , , , , ,

Whenever I wanted to learn Algorithms, Mathematics used there somehow seemed to be an obstacle. I admit my Math is not that good but it ain’t that bad either but this “ain’t bad” level of knowledge was not enough to learn Algorithms and the time and space complexities involved and comparisons of sorting and searching techniques which are at the heart of measuring performance of computer programs. I needed to learn all these and in that search I came across several articles written on Mathematics required for programming. I will explain what did I learn from these articles. When it comes to programming, most loudly known math-proponent is Steve Yegge. Here is what I have found on Math required for programming:

  1. Steve Summit notes on Math (author of brilliantly written C-FAQs)
  2. Steve Yegge who has written two articles Math Everyday and Math for Programmers
  3. Eric S. Raymond talks about how much math you need to become a Hacker
  4. Paul Graham on Math
  5. Evan Miller’s article as reply to 3 authors above
  6. Steven Noble wrote an article as reply to Evan Miller’s example of calculating fibonacci numbers

If you do not read all of those above then you will miss the intent of my blog post. As per Steve Summit, Eric Raymond and Paul Graham, you do not need to focus much on Math to become a brilliant programmer, a hacker, the most decorated word for a programmer (I do not mean Crackers who break into computers and steal private data. Read Wikipedia definition and Eric Raymond’s article on definition of a hacker). Steven Noble says you should learn a little bit of Math and Evan Miller somehow seems to agree with all of them but in a bitter way. I myself started programming just for the love of it. Since 2009, professionally, I am progrmming mostly in C, sometimes in C++ and almost always on Linux and sometimes on UNIX. My passion for programming has made me read and write code in many different languages where I had to learn different ways of thinking. Writing code is easy, thinking along the lines of the paradigm on the top of which a particular language was modeled is a tough, daunting and very time consuming task. I have always tried to do my best and got good amount of experience doing that. I think I am qualified enough to write smo comments about those articles mentioned above. So, let me tell you one thing very clearly: Computer Prgrommaing is not Math. Let me say it again, computer programming is not Math and will never be. You want to learn computer programming, then learn computer prgramming. Do not flip through Math books, read whatever is written on a particular newsgroup (comp.lang.c, comp.lang.lisp for example), read about all the software that came from GNU and use Linux distro exclusively for everday tasks (I prefer a distro with least amount of binary blob). If you are learning lot of Math because you want to learn computer programming then you are confused and headed in the wrong direction and you will not learn much of programming. Except in the speialized fields like 3D game programming etc., you only need Math as much mentioned by Steve Summit.

As computer programmers, we write programs, but why ? We write programs to solve problems of this world. That is what computer programmers do, they solve problems.

Now what does does a mathematician do ? He tries to understand nature and uses mathematics as a language to do that. Mathematics has helped solved many problems of this world. Look at what Quantum Physics, a branch of physics that has literally changed our millenia old assumptions about atoms, is heavily dependent on Math. Math is everwhere, from chemical industry to societal problems we use Statistics. Take any part of your daily life and you will see how deeply it is influenced my Math. Math has been used as the most prominent vehicle not only to understand nature but also to solve problems of this world. There is a reason for this, all these properties are just inherent in Math. I was not good at Math, so I was trying to solve the problems I was facing everday as a programmer using my intuition, common-sense, flow-charts and more other kinds of diagrams. This went on for few years and I came up with some rules and ideas on which I was building a model to solve problems, the problems that I faced everday as a computer programmer. Building up this model had one aim: to be extremely clear and very brief on what the problem is and same for solution. I was creating a model, to which you will feed a problem as input and it will produce a solution as output using English language, flow charts and lot of other kinds of diagrams I created. This model had certain assumptions, rules and conditions, which again were very clear. Clarity and simplicity were high on agenda. It was a kind of a general, abstract mechanism to be applied to problems to get solutions. Now a few months back, after I read all these Math articles I came across one more article from Evan Miller titled Don’t Kill Math which was actually written in response to Kill Math by Bret Victor.

These two article hit me very hard. First, Bret was trying to do the same thing I was trying from few years, though he was more successful than me in producing something. I could never come up with some solid model which could have been used by everyone and here is Bret who has already done that. Was I happy, yes, because I found what I was looking for and I was ready to follow Bret’s footsteps but I never did. Why ?

There was a reason I could never come up up with a solid model. I always thought it lacked something. No matter what I did and how much I worked on it, I always felt that something very fundamental and basic is lacking. My model lacked a soul, a life can not exist without a soul. Whenver I read Theory of Relativity, whenever I studied Schrodinger equation, Maxwell’s equation, Newton’s laws, Kepler’s laws, The Uncertainty Principle or Shulba-Sutras, I always felt that all those equations are complete, that they have a soul but my model does not. Both of these articles Kill Math and Dont’ Kill Math made me realize what is that soul. It is the properties of Mathematics mentioned in Don’t Kill Math. The questions Evan asked in this article and the way he has explained in very simple and basic details, concluded my search for a model. Math is a terse, short and succinct and the curtest method to solve problems and understand a phenomenon. These brutal characteristics are inherent to Math, just like soul is inherent to every being. With Math you can solve problems in a much shorter and better way than not using it. Try it yourself, read both of Kill Math and Don’t Kill Math and try to solve some problems using both methods.

This brings me to a very basic question: Why did I hate math ? If I truly do not like math then I must not like it now too, but instead it is opposite now, I like math. It was the way math was taught to me in school and college. I was taught rote-math, not real math. Same is true for hundreds of thousands of children who pass out of Indian schools. It is not their fault that they can not comprehend and hence hate Math. It is very common statement from Indian parents that “my kid does not know math, my kid hates math”. It is the fault of school, fault of our education system, not of the student.

Coming back to the primary question of whether we need Math for becoming a great programmer, this is how tho world solved its problems in beginning:

math-1

Then came Math and this is what most mathematicians did:

math-2

I have worked in software industry for more than 5 years now and this what almost all computer-programmers/software-engineers/developers do:

math-3

Evan Miller says you can become first rate hacker without using a lot of Math and I think he is right and that is in agreement with all other authors. The point he stressed was role of Math in solving problems of this world, that Math is brutally efficient in solving real world problems. As programmers, we solve problems, but if we solve problems using Math and then apply programming solutions to the mathematical model of the solution, then we can have some amazing ways of providing better solutions that will make our lives easier as a programmer (kind of side-effect):

math-4

I conclude this blogpost with these points:

  • You do not need math to become a first-rate programmer because we do not use much of Math directly. If you want to become programmer then learn programming. Computer programming is very different from mathematics, and as a computer programmer you have to focus more on how to write better programs, how to think in a particular paradigm (e.g functional, OO, Generic, Procedural, logical, declarative etc), find better ways to create software, you need to understand design-patterns, not to mention learning and using C for few years will add new dimension to your thinking. All these are not related to math in anyway. These tools we use to solve problems of this world and they are in no way related to Math e.g look at the different paradigms on which different languages are created, you need to learn these first and it will take you few years before you get a grip at them and then you can learn Math if you want. Read Introduction to Progrmming using Emacs Lisp by Roberrt J. Chassell to know how the problem of creating a customizable, self-documenting, ever-extensible real-time display text-editor was solved. Read GNU Make Manual and find out why does it need M4 and Autoconf.
  • Math is the most widely used vehicle to understand the nature and solve problems of this world. We can learn more ways of solving problems by learning mathematical methods. I myself have started studying probability because like Steve Yegge said, once you understand Math then you can look at the problem and see whether it a probability problem, calculus problem or statistical problem etc. Math is related to the nature of the problem, not nature of software, software has its own methods and tools of solving problems, keep that in mind.

I want beginning programmers to go on right path. Learning Math when what you actually want to write computer programs is a wrong, wrong path to walk on. Install a Linux distro, I prefer Trisquel for latest softwares and gNewSense if you want a solid and stable distro but with little bit outdated collection of softwares. Install Emacs using package manager on command-line and start reading Introduction to Programming using Emacs Lisp and you will get true taste of computer programming. This image shows you the world of computer programming

math-5

Copyright © 2014 Arnuld Uttre, Hyderabad, Telangana – 500017 (INDIA)
Licensed Under Creative Commons Attribution-NoDerivs 3.0 license (a.k.a. CC BY-ND)

The Emacs Way of understanding Humans and Computers

November 30, 2014 at 10:28 pm | Posted in Patterns | 1 Comment
Tags: , , , ,

I was using gNewSense frow sometime now and one thing about softwares endorsed or created by FSF is that you get to know some amazing ideas or some incredible ways of solving some problems that you never came across before and you yourself never knew those either. For example, take icecat, it comes default with libreJS add-on installed. Generally we think an OS can control your machine and then you. After using libreJS I see how you can use javascript in a web-browser to control the user, without giving any hint at all. User will use his computer for 10 years and for those 10 years he will not have slightest of the idea that he is being controlled. Then I came across duckduckgo search engine and then ThinkPenguin router  with 100% Freedom and then h-node  and now gNewSense.

When I used Emacs first time, in year 2006, after few weeks of usage I came across The GNU Project (open Emacs and press “Control-h g”), that one keystroke (C-h g) changed my life. I got hooked onto Linux forever (or GNU/Linux as RMS calls it). Since last few years, I have never used/installed any proprietary OS on my machine, my machine runs only on Linux, yes, no other OS, only and only Linux (something that majority of Software Engineering students and prfossionals in INDIA are always scared to do). Just few months back I came across gNewSense and from there I came across one gNewSense BlogPost, an introductory book on programming in Emacs Lisp written by Robert J. Chassell. For those who don’t know, Emacs is one of the most (if not the most) advanced text editors available. I am sure if you make a list of top 20 softwares ever created with best design ideas then Emacs will be one of them (and Apache web server will be there too along with several softwares starting with letter “g” 😉 ). Emacs is written using Emacs Lisp (a dialect of Lisp, an amazing language) while some parts are written in C for portability/efficiency reasons. I am using Emacs all the time for writitg code but I do admit I hardly make effective use of it. I think I use may be 10% of its power. I always wanted to learn more and the book written by Robert seemed like a decent start. I am already writing code from few years now and Robert mentioned that it is “not for experienced programmers” but I am reading it anyway because I always wated to understand Emacs and then this book is so interesing and engaging and I can not seem to put it down. It is as much interesting as The Man Who Sold The Moon . Whenever I will come across some idea that I will like then I will post about it here. So, here is the first design idea I really loved (I assume you are familiar with some dialect of Lisp. If not, then just read 17 pages of first chapter of Robert’s book. That will be more than enough. Do not worry, it will not take much time to read those)

  • You want to evaluate something written in Emacs Lisp ? Just open emacs, put cursor at the end of the variable or function name or the closing parenthesis or whatever you want to evaluate and press “C-x C-e” and you got the answer. That’s it, that is how simple it is in Emacs.
  • File and Buffer are two different entities. File is what permamently stored on your computer’s hard disk whereas a buffer is inside emacs which will go away as soon as you exit emacs. A buffer visits the file or is a pointer to the file, not the actual file. You want to save changes into the file then just save the buffer and changes will be written to the file.
  • This one is most interesting. switch-to-buffer is an Emacs Lisp function that helps you in switching to another buffer. Generally when you look at any editor (Notepad, Notepad++ or gedit etc. for example) , you usually look at the file you are editing. If you switch to another file then you will see only and only this another file and previous file will not be visible. Previous file is open but it is not visible and hidden in the editor). What I mean is you can see only one file in front of you, not two (I am not talking about splitting-frames). Within Emacs code, switch-to-buffer is less used than set-buffer. Why ? … Because computer does not need eyes to see while humans do. When a a computer program needs to work on a buffer/file, it does not need to see it, visibility is not needed. switch-to-buffer was designed for humans and it does two things:
    • It switches to the new buffer .
    • It switches the buffer “displayed” in the window with new one.

You can easily guess now that set-buffer only walks the first step, it switches the program to other buffer while buffer on the screen remains unchanged.  Doesn’t this concept feel like one of the rules of the creation of this Universe while still being so simple and straightforward. I salute RMS for creating Emacs and keeping it free


Copyright © 2014 Arnuld Uttre, Hyderabad, Telangana – 500017 (INDIA)

Licensed Under Creative Commons Attribution-NoDerivs 3.0 license (a.k.a. CC BY-ND)

Simple Lessons

May 12, 2011 at 10:33 am | Posted in Patterns | Leave a comment
Tags: , ,

I am working in C from last 3 years and these two very simple lessons are based on my experience, these are not taken from any book but by my own understanding of programming. They may look very simple and short and don’t underestimate them. You may already know them (I did) and you may not be aware of them. Its like everyone knew that apple falls on the ground but only Newton became aware of it 🙂

  • Solving Problems: Programming is all about solving problems. I knew that (and I am sure you knew that too), every programmer know this but how many programmers translate business problems into code? May be you are working on the problem which is just your interpretation of the problem? What is the real business problem you are trying to solve on your job as a programmer? You are actually a translator between a business man and computer.

  • Diagrams: Before you even think about coding you must draw a digram on how you are going to split this business problem into some or lots of small ones and what will be the general idea behind solving this problem. That you can accomplish very effectively by drawing a diagram on paper using a pen (or pencil). Also known as DFDs (Data Flow Diagrams). You will see how much of your life has become easier with DFDs. DFDs follow some rules and you can make your own diagrams and your own rules but make sure you stick to some standard (whether your own or someone else). DFDs are designed to make your life easier, it will make you happy because once you start coding you will see how important they are.

  • Tools: What tools you are using to translate problems into code ? Whether you are solving business problems or you do it for joy of solving problems (in the world of Hackers), Algorithms and Data Structures are the first of the tools you need, programming language is 2nd tool. Majority of programmers do not focus on first tool. Why you need qsort() over other sorting techniques. Why AVL tree will be better than Red-Black tree or Binary-Search tree. Why you will use a circular linked list instead of a doubly-linked list implemented as a Stack ? Why there exist so many different kind of trees and linked lists. Even I, myself, know only few of them. Its hard work but surely simple and very rewarding. I think half of the bugs exist in software because programmers lack this tool or the intended use of it

  • Tools-2: Like I said, programming language you are using is 2nd tool. Don’t go to high level talk here or dig yourself into advanced programming before you understand the basics. I use C language, so before I go into advanced C book, I will make sure I have spent two years on comprehending C FAQs and comp.lang.c archives

  • Breaking a big problem into small problems: I am using C, which is a procedural programming language. Hence I break down a business problem into small procedures (also known as functions). I will make sure that when one procedure calls other then both of them are doing some specific work and that in a proper and structured way. Writing too many procedures or the ones which do not have a proper siginificance can (and will) cause semantic bugs which in turn cause headaches over time.


Copyright © 2011 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA)

Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.

Next Page »

Create a free website or blog at WordPress.com.
Entries and comments feeds.