Subscribe to Penguin-man the computer guy

Monday, May 13, 2013

Understanding the Logic of Looping Structures

One of the subjects that gets taught very early in computer programming is the idea of a Logical loop. Unfortunately, it seems that some people find it difficult to see that looping structures are a very important part of understanding the universe, and in this post, we will try to examine the how and why of looping structures in order to see if we can understand them not just as a method of controlling logic flow in a coded program, but as a way of understanding language, behaviors, neurological processes, etc. I hate to be grandiose and pretend that this is an all important concept, but this in fact is a quite profound idea.

Our first question will be a simple one: What is a logic loop? I think that showing this by some kind of pseudo code is the easiest way to begin. Don't worry if you find this a difficult idea at first... we will attempt to break it down.

while (some_condition = true )
{
     // some action is done.
}

This code snippet (which uses C/C++ syntax) shows that the condition in the parenthesis governs if, and how many times, the statements inside the brackets are done. Before executing the code inside the brackets the very first time, a while loop checks that the condition is true. If the condition is true, then the code between the brackets is executed. When the last statement of code between the brackets is executed, the condition is checked again. If the statement is true, the code continues to be executed starting once again with the first line of code between the brackets. If the condition is not true, the loop is exited. To continue this thought, lets look at two loops where we specify the conditions of the code. Once again, this snippet of pseudo code will uses C/C++ like syntax, however it will not compile. We are using pseudo code for logical clarity, not  real code. We are also not going to specify a data type for our variables, and will be using line numbers so we can follow the ideas in more clarity.

1       x = 5;
2
3       while( x > 0 )
4       {
5           print "Hello John";
6           x = x -1;
7       }

8   
9       // next line of code

Here in this example we first create a variable, 'x', in line 1, and then set it equal to five. We then use the  variable 'x' as the condition of the loop. Remember the syntax for the while statement:

1      while (some_condition = true )

In our example above, the third line is while( x > 0 ). We see that the condition ( x > 0 ) must equal true. If x <= 0, the condition is not true. But, because x = 5 and 5 > 0, then the condition evaluates to true. The loop executes until the condition is false. To see how to control amount of times the loop executes, consider how the below code will work:

1       while( 1 = 1 )
2       {
3           print "Hello John";
4       }

5   
6       // next line of code

I think the above is obvious... 1 will always equal one no matter what so this is an INFINITE loop... it will loop as a long as the program is running. Remember that an infinite loop could also take this form:

1       x = 5;
2
3       while( x > 0 )
4       {
5           print "Hello John";
6       }
7       

8       // next line of code

Do you notice what is missing that would control this statement? The expression to increment the variable 'x'. This expression is found on line 6 of the original code and is ( x = x - 1; ). Here we see that for every loop, the variable x becomes one less than its initial value. (Note, the syntax of C++ allows a shorthand version of the statement  x = x - 1 to be written x = x--;. The name C++ comes because the x = x-- is the decremented form and x = x++; is the increment form).

The website http://www.cplusplus.com/ has some great resources in there tutorials describing control structures in depth. I recommend the following page if you want to better understand the specific syntax for loops in C/C++ http://www.cplusplus.com/doc/tutorial/control/. There are three kinds of loops; while loops, the do-while loop, and the for-loop. Similar control structures are if statements, if-else statements, and switch statements. Below is the basic syntax we showed before for a while loop:

1       x = 5;
2
3       while( x > 0 )
4       {
5           print "Hello John";
6           x = x - 1;
7       }

8       // next line of code

This is the basic syntax for a do-while loop:

1       x = 5;
2
3       do
4       {
5           print "Hello John";
6           x = x - 1;  
7       

8        }while( x > 0 );
9       
10      // next line of code

And finally, is the basic syntax for a for loop:

1       for(  x = 5;  x > 0;  x = x - 1)
2       {
3           print "Hello John";
4       }

5       // next line of code

Notice how the for-loop takes all the statements that control the loop and places them in the same line. While this is more complex to learn, it is ultimately less lines of code and more elegant.

What do we use Loops for?

Why do we need loops? What are they used for? Well, when we program, we are emulating reality, and that is where the value of loops is found. Lets take my favorite example that can be expressed either as code or in a sentence. In a sentence "while I pull Sally's hair, Sally will scream." Below the same in code form.


1       while( I pull Sally's hair )
2       {
3           Sally screams;
4       }


This is similar to the statement "while the car has gas and the engine is turned on, the cars engine will run. Here again, there is a condition ("while the car has gas and the engine is turned on") and a result ("the cars engine will run"). Note though that the condition has an and... this makes a more interesting loop structure. Note that && is the computer code way of expression a logical and.


1       while( ( car has gas ) && (the engine is turned on) )
2       {
3           The engine will keep running;
4       }



Here we see that we have two statements separated by an and. Remember the truth table for an and statement of two variables which we will call p and q in respect to convention:

       p   &   q    Truth value

       T         T            T
       T         F            F
       F         T            F
       F         F            F

This table shows us why a logical and is so special. Only in one case, both premises are true, is the statement true. Thus, when a while statement contains an a logical AND, the statement is quite narrowly defined. Less narrowly defined is the or statement:


       p   OR   q    Truth value

       T           T            T
       T           F            T
       F           T            T
       F           F            F

In a logical or, the statement is true unless both premises are false. That means the difference between an or statement verses an and statement is huge.

Conclusion

In conclusion, we need to look at the ways in which we may encounter loops. In reality we see loops all the time. Consider the following:

"While it is cold, I wear a jacket."

In the above, identify that the action, "I wear a jacket", will be terminated when the condition, "while it is cold", is negated. In logic, a ~ is the symbol used to show negation. So,

 ~(action) --> ~(condition)  which could also be written   NOT(action) --> NOT(condition)               

This means that we can expect that if I am not wearing a jacket, then the weather is NOT cold. This is a simple, but valuable insight. Also note that the use of a while here is appropriate, as I repeatedly don my jacket as long as the weather is cold.

Ultimately, anytime we see a process frequently occurs in reality, then we can expect to see it equally frequently in code. In fact, when coding, anytime a task needs repetition until some condition is either met, or not met, the logic of that task is a loop. This makes understanding loops of primary importance to both programmers and philosophers.

Friday, May 10, 2013

Linux Commands

For several years I have been using Ubuntu Linux and overall have become a real enthusiast. I'm sure some old hats might call me a newbie still, and it is true that I still am learning a lot. In some ways, I feel like it takes 2-3 years to get comfortable enough with Linux to start really enjoying it. Anyways, the other day I started taking notes on the normal, and especially the not so normal tasks I do on the terminal. You know there are some things that I just don't do that often... and when I need to do them, I start to wonder, "How did I do that last time? I know it was easy but I can't remember how to do it!!!"

Well, the solution is to write down the commands, so that I would remember them. This is a kind of self documentation of sorts, and I first started doing this maybe a year ago. I more recently started trying to teach someone Linux, and they needed some basics written down. So I've put several of these together and here it is. Feel free to critique, copy, and edit. This is a work in progress that is made to be saved as a .sh in order to be able to see the markup.

-Cal


# Misc Linux Commands
#
# OS:            Using Ubuntu 12.10 Desktop Version
# Author:      Calvin R. Johnson
# Date:          Last update 5-19-2013
# Credits:      Numerous Internet Sources


# Basic Commands

       # To update run:
       sudo apt-get update
       sudo apt-get upgrade

       # Or run this which does both...
       sudo apt-get update && sudo apt-get upgrade

       # Navigate Through Your Filesystem and Directories

               # To change directories run cd
               cd <'path to file'>
               #example is:
               cd /media/flashdrive/anime

               # To change directories to home, run cd ~

                                cd ~

               # To change directories to root, run cd /

                                cd /

               # To change directories back one directory (towards root) run ..

                                $..

                # To List directories run ls:
                        ls
                        syntax = ls (options)
                                ls -l

                # To clear Terminal

                        clear

                # To close Terminal

                        exit

       #To copy files use cp or rsync

       # To use cp (copy)
       cp /media/flashdrive/anime/picture1.jpg /home/heather/pictures/picture1.jpg

       # Or use rsync to copy o whole directory (folder)
       #syntax is:
       rsync [options] <'source'> <'destination'>
       #example
       rsync -avi /media/flashdrive/anime/ /home/heather/pictures/
       #the above copies directory anime from flashdrive to pictures

       # To install software
       # Using apt-get
       sudo apt-get install <'package'>

                        # Before installing many packages, one must add the source or ppa
                        # You will find the ppa listed in the instructions for installing the package
                                sudo apt-add-repository ppa:<package>
                                # Example of adding ppa
                                sudo add-apt-repository ppa:webupd8team/gnome3
                                # Then update
                                sudo apt-get update
                                # Now install
       sudo apt-get install <'package'>
                        # NOTE
                                #When you add a PPA, a new .list file is created under /etc/apt/sources.list.d/.
                                # The files are named based on the PPA name and your Ubuntu version, like this: "someppa-ppa-oneiric.list".
                               
                                # To edit these PPAs, run:
                                        sudo gedit /etc/apt/sources.list.d/*
                        # To remove a ppa
                               sudo add-apt-repository --remove ppa:someppa/ppa
                        # PPA purge
                                sudo apt-get install ppa-purge
                                sudo ppa-purge ppa:someppa/ppa

                # To Find a file
             
                        find file_name

                # Using Wildcards to help find a file

                                find partial_file_name* # or
                                find *partial_file_name

                        # You can also use the wildcard to list file types

                                find *.mp3 # or any other file extension


#************************************************************************************************
# Linux Networking Commands

        # Look up Information:

                sudo ifconfig
                # in windows, >ipconfig

        # To Release and Renew IP Address:

                sudo dhclient

        # To Restart the Networking Service:
        # Always Restart the Networking Service After Changing Network Configurations

                sudo /etc/init.d/networking restart # also (start, stop)

        # Network Config file
        # To Edit the Network Adapter Configurations

                sudo gedit /etc/network/interfaces

        #To Edit the DNS Resolution File

                sudo gedit /etc/resolv.conf

        #To See Current Hostname

                sudo /bin/hostname

        # Hostname
                #To Echo Hostname

                        sudo /bin/hostname newhostname

                #To Change Hostname

                        sudo /bin/hostname newhostname

        # Ping -- To Determine if You Can See an IP Address

                ping <IP Address>

        # To Determine DNS is Working

                ping <domainname>

        # UFW firewall

                # To Change Default Handling of Ports When UFW is Enabled:

                        sudo ufw default allow/deny

                # To Turn UFW on or Off:

                        sudo ufw enable/disable

                # To Open or Close Ports for Everyone:
             
                        sudo ufw allow/deny port#

                # To Delete a UFW Rule:

                        sudo ufw delete allow/deny port#

                # To Allow Access to All Ports from a Specific IP Address:

                        sudo ufw allow from IP Address

                # To Allow Access to a Specific Port from a Specific IP Address:

                        sudo ufw allow from IP Address to any port port#

        # SSH and FTP
                # SSH -- Secure Shell

                        #Install SSH on Server:

                                sudo apt-get install ssh
                                # SSH Requires Port 22
                                # Use a Terminal Emulator to Connect to the Server (PuTTy)

                        # To check the UFW Firewall
     
                                sudo ufw status

                #FTP -- File Transfer Protocol
                        # Install FTP Server

                                sudo apt-get install vsftpd

                        # Edit vsftpd Configuration Files

                                sudo gedit /etc/vsftpd.conf

                                        #Uncoment
                                                #local_enable=YES to Allow Local Users to Login
                                        #Uncomment
                                                #write_enable=YES to Allow File Uploads

                        # To Restart vsftpd Service:
                                sudo service vsftpd restart

                        # Use an FTP Client to Connect to FTP Server (FileZilla)


#*************************************************************************************#
# Some software installation instructions for Ubuntu 12.10 customisations script
        #Terminal Applications

         # SSH
          sudo apt-get install openssh-server


         # g++ & gcc

          sudo apt-get install build-essential

         # gcc for objective C
         sudo apt-get install gobjc


         # Valgrind
         sudo apt-get install valgrind

         # Python

          sudo add-apt-repository ppa:fkrull/deadsnakes
          sudo apt-get update
          sudo apt-get install python2.6 python2.6-dev


         # Ruby

          sudo apt-get install git build-essential

         # Java
         # sudo add-apt-repository ppa:webupd8team/java
         # sudo apt-get install oracle-java7-install
         # sudo apt-get update
         # sudo apt-get remove oracle-java7-installer

         # R

          gpg --keyserver keyserver.ubuntu.com --recv-key E084DAB9
          gpg -a --export E084DAB9 | sudo apt-key add -
          gksudo gedit /etc/apt/sources.list
          # add this line to the bottom of sources.list
          # deb http://cran.ma.imperial.ac.uk/bin/linux/ubuntu precise/
          sudo apt-get update
          sudo apt-get install r-base

        #GUI Apps
         # gedit

          sudo apt-get install gedit
          sudo apt-get check gedit


          sudo apt-get install gedit-plugins

         # Gmate-gedit (for Ruby on rails developers)
         sudo apt-add-repository ppa:ubuntu-on-rails/ppa
         sudo apt-get update
         sudo apt-get install gedit-gmate


         # SciTE

          sudo apt-get install scite
          sudo apt-get check scite

         # Openoffice/libreoffice

          sudo apt-get install libreoffice
          sudo apt-get check libreoffice

         # startup disk creator

          sudo apt-get install usb-creator-gtk
          sudo apt-get check usb-creator-gtk

         # transmition bit torrent

          sudo add-apt-repository ppa:transmissionbt/ppa
          sudo apt-get update
          sudo apt-get install transmission-gtk
          sudo apt-get check transmission-gtk

         # firefox

          sudo apt-get install firefox

         #  Chrome

         # wget https://dl.google.com/linux/direct/google-chrome-stable_current_i386.deb  #32bit version

          wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
          sudo dpkg -i google-chrome*
          sudo apt-get -f install

         # Chromium
  
          sudo apt-get install chromium-browser

         # VLC
       
          sudo apt-get install vlc

         # XBMC
                        sudo add-apt-repository ppa:team-xbmc
                        sudo apt-get update
          sudo apt-get install xbmc

         # Texmacs

          sudo apt-get install texmacs

         # Audacious Music Player

          sudo apt-get install audacious

                #       OpenShot Video Editor
                        sudo add-apt-repository ppa:jonoomph/openshot-edge
                        sudo apt-get update
                        sudo apt-get install openshot openshot-doc

        # Utilities

                # compizconfig-settings-manager
                        sudo apt-get install compizconfig-settings-manager

                # Gparted disk editor
                        sudo apt-get install gparted

                # PPA purge
                        sudo apt-get install ppa-purge
                        #sudo ppa-purge ppa:someppa/ppa

                # Ubuntu Tweak
                        sudo add-apt-repository ppa:tualatrix/ppa
                        sudo apt-get update
                        sudo apt-get install ubuntu-tweak

                # Play encripted DVDs
                        sudo apt-get install libdvdcss2 && sudo /usr/share/doc/libdvdread4/./install-css.sh

                # Extra (Non-Free Codecs)
                        sudo apt-get install non-free-codecs libxine1-ffmpeg gxine mencoder totem-mozilla
                                icedax tagtool easytag id3tool lame   nautilus-script-audio-convert libmad0 mpg321 mpg123libjpeg-prog