Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added associated markdown files.

  • Loading branch information...
commit 7d32d4ecac2ae06e1baef9cef1f6d8eca675a646 1 parent b849b89
Anthony Scopatz authored
1  0-SetUp/Readme.md
View
@@ -0,0 +1 @@
+
9 1-Shell/Readme.md
View
@@ -0,0 +1,9 @@
+# The Shell
+
+[Back To The Menu](http://github.com/thehackerwithin/UofCSCBC2012/) -
+[Forward to Python
+Variables](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/2a-PythonVariables/)
+
+* * * * *
+
+**Presented By : Milad Fatenejad**
226 2b-PythonDataStructures/Readme.md
View
@@ -0,0 +1,226 @@
+# Python 2: Lists, Dictionaries, Sets, Tuples
+
+[Back To Python
+Variables](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/2a-PythonVariables/)
+- [Forward to Python Flow
+Control](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/2c-PythonFlowControl/)
+
+* * * * *
+
+**Presented By : Tommy Guy**
+
+**Based on lecture materials by Milad Fatenejad**
+
+## Lists
+
+Most languages have some kind of simple syntax for making lists of
+things. In python it is extremely easy and intuitive to make a list of
+things, for example:
+
+```python
+> mylist = [] # Make an empty list
+> mylist = [1, 1.0+3j, "aperitivo", True] # Make a list containing four entities
+```
+
+Using lists is easy and intuitive. Notice that lists can contain objects
+of any data type. Try entering the following lines.
+
+```python
+> mylist = [1,2,3,4]
+> mylist[2] = 1.0 + 2j # Modify an element
+> mylist.append("test") # Add an element to the end of a the list
+> print len(mylist) # print the length of mylist (5)
+
+> mylist = [1,9,7,32,2.0]
+> del(mylist[2]) # Remove element 2 from the list
+
+> mylist = [1,5,4,2]; mylist.sort() # Sort the list
+```
+
+The colon, **:**, provides a syntax for ranges.
+
+```python
+> print mylist[1:4] # Prints a list containing elements 1 2 and 3 from mylist
+```
+
+Remember that there is an element 0, so this prints [4, 6, 8]
+
+```python
+> print mylist[-2] # Print the second element from the end of the list (8)
+```
+
+## Dictionaries
+
+Lists aren't the only compound data type. Another really useful one is a
+dictionary (referred to as a map in many other languages). Dictionaries
+allow you to set/access elements using a key value relationship. You can
+create dictionaries as shown below:
+
+```python
+> mydictionary = {} # Make an empty dictionary
+> mydictionary = {"one" : 1, "two" : 2, "three" : 3} # Initialize a dictionary
+> with some values
+
+> print type(mydictionary) # Tells you mydictionary is of type "dict"
+> print mydictionary["one"] # Prints the number 1
+> print mydictionary["two"] # Prints the number 2
+> mydictionary["four"] = 4 # Insert an element into the dictionary
+> mydictionary["list"] = [1,2,3] # Sets the element "list" to a list containing
+> the numbers 1, 2, and 3
+```
+
+### Example: Creating and Sorting Lists
+
+Accomplish the following tasks using Python. Each task should take only
+one line. You may need to use the help and dir functions to figure out
+parts you don't know:
+
+1. Create a string and initialize it to "Tommy Katy Stefano Antun
+ Graziano""
+
+\2. Split the string into a list whose elements are the names Tommy,
+Katy, Stefano, Antun, Graziano. 3. Sort and print the list 4. Without
+deleting anyone, add your own name to the list **so that it comes
+first.**
+
+### Example: Manipulating Compound Data
+
+Accomplish the following tasks using Python. Each task should take only
+one line. You may need to use the help and dir functions to figure out
+parts you don't know:
+
+1. Create a dictionary containing the key, value pairs:
+ - "Red", 5
+ - "Green", 3
+ - "Purple", 3
+ - "Orange", 1
+ - "Blue", 3
+
+ \* "Teal", 3
+
+\2. Extract a list of values from the dictionary (i.e. get a list
+containing [3,3,3,3,1,5] from the dictionary, don't make the list on
+your own) 3. Find and use a list method to count the number of times the
+value 3 appears (Use the list you produced on step 2, the correct answer
+is that the value 3 appears four times)
+
+In a dictionary, the keys must be unique: assigning a second value to a
+key overwrites whatever was stored there. What if we want to store a
+list of unique items? There are two options using what we know about so
+far:
+
+\1. Use a list, but every time we add an element, check whether it is
+already there. 2. Use a dictionary to store the object as a key to some
+dummy value.
+
+## Sets
+
+It turns out there is a third type of container in Python that only
+stores unique things: it's called a set.
+
+```python
+> s = set()
+> s = set([1,1,2,3,4]) # Note that there are 2 1's in the input list.
+> print s
+set([1, 2, 3, 4])
+> 1 in s
+True
+> 5 in s
+False
+> s.add(5)
+> 5 in s
+True
+> anotherSet = set([1,2,"hello"])
+> s.intersection(anotherSet)
+set([1, 2])
+```
+
+### Example : Appending/Adding vs Updating
+
+There are two methods to add element(s) to a list: append and update.
+Likewise, there are two methods to add element(s) to a set: add and
+update. What is the difference?
+
+```python
+> myList = [1,2,3]
+> myAppendedList = myList.append([4,5])
+> myUpdatedList = myList.update([4,5])
+```
+
+What is the difference between the appended list and the updated list?
+Why did this happen?
+
+\1. Try the same thing with the add() and update() functions on a set.
+The key is that containers can hold other containers.
+
+## Tuples
+
+There is one other compound data type - the tuple. Think of a tuple as a
+list that you can't change. The example below demonstrates how to create
+and use tuples:
+
+```python
+> mytuple = (1,2,3,4) # Create a four element tuple
+> mytuple[2] = 4 # ERROR - tuples can't be modified
+> print mytuple[2], len(mytuple)
+
+> myonetuple = ("hello",) # Create a tuple containing only one element (note the trailing comma)
+```
+
+You might be asking yourself, why do we need tuples if we have lists?
+The answer is that tuples are used internally in Python in a lot of
+places. One of the basic differences is that dictionaries cannot use a
+list as a key, but they can use a tuple:
+
+```python
+> d = {}
+> d[(1,2)] = 'numbers'
+> d
+{(1, 2): 'numbers'}
+> d[ [1,2] ] = 'listOnumbers'
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ TypeError: unhashable type: 'list'
+```
+
+As you learn more about python you'll see how lists, tuples and
+dictionaries are the basic building blocks of the entire language.
+
+## Copy or Reference?
+
+Simple data types like integers and strings behave slightly differently
+than more complicated objects. To see one unexpected example, try these
+commands:
+
+```python
+> list1 = [1, 5, 9, 13]
+> list2 = list1
+> list2[0] = -1
+> print list1, list2
+```
+
+What happens? You'll notice that modifying list2 also modifies list1!
+This is because line 2 does not copy list1, instead list2 is set to
+*reference* the same data as list1. After line 2 is executed, list1 and
+list2 refer to the same data. Modifying one list also modifies the
+other. This was not the case when we were dealing with simple numbers.
+This behavior can be very annoying and can lead to a lot of bugs, so be
+careful. We can force python to copy list1 as shown in the example
+below:
+
+```python
+> list1 = [1, 5, 9, 13]
+> list2 = list1[:] # <--- Notice the colon!
+> list2[0] = -1
+> print list1, list2
+```
+
+Why would Python variables be references rather than copied instances?
+Let's think about a list file handles or some other complicated data
+type. In two lectures, we will talk a lot more about file handles. If
+you've ever done file I/O, you know that the file handle has a *state*:
+it stores the location of the next readable byte in the file as well as
+a lot of other information. When we copy the list, we probably want to
+maintain the same set of file handles rather than reinitialize them all.
+Python made the decision that the default should be to pass the
+reference to the list rather than create a copy of each element.
354 2c-PythonFlowControl/Readme.md
View
@@ -0,0 +1,354 @@
+Python 3 : Flow Control - Loops, Conditionals, etc.
+\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
+
+[Back To Python Data
+Structures](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/2b-PythonDataStructures)
+- [Forward To Python Functions and
+Modules](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/2d-PythonFunctionsAndModules/)
+
+* * * * *
+
+**Presented By : Katy Huff**
+
+**Based on Lecture Materials By: Milad Fatenejad**
+
+# Pasting into iPython
+
+This part of the lesson includes a lot of text, but it will be useful to
+run it yourself in iPython.
+
+To paste text from another application (i.e. these lecture notes) into
+iPython :
+
+1. select text from the wiki
+2. copy with **ctrl+c**
+3. in iPython, type **%paste**
+
+The code should paste and execute in iPython.
+
+If you also type %autocall to turn autocall OFF, you may be able to
+paste with **ctrl+v** though this won't work with all ipython builds.
+
+# Conditionals
+
+A conditional (if statement) is some statement that in general says :
+"When some boolean is true, do the following. Elsewise, do this other
+thing."
+
+Many equivalence test statements exist in Python that are similar in
+other languages:
+
+```python
+i=1
+j=2
+i==j # i is equal to j : FALSE
+i<j # i is less than j
+i<=j # i is less than or equal to j : TRUE
+i>j # i is greater than j
+i>=j # i is greater than or equal to j : FALSE
+i!=j # i is not equal to j : TRUE
+```
+
+However, python has other equivalence test statements that are fairly
+unique to python. To check whether an object is contained in a list :
+
+```python
+beatle="John"
+beatles=["George", "Ringo","John", "Paul"]
+print beatle in beatles # is John one of the beatles? : TRUE
+print "Katy" not in beatles # this is also TRUE.
+```
+
+Conditionals (if statements) are also really easy to use in python. Take
+a look at the following example:
+
+```python
+i = 4
+sign = "zero"
+if i < 0:
+ sign = "negative"
+elif i > 0:
+ sign = "positive"
+else:
+ print "Sign must be zero"
+ print "Have a nice day"
+print sign
+```
+
+The behavior of this code snippet should be pretty clear, but there is
+something peculiar. How does Python know where the if-statement ends?
+Other languages, like FORTRAN, MatLab, and C/C++ all have some way of
+delimiting blocks of code. For example, in MatLab you begin an if
+statement with the word "if" and you end it with "end if". In C/C++ you
+delimit blocks with curly braces. Python uses ''indentation'' to delimit
+code blocks. The **indentation** above is NOT just to make things look
+pretty - it tells Python what the body of the if-statement is. This is
+true when ever we create any code blocks, such as the bodies of loops,
+functions or classes.
+
+**Aside: Compact if-statement:**
+
+Python has an easy to use if-syntax for setting the value of a variable.
+Try entering this into IPython:
+
+```python
+i = 5
+sign = "positive" if i > 0 else "negative"
+```
+
+# While Loops
+
+Lets start by looking at while loops since they function like while
+loops in many other languages. The example below takes a list of
+integers and computes the product of each number in the list up to the
+-1 element.
+
+A while loop will repeat the instructions within itself until the
+conditional that defines it is no longer true.
+
+```python
+mult = 1
+sequence = [1, 5, 7, 9, 3, -1, 5, 3]
+while sequence[0] is not -1:
+ mult = mult * sequence[0]
+ del sequence[0]
+
+print mult
+```
+
+Some new syntax has been introduced in this example.
+
+- On line 3 We begin the while loop. Notice that instead of using the
+ not-equals symbol, !=, we can simply enter "is not" which is easier
+ to read. This while loop will execute until sequence[0]= -1 . That
+ is, until deletes all of the entries of the sequence that come
+ before -1.
+
+- On line 4, we compute the product of the elements just to make this
+ more interesting.
+
+- On line 5, we use the \`del\` keyword to remove the first element of
+ the list, shifting every element down one.
+
+**Watch Out**
+
+Since a while loop will continue until its conditional is no longer
+true, a **poorly formed** while loop might repeat forever. For example :
+
+```python
+i=1
+print "Well, there's egg and bacon, egg and spam, egg bacon and"
+while i is 1:
+ print "spam "
+print "or Lobster Thermidor a Crevette with a mornay sauce served in a Provencale manner with shallots..."
+```
+
+Since the variable **i** never changes within the while loop, we can
+expect that the conditional, **i=1** will remain true forever and the
+while loop will just go round and round, as if this restaurant offered
+nothing but spam. (If you try this at home, please note that one way to
+interrupt a non-terminating process is **ctrl+c** or **ctrl+z**.
+
+To create nested if loops, the indentation (preferably two or four
+spaces) should increase for each looping level.
+
+```python
+weapons=["surprise","fear","ruthless efficiency","an almost fanatical devotion..."]
+tries=0
+script=""
+while tries < len(weapons) :
+ i=0
+ while i<tries :
+ script += weapons[i]
+ script += " and "
+ i+=1
+ script += weapons[tries]
+ script += ". "
+ if tries == len(weapons) - 1 :
+ script += " and nice red uniforms. Oh damn!"
+ tries +=1
+print script
+```
+
+# For Loops
+
+For loops in python operate a little differently from other languages.
+Lets start with a simple example which prints all of the numbers from 0
+to 9:
+
+```python
+for i in range(10):
+ print i
+```
+
+You may be wondering how this works. Start by using help(range) to see
+what the range function does.
+
+ Help on built-in function range in module __builtin__:
+
+ range(...)
+ range([start,] stop[, step]) -> list of integers
+
+ Return a list containing an arithmetic progression of integers.
+ range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
+ When step is given, it specifies the increment (or decrement).
+ For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
+ These are exactly the valid indices for a list of 4 elements.
+
+Range is a function that returns a list containing a sequence of
+integers. So, range(10) returns the list [0,1,2,3,4,5,6,7,8,9]. The for
+loop then simply iterates over that list, setting i to each value.
+
+# For Loops with Lists and Dictionaries
+
+With range, we learned that **for** loops in python are really used to
+iterate over sequences of things (they can be used for much more, but
+for now this definition will do). Try entering the following to see what
+happens:
+
+```python
+for c in ["one", 2, "three", 4, "five"]:
+ print c
+```
+
+this is equivalent to:
+
+```python
+c = ["one", 2, "three", 4, "five"]
+for i in range(len(c)):
+ print c[i]
+```
+
+With a list, then, it's clear that we can use the **in** keyword to
+indicate a list of things. What about a nested loops around a list of
+lists?
+
+```python
+italy = ["Rome", "Pisa", "Florence", "Venice", "Trieste"]
+argentina = ["Mendoza", "Buenos Aires", "Patagonia"]
+india = ["Ahmedabad","Kolkata", "Chennai", "Jaipur", "Surat"]
+us = ["Chicago", "Austin", "New York", "San Fran"]
+nations = [italy, argentina, india, us]
+nationnames = ["italy","argentina", "india", "us"]
+for nation in nations :
+ print nationnames[nations.index(nation)] + ": "
+ for city in nation :
+ print " " + city
+```
+
+Of course, this information is better stored in a dictionary, isn't it?
+The data makes more sense if the keys were the nation names and the
+values were lists of cities. Importantly, python has given us a tool
+specifically for dictionary looping.
+
+The syntax for looping through the keys and values of a dictionary is :
+
+ for key, value in dictionary.iteritems():
+
+Importantly, you don't have to use the words key and value. That's just
+what will fill those variables. Here, we rewrite the previous loop using
+this clever syntax.
+
+```python
+italy = ["Rome", "Pisa", "Florence", "Venice", "Trieste"]
+argentina = ["Mendoza", "Buenos Aires", "Patagonia"]
+india = ["Ahmedabad","Kolkata", "Chennai", "Jaipur", "Surat"]
+us = ["Chicago", "Austin", "New York", "San Fran"]
+nations = {"italy":italy, "argentina":argentina, "india":india, "us":us}
+for nation, cities in nations.iteritems() :
+ print nation + " : "
+ for city in cities :
+ print " " + city
+```
+
+# break, continue, and else
+
+A break statement cuts off a loop from within an inner loop. It helps
+avoid infinite loops by cutting off loops when they're clearly going
+nowhere.
+
+```python
+reasonable = 10
+for n in range(1,2000):
+ if n == reasonable :
+ break
+ print n
+```
+
+Something you might want to do instead of breaking is to continue to the
+next iteration of a loop, giving up on the current one..
+
+```python
+reasonable = 10
+for n in range(1,2000):
+ if n == reasonable :
+ continue
+ print n
+```
+
+What is the difference between the output of these two?
+
+Importantly, Python allows you to use an else statement in a for loop.
+
+That is :
+
+```python
+knights={"Sir Belvedere":"the Wise", "Sir Lancelot":"the Brave", \
+ "Sir Galahad":"the Pure", "Sir Robin":"the Brave", "The Black Knight":"John Clease"}
+
+favorites=knights.keys()
+favorites.remove("Sir Robin")
+for name, title in knights.iteritems() :
+ string = name + ", "
+ for fav in favorites :
+ if fav == name :
+ string += title
+ break
+ else:
+ string += title + ", but not quite so brave as Sir Lancelot."
+ print string
+```
+
+# Final Example
+
+We've seen a lot so far. Lets work through a slightly lengthier example
+together. I'll use some of the concepts we already saw and introduce a
+few new concepts. To run the example, you'll need to locate a short file
+containing phone numbers. The file can be found in your PyTrieste
+repository within the phonenums directory and is called phonenums.txt.
+Now we have to move ipython to that directory so it can find the
+phonenums.txt file. You navigate within ipython in the same way that you
+navigate in the shell, by entering "cd [path]" .
+
+This example opens a text file containing a list of phone numbers. The
+phone numbers are in the format \#\#\#-\#\#\#-\#\#\#\#, one to a line.
+The example code loops through each line in the file and counts the
+number of times each area code appears. The answer is stored in a
+dictionary, where the area code is the key and the number of times it
+occurs is the value.
+
+```python
+areacodes = {} # Create an empty dictionary
+f = open("phonenums.txt") # Open the text file
+for line in f: # iterate through the text file, one line at a time (think of the file as a list of lines)
+ ac = line.split('-')[0] # Split phone number, first element is the area code
+ if not ac in areacodes: # Check if it is already in the dictionary
+ areacodes[ac] = 1 # If not, add it to the dictionary
+ else:
+ areacodes[ac] += 1 # Add one to the dictionary entry
+
+print areacodes # Print the answer
+```
+
+## Example : Iteritems
+
+Use the iteritems dictionary method in combination with a for loop to
+print the keys/values of the areacodes dictionary one to a line. In
+other words, the goal is to write a loop that prints:
+
+ 203 4
+ 800 4
+ 608 8
+ 773 3
+
+This example is a little tricky to figure out, but give it a shot.
294 2d-PythonFunctionsAndModules/Readme.md
View
@@ -0,0 +1,294 @@
+Python 4 : Functions and Standard Modules
+\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
+
+[Back To Flow
+Control](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/2c-PythonFlowControl/)
+- [Forward To Local Version
+Control](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/3a-VersionControlLocal/)
+
+* * * * *
+
+**Presented By : Tommy Guy**
+
+**Original material by Milad Fatenejad**
+
+During the last session we saw how to use some of the built-in data
+types. During this session, we are going to learn about writing
+functions and using modules.
+
+# Using modules
+
+Python has a lot of useful data type and functions built into the
+language. We've see some of these already, and we'll see more over the
+next few lectures. For a full list, you can type
+\`dir(\_[\_builtins](____________________________________________________________________))\`.
+However, most of the useful function are stored in modules. An example
+is the sine function, which is stored in the math module. In order to
+access mathematical functions, like \`sin\`, we need to ''import'' the
+math module. Lets take a look at a simple example:
+
+```python
+> print sin(3) # Error! Python doesn't know what sin is...yet
+> import math # Import the math module
+> print math.sin(3)
+> print dir(math) # See a list of everything in the math module
+> help(math) # Get help information for the math module
+```
+
+It is not very difficult to use modules - you just have to know the
+module name and import it. There are a few variations on the import
+statement that can be used to make your life easier. Lets take a look at
+an example:
+
+```python
+> from math import * # import everything from math into the global namespace (A BAD IDEA IN GENERAL)
+> print sin(3) # notice that we don't need to type math.sin anymore
+> print tan(3) # the tangent function was also in math, so we can use that too
+```
+
+```python
+> reset # Clear everything from IPython
+> from math import sin # Import just sin from the math module. This is a good idea.
+> print sin(3) # We can use sin because we just imported it
+> print tan(3) # Error: We only imported sin - not tan
+```
+
+```python
+> reset # Clear everything
+> import math as m # Same as import math, except we are renaming the module m
+> print m.sin(3) # This is really handy if you have module names that are long
+```
+
+# A running example
+
+The goal of this lecture is to use Python to read a series of strings
+from the command line, convert them into numbers, and list whether they
+are prime. A single run of this program will look like this:
+
+ (unix shell)$ python findPrimes.py 2 4 3 9 7
+ 2 is prime
+ 4 is not prime
+ 3 is prime
+ 9 is not prime
+ 7 is prime
+
+We'll split this problem into a few pieces: 1) Process the command line
+arguments using the sys module. 2) Write a function to determine whether
+a number is prime. 3) Combine the two and test it.
+
+# Writing Python Scripts
+
+Python scripts are simply files ending in ".py" that contain python
+instructions. You can write them using any text editor such as emacs,
+vi, nano, notepad, etc... If you don't have a text editor you like to
+use to write computer programs then you are in luck because it turns out
+that all of you installed a decent and easy to use python editor called
+IDLE. So far, we have been feeding commands directly to the python
+interpreter, ipython. This starts to become very tedious once we want to
+write longer programs. So from now on we are going to write python
+scripts instead using IDLE. You can run the scripts you wrote using the
+"%run" command in ipython.
+
+To open IDLE in Windows, simply use the run box in the start menu and
+enter "idle". Similarly on Mac OSX enter "idle" into spotlight, or enter
+"idle" into a terminal if you are on Linux. Once idle is open, click on
+File -\> New Window to start a new python script. For the rest of this
+session I will assume that you are saving the scripts to the Desktop.
+Enter the command: print "Hello World!" into the new script then save it
+to the Desktop with the name "hello.py". Now, we have to move ipython to
+the Desktop using the commands "cd" followed by "cd Desktop". You can
+now run the script by entering "%run hello.py" in ipython. We'll learn
+more about writing python files ourselves in the next session.
+
+**Aside: IDLE** IDLE can do a lot more that write simple python scripts.
+It contains its own python interpreter, so you can run python scripts
+directly within IDLE by hitting f5. It also contains a debugger. We're
+not going to use these features in this boot camp - instead we will
+write the scripts in IDLE and run them in ipython since we are already
+familiar with it. However, running writing and running scripts in IDLE
+has its advantages and I encourage you to learn more about it.
+
+# Using the sys module
+
+The sys module gives you access to the Python interpreter. Some
+important objects in this module are: 1) sys.argv is a list of command
+line arguments. The first argument is always the name of the file. 2)
+sys.path gives a list of all paths on your computer where Python will
+look for modules 2) sys.modules gives a dictionary of all currently
+loaded modules.
+
+Put the following text in a file findPrimes.py in your current working
+directory.
+
+```python
+''' findPrimes.py
+List whether the numbers passed in the command line are prime.
+'''
+
+from sys import argv
+
+for i in xrange(1,len(argv)):
+ print argv[i]
+```
+
+This program should print each input on its own line.
+
+**Hands on example**
+
+How could you alter the for loop to not use xrange and element indexing?
+
+Now, let's work on the next piece of the program, which is a function to
+compute whether a number is prime. To do that, we'll need to detour to
+talk about functions in general.
+
+# Using Functions
+
+The keyword "\`def\`" is used to define a function. As in the case of
+conditionals and loops, whitespace is used to define the body of a
+function. Try entering the following into iPython:
+
+```python
+> def triangle_perimeter(a, b, c):
+> return a + b + c
+>
+> p = triangle_perimeter(3,4,5)
+> print p
+```
+
+Python functions can return multiple values:
+
+```python
+def rgb(color_name):
+
+ if color_name is "red":
+ return 1,0,0
+ if color_name is "green":
+ return 1,0,0
+ if color_name is "blue":
+ return 1,0,0
+ if color_name is "yellow":
+ return 1,1,0
+
+ print "ERROR: Unknown color"
+
+ r,g,b = rgb("yellow")
+ print r,g,b
+```
+
+**Hands-on Example**
+
+Write a function, "\`perimeter\`" that takes one argument - a tuple
+containing the lengths of each side of a polygon. Have the function
+return the perimeter of the polygon. So, for example to find the area of
+a square with side length 3, the function call would be:
+perimeter((3,3,3,3)) and the function would return 12. Use the \`help\`
+and \`dir\` functions to figure out how to write this function in one
+line.
+
+## Variable Number of Arguments
+
+In the last example, you wrote a function, called \`perimeter\`, that
+you have to call like this:
+
+```python
+print perimeter((1,2,3,4,5))
+```
+
+You need the extra set of parentheses, because the function takes only
+one argument - a single tuple. Wouldn't it be nice if we didn't have to
+have the extra parentheses? It turns out that this is easy in python:
+
+```python
+def perimeter(\*args):
+ return sum(args)
+
+print perimeter(1,2,3,4,5)
+```
+
+Notice that little star on the first line. That star tells python to
+take all of the arguments and bundle them into a single tuple called
+args. This feature allows us to create functions that take a variable
+number of arguments. The function calls do not require the extra set of
+parentheses we saw earlier.
+
+**Hands-on Example**
+
+Write a function that takes a variable number of floating point
+arguments and returns their average.
+
+## Keyword Arguments
+
+Consider the following function, whose arguments represent the model
+year, mileage, and number of accidents that a car has had. The function
+attempts to use this information to compute the value of the car.
+
+```python
+def carvalue(year, mileage, nacc):
+ return 30000 - mileage/10 - nacc*1000 - (2010-year)*1000
+
+print carvalue(2001, 100000, 2)
+```
+
+In order to use the \`carvalue\` function, we have to remember that
+\`year\` is the first argument, \`mileage\` is the second, and \`nacc\`
+is the third. If we accidentally put the wrong argument in the wrong
+place then we will compute the wrong answer. Luckily, we can be explicit
+when calling functions using the following syntax:
+
+```python
+print carvalue(year=2001, mileage = 100000, nacc=2)
+print carvalue(mileage= 100000, year = 2001, nacc=2) # Also produces the correct answer!
+print carvalue(2001, nacc= 2, mileage = 100000) # Sets the year to 2001, the mileage to 100000, and nacc to 2
+print carvalue(year= 2001, mileage = 100000, 2) # ERROR: Keyword arguments must precede non-keyword arguments
+```
+
+## Default Value Arguments
+
+Suppose I did a study that showed that the average number of car
+accidents a particular vehicle experienced was two. Now I want to modify
+the \`carvalue\` function so that if the user doesn't know the number of
+accidents, the function will use two by default. I can do this by
+providing a default value in the function definition.
+
+```python
+def carvalue(year, mileage, nacc=2):
+ return 30000 - mileage/10 - nacc*1000 - (2010-year)*1000
+
+print carvalue(2001, 100000, 2) # Works just like before
+print carvalue(2001, 100000) # Since nacc is not specified, it defaults to 2
+```
+
+You cannot mix default value arguments and variable numbers of arguments
+in the same function.
+
+# Back to Prime Numbers
+
+Let's write a function in findPrimes.py to find prime numbers. Recall
+that a prime number is a number that has no divisors other than 1 and
+the number itself. In the code below, I'm using the sqrt function, which
+can be imported from the math module.
+
+```python
+def isPrime(n):
+ ''' Return True iff a number is prime. '''
+
+ if n <= 0:
+ return False
+ if n <= 2:
+ return True
+
+ if n % 2 == 0:
+ return False
+
+ cntr = 3 # The first odd divisor is 2.
+ stopPoint = sqrt(n)
+ while cntr <= stopPoint:
+ if n % cntr == 0: return False
+ cntr += 2
+
+ return True
+```
+
+**Hands on example** Devise a few tests for this function. Are there any
+special cases you've forgotten? Are there any checks for data validity
+that we should add?
418 3a-VersionControlLocal/Readme.md
View
@@ -0,0 +1,418 @@
+Local Version Control
+\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
+
+[Back To Python Functions and
+Modules](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/2d-PythonFunctionsAndModules/)
+- [Forward To Remote Version
+Control](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/3b-VersionControlRemote/)
+
+* * * * *
+
+**Presented By : Katy Huff**
+
+# git : What is Version Control ?
+
+Very briefly, version control is a way to keep a backup of changing
+files, to store a history of those changes, and most importantly to
+allow many people in a collaboration to make changes to the same files
+concurrently. There are a lot of verson control systems. Wikipedia
+provides both a nice vocabulary list and a fairly complete table of some
+popular version control systems and their equivalent commands.
+
+Today, we'll be using git. Git is an example of a distributed version
+control system, distinct from centralized verson control systems. I'll
+make the distinction clear later, but for now, the table below will
+suffice.
+
+ Version Control System To ol Options
+ --------------------------- -----------------------------------
+ **Distributed** **Centralized**
+ Decentralized CVS (dcvs) concurrent versions system (cvs)
+ mercurial (hg) subversion (svn)
+ git (git)
+ bazaar (bzr)
+
+# git --help : Getting Help
+
+The first thing I like to know about any tool is how to get help. From
+the command line type
+
+ $ man git
+
+The manual entry for the git version control system will appear before
+you. You may scroll through it using arrows, or you can search for
+keywords by typing **/** followed by the search term. I'm interested in
+help, so I type **/help** and then hit enter. It looks like the syntax
+for getting help with git is **git --help**.
+
+To exit the manual page, type q.
+
+Let's see what happens when we type :
+
+ $ git --help
+
+Excellent, it gives a list of commands it is able to help with, as well
+as their descriptions.
+
+ $ git --help
+ usage: git [--version] [--exec-path[=<path>]] [--html-path]
+ [-p|--paginate|--no-pager] [--no-replace-objects]
+ [--bare] [--git-dir=<path>] [--work-tree=<path>]
+ [-c name=value] [--help]
+ <command> [<args>]
+
+ The most commonly used git commands are:
+ add Add file contents to the index
+ bisect Find by binary search the change that introduced a bug
+ branch List, create, or delete branches
+ checkout Checkout a branch or paths to the working tree
+ clone Clone a repository into a new directory
+ commit Record changes to the repository
+ diff Show changes between commits, commit and working tree, etc
+ fetch Download objects and refs from another repository
+ grep Print lines matching a pattern
+ init Create an empty git repository or reinitialize an existing one
+ log Show commit logs
+ merge Join two or more development histories together
+ mv Move or rename a file, a directory, or a symlink
+ pull Fetch from and merge with another repository or a local branch
+ push Update remote refs along with associated objects
+ rebase Forward-port local commits to the updated upstream head
+ reset Reset current HEAD to the specified state
+ rm Remove files from the working tree and from the index
+ show Show various types of objects
+ status Show the working tree status
+ tag Create, list, delete or verify a tag object signed with GPG
+
+ See 'git help <command>' for more information on a specific command.
+
+# git init : Creating a Local Repository
+
+To keep track of numerous versions of your work without saving numerous
+copies, you can make a local repoitory for it on your computer. What git
+does is to save the first version, then for each subsequent version it
+saves only the changes. That is, git only records the difference between
+the new version and the one before it. With this compact information,
+git is able to recreate any version on demand by adding the changes to
+the original in order up to the version of interest.
+
+To create your own local (on your own machine) repository, you must
+initialize the repository with the infrastructure git needs in order to
+keep a record of things within the repsitory that you're concerned
+about. The command to do this is **git init** .
+
+## Exercise : Create a Local Repository
+
+Step 1 : Initialize your repository.
+
+ $ mkdir good_science
+ $ cd good_science
+ $ git init
+ Initialized empty Git repository in /Users/khuff/Documents/hacker/good_science/.git/
+
+Step 2 : Browse the directory's hidden files to see what happened here.
+Open directories, browse file contents. Learn what you can in a minute.
+
+ $ ls -A
+ .git
+ $ cd .git
+ $ ls -A
+ HEAD config description hooks info objects refs
+
+Step 3 : Use what you've learned. You may have noticed the file called
+description. You can escribe your repository by opening the description
+file and replacing the text with a name for the repository. Mine will be
+called "Reproducible Science". You may call yours anything you like.
+
+ $ gedit description &
+
+# git add : Adding a File To Version Control
+
+For the git repository to know which files within this directory you
+would like to keep track of, you must add them. First, you'll need to
+create one, then we'll learn the **git add** command.
+
+## Exercise : Add a File to Your Local Repository
+
+Step 1 : Create a file to add to your repository.
+
+ $ gedit readme.rst &
+
+Step 2 : Inform git that you would like to keep track of future changes
+in this file.
+
+ $ git add readme.rst
+
+# Checking The Status of Your Local Copy
+
+The files you've created on your machine are your local "working" copy.
+The changes your make in this local copy aren't backed up online
+automatically. Until you commit them, the changes you make are local
+changes. When you change anything, your set of files becomes different
+from the files in the official repository copy. To find out what's
+different about them in the terminal, try:
+
+ $ git status
+ # On branch master
+ #
+ # Initial commit
+ #
+ # Changes to be committed:
+ # (use "git rm --cached <file>..." to unstage)
+ #
+ # new file: readme.rst
+ #
+
+The null result means that you're up to date with the current version of
+the repository online. This result indicates that the current difference
+between the repository HEAD (which, so far, is empty) and your
+good\_science directory is this new readme.rst file.
+
+# git commit : Saving a Snapshot
+
+In order to save a snapshot of the current state (revision) of the
+repository, we use the commit command. This command is always associated
+with a message describing the changes since the last commit and
+indicating their purpose. Informative commit messages will serve you
+well someday, so make a habit of never committing changes without at
+least a full sentence description.
+
+**ASIDE: Commit Often**
+
+In the same way that it is wise to often save a document that you are
+working on, so too is it wise to save numerous revisions of your code.
+More frequent commits increase the granularity of your **undo** button.
+
+## Exercise : Commit Your Changes
+
+Step 1 : Commit the file you've added to your repository.
+
+ $ git commit -am "This is the first commit. It adds a readme file."
+ [master (root-commit) 1863aef] This is the first commit. It adds a readme file.
+ 1 files changed, 2 insertions(+), 0 deletions(-)
+ create mode 100644 readme.rst
+
+Step 2 : Admire your work.
+
+ $ git status
+ # On branch master
+ nothing to commit (working directory clean)
+
+# git diff : Viewing the Differences
+
+There are many diff tools.
+
+If you have a favorite you can set your default git diff tool to execute
+that one. Git, however, comes with its own diff system.
+
+Let's recall the behavior of the diff command on the command line.
+Choosing two files that are similar, the command :
+
+ $ diff file1 file2
+
+will output the lines that differ between the two files. This
+information can be saved as what's known as a patch, but we won't go
+deeply into that just now.
+
+The only difference between the command line diff tool and git's diff
+tool is that the git tool is aware of all of the revisions in your
+repository, allowing each revision of each file to be treated as a full
+file.
+
+Thus, git diff will output the changes in your working directory that
+are not yet staged for a commit. To see how this works, make a change in
+your readme.rst file, but don't yet commit it.
+
+ $ git diff
+
+A summarized version of this output can be output with the --stat flag :
+
+ $ git diff --stat
+
+To see only the differences in a certain path, try:
+
+ $ git diff HEAD -- [path]
+
+To see what IS staged for commit (that is, what will be committed if you
+type git commit without the -a flag), you can try :
+
+ $ git diff --cached
+
+# git log : Viewing the History
+
+A log of the commit messages is kept by the repository and can be
+reviewed with the log command.
+
+ $ git log
+ commit 1863aefd7db752f58226264e5f4282bda641ddb3
+ Author: Katy Huff <katyhuff@gmail.com>
+ Date: Wed Feb 8 16:08:08 2012 -0600
+
+ This is the first commit. It adds a readme file.
+
+There are some useful flags for this command, such as
+
+ -p
+ -3
+ --stat
+ --oneline
+ --graph
+ --short
+ --full
+ --pretty
+ --since
+ --until
+ --author
+
+# git branch : Listing, Creating, and Deleting Branches
+
+Branches are parallel instances of a repository that can be edited and
+version controlled in parallel. They are useful for pursuing various
+implementations experimentally or maintaining a stable core while
+developing separate sections of a code base.
+
+Without an argument, the **branch** command lists the branches that
+exist in your repository.
+
+ $ git branch
+ * master
+
+The master branch is created when the repository is initialized. With an
+argument, the **branch** command creates a new branch with the given
+name.
+
+ $ git branch experimental
+ $ git branch
+ * master
+ experimental
+
+To delete a branch, use the **-d** flag.
+
+ $ git branch -d experimental
+ $ git branch
+ * master
+
+# git checkout : Switching Between Branches, Abandoning Local Changes
+
+The **git checkout** command allows context switching between branches
+as well as abandoning local changes.
+
+To switch between branches, try
+
+::
+ ~ $ git branch newbranch $ git checkout newbranch $ git branch
+
+How can you tell we've switched between branches? When we used the
+branch command before there was an asterisk next to the master branch.
+That's because the asterisk indicates which branch you're currently in.
+
+# git merge : Merging Branches
+
+At some point, the experimental branch may be ready to become part of
+the core or two testing branches may be ready to be combined for further
+integration testing. The method for combining the changes in two
+parallel branches is the **merge** command.
+
+## Exercise : Create and Merge Branches
+
+Step 1 : Create two new branches and list them
+
+ $ git branch first
+ $ git branch second
+
+Step 2 : Make changes in each new branch and commit them.
+
+ $ git checkout first
+ Switched to branch 'first'
+ $ touch firstnewfile
+ $ git add firstnewfile
+ $ git commit -am "Added firstnewfile to the first branch."
+ [first 68eba44] Added firstnewfile to first branch.
+ 0 files changed, 0 insertions(+), 0 deletions(-)
+ create mode 100644 firstnewfile
+ $ git checkout second
+ Switched to branch 'second'
+ $ touch secondnewfile
+ $ git add secondnewfile
+ $ git commit -am "Added secondnewfile to the second branch."
+ [second 45dd34c] Added secondnewfile to the second branch.
+ 0 files changed, 0 insertions(+), 0 deletions(-)
+ create mode 100644 secondnewfile
+
+Step 3 : Merge the two branches into the core
+
+ $ git checkout first
+ Switched to branch 'first'
+ $ git merge second
+ Merge made by recursive.
+ 0 files changed, 0 insertions(+), 0 deletions(-)
+ create mode 100644 secondnewfile
+ $ git checkout master
+ Switched to branch 'master'
+ $ git merge first
+ Updating 1863aef..ce7e4b5
+ Fast-forward
+ 0 files changed, 0 insertions(+), 0 deletions(-)
+ create mode 100644 firstnewfile
+ create mode 100644 secondnewfile
+
+# git clone : Copying a Repository
+
+The Hacker Within has its own online code repositories. You can check
+out code from them at any time, from anywhere. You checked out some code
+this morning at github
+[http://www.github.com/thehackerwithin/PyTrieste.](http://www.github.com/thehackerwithin/PyTrieste.)
+
+If you gave me github account name, you are a fully fledged reading
+writing member today. Remember, with great power comes great
+responsibility.
+
+Today, we'll check out a git type repository at
+www.github.com/thehackerwithin/PyTrieste .
+
+When you clone the Original repository, the one that is created on your
+local machine is a copy, and will behave as a fully fledged local
+repository locally. However, with the right configuration, it will be
+able to pull changes from collaborators to your local machine and push
+your changes to the Original repository. We'll get to that soon, but for
+now, let's **fork** the repository from GitHub.
+
+## Exercise : Cloning a Repository from GitHub
+
+Step 1 : Pick any repository you like. There are many cool projects
+hosted on github. Take a few minutes here, and pick a piece of code. May
+I recommend the cyclus repository or the github.com/cyclus/core.
+
+Step 2 : Clone it. If you didn't find anything cool, you can chose the
+"instructional" Spoon-Knife repository:
+
+ $ git clone git@github.com/octocat/Spoon-Knife.git
+ Cloning into Spoon-Knife...
+ remote: Counting objects: 24, done.
+ remote: Compressing objects: 100% (21/21), done.
+ remote: Total 24 (delta 7), reused 17 (delta 1)
+ Receiving objects: 100% (24/24), 74.36 KiB, done.
+ Resolving deltas: 100% (7/7), done.
+
+Step 3 : You should see many files download themselves onto your
+machine. Let's make sure it worked. Change directories to the source
+code and list the contents.
+
+ $ cd Spoon-Knife
+ $ ls
+
+# git pull : Pulling updates from the Original Repository
+
+Updating your repository is like voting. You should update early and
+often especially if you intend to contribute back to the upstream
+repository and particularly before you make or commit any changes. This
+will ensure you're working with the most up-to-date version of the
+repository. Updating won't overwrite any changes you've made locally
+without asking, so don't get nervous. When in doubt, update.
+
+ $ git pull
+ Already up-to-date.
+
+Since we just pulled the repository down, we will be up to date unless
+there has been a commit by someone else to the Original repository in
+the meantime.
303 3b-VersionControlRemote/Readme.md
View
@@ -0,0 +1,303 @@
+Version Control Collaboratively
+\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
+
+[Back To Local Version
+Control](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/3a-VersionControlLocal/)
+- [Forward To
+Debugging](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/4-Debugging/)
+
+* * * * *
+
+**Presented By : Katy Huff**
+
+# github.com?
+
+GitHub is a site where many people store their open (and closed) source
+code repositories. It provides tools for browsing, collaborating on and
+documenting code. It is very similar to the [[ictp gforge portal|
+http://gforge.ictp.it]]. GitHub, much like the ictp gforge portal and
+other forge hosting services ([[launchpad|https://launchpad.net]],
+[[bitbucket | https://bitbucket.org]], [[googlecode |
+http://code.google.com]], [[sourceforge | http://sourceforge.net]] etc.)
+provides :
+
+- landing page support ([[my research is at cyclus.github.com |
+ http://cyclus.github.com]])
+- wiki support
+- network graphs and time histories of commits
+- code browser with syntax highlighting
+- issue (ticket) tracking
+- user downloads
+- varying permissions for various groups of users
+- commit triggered mailing lists
+- other service hooks (twitter, etc.)
+
+Setting up github at first requires [[some setup |
+http://help.github.com/set-up-git-redirect]].
+
+# git config : Configuring your git environment
+
+Once you've set up your rsa keys, you need to tell github who you are.
+Crack open a terminal.
+
+ $ git config --global user.name "Firstname Lastname"
+ $ git config --global user.email "your_email@youremail.com"
+
+Unless your name is Firstname Lastname, please don't copy the above
+lines verbatim. Make the appropriate substitutions.
+
+If you did this properly, you'll have a file in your home **(\~)**
+directory that's called **.gitconfig** . It's contents should look like
+:
+
+ [user]
+ name = Katy Huff
+ email = southside@gmail.com
+
+This configuration step allows github to properly credit the authorship
+of changes you make in your repository. For projects with numerous
+authors, this is essential.
+
+Another configuration step for some will be to set their favorite text
+editor as git's text editor of choice. This is optional, since vi is
+usually the default, but can be done with the following command (if you
+like **gedit** for example):
+
+ $ git config --global core.editor gedit
+
+# git remote : Steps for Forking a Repository
+
+A key step to interacting with an online repository that you have forked
+is adding the original as a remote repository. By adding the remote
+repository, you inform git of a new option for fetching updates and
+pushing commits.
+
+The **git remote** command allows you to add, name, rename, list, and
+delete repositories such as the original one **upstream** from your
+fork, others that may be **parallel** to your fork, and so on.
+
+## Exercise : Fork Our GitHub Repository
+
+While you probably already have a copy of the PyTrieste repository,
+GitHub doesn't know about it yet. You'll need to tell github you want to
+have an official fork of this repository.
+
+Step 1 : Go to our [[repository |
+https://github.com/thehackerwithin/PyTrieste/]] from your browser, and
+click on the Fork button. Choose to fork it to your username rather than
+any organizations.
+
+Step 2 : Clone it. From your terminal :
+
+ $ git clone git@github.com:username/PyTrieste.git
+ $ cd PyTrieste
+
+Step 3 :
+
+ $ git remote add upstream git://github.com/thehackerwithin/PyTrieste.git
+ $ git remote -v
+ origin git@github.com:username/PyTrieste.git (fetch)
+ origin git@github.com:username/PyTrieste.git (push)
+ upstream git://github.com/thehackerwithin/PyTrieste.git (fetch)
+ upstream git://github.com/thehackerwithin/PyTrieste.git (push)
+
+All repositories that are clones begin with a remote called origin.
+
+# git fetch : Fetching the contents of a remote
+
+Now that you have alerted your repository to the presence of others, it
+is able to pull in updates from those repositories. In this case, if you
+want your master branch to track updates in the original PyTrieste
+repository, you simply **git fetch** that repository into the master
+branch of your current repository.
+
+The fetch command alone merely pulls down information recent changes
+from the original master (upstream) repository. By itself, the fetch
+command does not change your local working copy. To update your local
+working copy to include recent changes in the original (upstream)
+repository, it is necessary to also merge.
+
+# git merge : Merging the contents of a remote
+
+To incorporate upstream changes from the original master repository (in
+this case thehackerwithin/PyTrieste) into your local working copy, you
+must both fetch and merge. The process of merging may result in
+conflicts, so pay attention. This is where version control is both at
+its most powerful and its most complicated.
+
+## Exercise : Fetch and Merge the Contents of Our GitHub Repository
+
+Step 1 : Fetch the recent remote repository history
+
+ $ git fetch upstream
+
+Step 2 : Make certain you are in the master branch and merge the
+upstreeam master branch into your master branch
+
+ $ git checkout master
+ $ git merge upstream\master
+
+Step 3 : Check out what happened by browsing the directory.
+
+# git pull : Pull = Fetch + Merge
+
+The command **git pull** is the same as executing **git fetch** followed
+by **git merge**. Though it is not recommened for cases in which there
+are many branches to consider, the pull command is shorter and simpler
+than fetching and merging as it automates the branch matching.
+Specificially, to perform the same task as we did in the previous
+exercise, the pull command would be :
+
+ $ git pull upstream
+ Already up-to-date.
+
+When there have been remote changes, the pull will apply those changes
+to your local branch, unless there are conflicts with your local
+changes.
+
+# git push : Sending Your Commits to Remote Repositories
+
+The **git push** command pushes commits in a local working copy to a
+remote repository. The syntax is git push [remote] [local branch].
+Before pushing, a developer should always pull (or fetch + merge), so
+that there is an opportunity to resolve conflicts before pushing to the
+remote.
+
+We'll talk about conflicts later, but first, since we have no conflicts
+and are up to date, we can make a minor change and send our changes to
+your fork, the "origin."
+
+ $ git push origin master
+
+If you have permission to push to the upstream repository, sending
+commits to that remote is exactly analagous.
+
+ $ git push upstream master
+
+In the case of the PyTrieste code, new developer accounts will not allow
+this push to succeed. You're welcome to try it though.
+
+# git merge : Conflicts
+
+This is the trickiest part of version control, so let's take it very
+carefully.
+
+In the PyTrieste code, you'll find a file called readme.rst. This is a
+standard documentation file that appears rendered on the landing page
+for the repository in github. To see the rendered version, visit your
+fork on github,
+[https://github.com/username/PyTrieste/](https://github.com/username/PyTrieste/)
+.
+
+For illustration, let's imagine that, suddenly, each of the developers
+on the PyTrieste code would like to welcome visitors in a language other
+than English. Since we're all from so many different nations and speak
+so many languages, there will certainly be disagreements about what to
+say instead of "Welcome."
+
+I, for example, am from Texas, so I'll push (to the upstream repository)
+my own version of the Welcome on line 2 of readme.rst.
+
+You, however will want to replace the english word Welcome with an
+equivalent word that you prefer (willkommen, bienvenido, benvenuti,
+etc.).
+
+You'll want to start a new branch for development. It's a good
+convention to think of your master branch as the "production branch,"
+typically by keeping that branch clean of your local edits until they
+are ready for release. Developers typically use the master branch of
+their local fork to track other developers changes in the remote
+repository until their own local development branch changes are ready
+for production.
+
+## Exercise : Experience a Conflict
+
+Step 1 : Make a new branch, edit the readme file in that branch, and
+commit your changes.
+
+ $ git branch development
+ $ git checkout development
+ Switched to branch 'development'
+ $ gedit readme.rst &
+ <edit the readme file and exit gedit>
+ $ git commit -am "Changed the welcome message to ... "
+
+Step 2 : Mirror the remote upstream repository in your master branch by
+pulling down my changes
+
+ $ git checkout master
+ Switched to branch 'master'
+ $ git fetch upstream
+ $ git merge upstream/master
+ Updating 43844ea..3b36a87
+ Fast-forward
+ README.rst | 2 +-
+ 1 files changed, 1 insertions(+), 1 deletions(-)
+
+Step 3 : You want to push it to the internet eventually, so you pull
+updates from the upstream repository, but will experience a conflict.
+
+ $ git merge development
+ Auto-merging readme.rst
+ CONFLICT (content): Merge conflict in readme.rst
+ Automatic merge failed; fix conflicts and then commit the result.
+
+# git resolve : Resolving Conflicts
+
+Now what?
+
+Git has paused the merge. You can see this with the **git status**
+command.
+
+ # On branch master
+ # Unmerged paths:
+ # (use "git add/rm <file>..." as appropriate to mark resolution)
+ #
+ # unmerged: readme.rst
+ #
+ no changes added to commit (use "git add" and/or "git commit -a")
+
+The only thing that has changed is the readme.rst file. Opening it,
+you'll see something like this at the beginning of the file.
+
+ =====================
+ <<<<<<< HEAD
+ Howdy
+ =======
+ Willkommen
+ >>>>>>> development
+ =====================
+
+The intent is for you to edit the file, knowing now that I wanted the
+Welcome to say Howdy. If you want it to say Willkommen, you should
+delete the other lines. However, if you want to be inclusive, you may
+want to change it to read Howdy and Willkommen. Decisions such as this
+one must be made by a human, and why conflict resolution is not handled
+more automatically by the version control system.
+
+ =====================
+ Howdy and Willkommen
+ =====================
+
+This results in a status To alert git that you have made appropriate
+alterations,
+
+ $ git add readme.rst
+ $ git commit
+ Merge branch 'development'
+
+ Conflicts:
+ readme.rst
+ #
+ # It looks like you may be committing a MERGE.
+ # If this is not correct, please remove the file
+ # .git/MERGE_HEAD
+ # and try again.
+ #
+ $ git push origin master
+ Counting objects: 10, done.
+ Delta compression using up to 2 threads.
+ Compressing objects: 100% (6/6), done.
+ Writing objects: 100% (6/6), 762 bytes, done.
+ Total 6 (delta 2), reused 0 (delta 0)
+ To git@github.com:username/PyTrieste.git
36 4-Debugging/Readme.md
View
@@ -0,0 +1,36 @@
+# Debugging
+
+[Back To Remote Version
+Control](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/3b-VersionControlRemote/)
+- [Forward To
+Testing](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/5-Testing/)
+
+Compile each program without optimization first.
+
+For simpleTest.cc, run this line to see errors in this code.
+
+ valgrind --track-origins=yes --leak-check=full ./simpleTest 300 300
+
+We also have a cache test line. Run this line to see the cache errors.
+
+ valgrind --tool=cachegrind ./a.out 0 1000 100000
+
+There are two paths in this code. If the first input is 1, it runs a
+cache-sensitive version of the loop. If it is 0, it runs a
+cache-insensitive version.
+
+FYI: on the Trieste lab machines, this is what cache looks like:
+
+ guy ~>dmesg | grep cache
+ CPU: L1 I cache: 32K, L1 D cache: 32K
+ CPU: L2 cache: 6144K
+ CPU: L1 I cache: 32K, L1 D cache: 32K
+ CPU: L2 cache: 6144K
+
+You can run the same command to see cache on your linux machine. Another
+way to see the exact cache setup that valgrind found is the following:
+
+ cg_annotate --auto=yes cachegrind.out.21960
+
+Note that your cachegrind.out will have a different number. This command
+is also handy because it shows which functions caused cache misses.
374 5-Testing/Readme.md
View
@@ -0,0 +1,374 @@
+[[Back To NumPy | Python9-NumPy]] - [[Forward To Home | Home]]
+
+* * * * *
+
+**Presented By Tommy Guy**
+
+**Based on materials by Katy Huff and Rachel Slaybaugh**
+
+**What is testing?**
+
+Software testing is a process by which one or more expected behaviors
+and results from a piece of software are exercised and confirmed. Well
+chosen tests will confirm expected code behavior for the extreme
+boundaries of the input domains, output ranges, parametric combinations,
+and other behavioral edge cases.
+
+**Why test?**
+
+Unless you write flawless, bug-free, perfectly accurate, fully precise,
+and predictable code every time, you must test your code in order to
+trust it enough to answer in the affirmative to at least a few of the
+following questions:
+
+Does your code work?
+
+Always?
+
+Does it do what you think it does?
+
+Does it continue to work after changes are made?
+
+Does it continue to work after system configurations or libraries are
+upgraded?
+
+Does it respond properly for a full range of input parameters?
+
+What about edge or corner cases?
+
+What’s the limit on that input parameter?
+
+**Verification**
+
+Verification is the process of asking, “Have we built the software
+correctly?” That is, is the code bug free, precise, accurate, and
+repeatable?
+
+**Validation**
+
+Validation is the process of asking, “Have we built the right software?”
+That is, is the code designed in such a way as to produce the answers
+we’re interested in, data we want, etc.
+
+Where are tests ? Say we have an averaging function:
+
+ def mean(numlist):
+ total = sum(numlist)
+ length = len(numlist)
+ return total/length
+
+The test could be runtime exceptions in the function.
+
+ def mean(numlist):
+ try :
+ total = sum(numlist)
+ length = len(numlist)
+ except ValueError :
+ print "The number list was not a list of numbers."
+ except :
+ print "There was a problem evaluating the number list."
+ return total/length
+
+Sometimes they’re alongside the function definitions they’re testing.
+
+ def mean(numlist):
+ try :
+ total = sum(numlist)
+ length = len(numlist)
+ except ValueError :
+ print "The number list was not a list of numbers."
+ except :
+ print "There was a problem evaluating the number list."
+ return total/length
+
+ class TestClass:
+ def test_mean(self):
+ assert(mean([0,0,0,0])==0)
+ assert(mean([0,200])==100)
+ assert(mean([0,-200]) == -100)
+ assert(mean([0]) == 0)
+ def test_floating_mean(self):
+ assert(mean([1,2])==1.5)
+
+Sometimes they’re in an executable independent of the main executable.
+
+ def mean(numlist):
+ try :
+ total = sum(numlist)
+ length = len(numlist)
+ except ValueError :
+ print "The number list was not a list of numbers."
+ except :
+ print "There was a problem evaluating the number list."
+ return total/length
+
+Where, in a different file exists a test module:
+
+ import mean
+ class TestClass:
+ def test_mean(self):
+ assert(mean([0,0,0,0])==0)
+ assert(mean([0,200])==100)
+ assert(mean([0,-200]) == -100)
+ assert(mean([0]) == 0)
+ def test_floating_mean(self):
+ assert(mean([1,2])==1.5)
+
+**When should we test?**
+
+The short answer is all the time. The long answer is that testing either
+before or after your software is written will improve your code, but
+testing after your program is used for something important is too late.
+
+If we have a robust set of tests, we can run them before adding
+something new and after adding something new. If the tests give the same
+results (as appropriate), we can have some assurance that we didn’t
+break anything. The same idea applies to making changes in your system
+configuration, updating support codes, etc.
+
+Another important feature of testing is that it helps you remember what
+all the parts of your code do. If you are working on a large project
+over three years and you end up with 200 classes, it may be hard to
+remember what the widget class does in detail. If you have a test that
+checks all of the widget’s functionality, you can look at the test to
+remember what it’s supposed to do.
+
+**Who tests?** In a collaborative coding environment, where many
+developers contribute to the same code, developers should be responsible
+individually for testing the functions they create and collectively for
+testing the code as a whole.
+
+Professionals invariably test their code, and take pride in test
+coverage, the percent of their functions that they feel confident are
+comprehensively tested.
+
+**How does one test?**
+
+The type of tests you’ll write is determined by the testing framework
+you adopt.
+
+**Types of Tests:** *Exceptions* Exceptions can be thought of as type of
+runttime test. They alert the user to exceptional behavior in the code.
+Often, exceptions are related to functions that depend on input that is
+unknown at compile time. Checks that occur within the code to handle
+exceptional behavior that results from this type of input are called
+Exceptions.
+
+*Unit Tests*
+
+Unit tests are a type of test which test the fundametal units a
+program’s functionality. Often, this is on the class or function level
+of detail.
+
+To test functions and classes, we want to test the interfaces, rather
+than the implmentation. Treating the implementation as a ‘black box’, we
+can probe the expected behavior with boundary cases for the inputs.
+
+In the case of our fix\_missing function, we need to test the expected
+behavior by providing lines and files that do and do not have missing
+entries. We should also test the behavior for empty lines and files as
+well. These are boundary cases.
+
+*System Tests*
+
+System level tests are intended to test the code as a whole. As opposed
+to unit tests, system tests ask for the behavior as a whole. This sort
+of testing involves comparison with other validated codes, analytical
+solutions, etc.
+
+*Regression Tests*
+
+A regression test ensures that new code does change anything. If you
+change the default answer, for example, or add a new question, you’ll
+need to make sure that missing entries are still found and fixed.
+
+*Integration Tests*
+
+Integration tests query the ability of the code to integrate well with
+the system configuration and third party libraries and modules. This
+type of test is essential for codes that depend on libraries which might
+be updated independently of your code or when your code might be used by
+a number of users who may have various versions of libraries.
+
+**Test Suites** Putting a series of unit tests into a suite creates, as
+you might imagine, a test suite.
+
+**Elements of a Test**
+
+**Behavior**
+
+The behavior you want to test. For example, you might want to test the
+fun() function.
+
+**Expected Result**
+
+This might be a single number, a range of numbers, a new, fully defined
+object, a system state, an exception, etc.
+
+When we run the fun function, we expect to generate some fun. If we
+don’t generate any fun, the fun() function should fail its test.
+Alternatively, if it does create some fun, the fun() function should
+pass this test.
+
+**Assertions**
+
+Require that some conditional be true. If the conditional is false, the
+test fails.
+
+**Fixtures**
+
+Sometimes you have to do some legwork to create the objects that are
+necessary to run one or many tests. These objects are called fixtures.
+
+For example, since fun varies a lot between people, the fun() function
+is a member function of the Person class. In order to check the fun
+function, then, we need to create an appropriate Person object on which
+to run fun().
+
+**Setup and teardown**
+
+Creating fixtures is often done in a call to a setup function. Deleting
+them and other cleanup is done in a teardown function.
+
+**The Big Picture** Putting all this together, the testing algorithm is
+often:
+
+ setUp
+ test
+ tearDown
+
+But, sometimes it’s the case that your tests change the fixtures. If so,
+it’s better for the setup and teardown functions to occur on either side
+of each test. In that case, the testing algorithm should be:
+
+ setUp
+ test1
+ tearDown
+ setUp
+ test2
+ tearDown
+ setUp
+ test3
+ tearDown
+
+# Python Nose
+
+The testing framework we’ll discuss today is called nose, and comes
+packaged with the enthought python distribution that you’ve installed.
+
+**Where is a nose test?**
+
+Nose tests are files that begin with Test-, Test\_, test-, or test\_.
+Specifically, these satisfy the testMatch regular expression
+[Tt]est[-\_]. (You can also teach nose to find tests by declaring them
+in the unittest.TestCase subclasses chat you create in your code. You
+can also create test functions which are not unittest.TestCase
+subclasses if they are named with the configured testMatch regular
+expression.)
+
+Nose Test Syntax To write a nose test, we make assertions.
+
+ assert (ShouldBeTrue())
+ assert (not ShouldNotBeTrue())
+
+In addition to assertions, in many test frameworks, there are
+expectations, etc.
+
+**Add a test to our work**
+
+There are a few tests for the mean function that we listed in this
+lesson. What are some tests that should fail? Add at least three test
+cases to this set.
+
+*Hint: think about what form your input could take and what you should
+do to handle it. Also, think about the type of the elements in the list.
+What should be done if you pass a list of integers? What if you pass a
+list of strings?*
+
+**Test Driven Development**
+
+Some people develop code by writing the tests first.
+
+If you write your tests comprehensively enough, the expected behaviors
+that you define in your tests will be the necessary and sufficient set
+of behaviors your code must perform. Thus, if you write the tests first
+and program until the tests pass, you will have written exactly enough
+code to perform the behavior your want and no more. Furthermore, you
+will have been forced to write your code in a modular enough way to make
+testing easy now. This will translate into easier testing well into the
+future.
+
+# An example
+
+The overlap method takes two rectangles (red and blue) and computes the
+degree of overlap between them. Save it in overlap.py. A rectangle is
+defined as a tuple of tuples: ((x\_lo,y\_lo),(x\_hi),(y\_hi))
+
+ def overlap(red, blue):
+ '''Return overlap between two rectangles, or None.'''
+
+ ((red_lo_x, red_lo_y), (red_hi_x, red_hi_y)) = red
+ ((blue_lo_x, blue_lo_y), (blue_hi_x, blue_hi_y)) = blue
+
+ if (red_lo_x >= blue_hi_x) or \
+ (red_hi_x <= blue_lo_x) or \
+ (red_lo_y >= blue_hi_x) or \
+ (red_hi_y <= blue_lo_y):
+ return None
+
+ lo_x = max(red_lo_x, blue_lo_x)
+ lo_y = max(red_lo_y, blue_lo_y)
+ hi_x = min(red_hi_x, blue_hi_x)
+ hi_y = min(red_hi_y, blue_hi_y)
+ return ((lo_x, lo_y), (hi_x, hi_y))
+
+Now let's create a set of tests for this class. Before we do this, let's
+think about *how* we might test this method. How should it work?
+
+ from overlap import overlap
+
+ def test_empty_with_empty():
+ rect = ((0, 0), (0, 0))
+ assert overlap(rect, rect) == None
+
+ def test_empty_with_unit():
+ empty = ((0, 0), (0, 0))
+ unit = ((0, 0), (1, 1))
+ assert overlap(empty, unit) == None
+
+ def test_unit_with_unit():
+ unit = ((0, 0), (1, 1))
+ assert overlap(unit, unit) == unit
+
+ def test_partial_overlap():
+ red = ((0, 3), (2, 5))
+ blue = ((1, 0), (2, 4))
+ assert overlap(red, blue) == ((1, 3), (2, 4))
+
+Run your tests.
+
+ [rguy@infolab-33 ~/TestExample]$ nosetests
+ ...F
+ ======================================================================
+ FAIL: test_overlap.test_partial_overlap
+ ----------------------------------------------------------------------
+ Traceback (most recent call last):
+ File "/usr/lib/python2.6/site-packages/nose/case.py", line 183, in runTest
+ self.test(*self.arg)
+ File "/afs/ictp.it/home/r/rguy/TestExample/test_overlap.py", line 19, in test_partial_overlap
+ assert overlap(red, blue) == ((1, 3), (2, 4))
+ AssertionError
+
+ ----------------------------------------------------------------------
+ Ran 4 tests in 0.005s
+
+ FAILED (failures=1)
+
+Oh no! Something failed. The failure was on line in this test:
+
+ def test_partial_overlap():
+ red = ((0, 3), (2, 5))
+ blue = ((1, 0), (2, 4))
+ assert overlap(red, blue) == ((1, 3), (2, 4))
+
+Can you spot why it failed? Try to fix the method so all tests pass.
6 6-Documentation/Readme.md
View
@@ -0,0 +1,6 @@
+# Documentation
+
+[Back To
+Testing](http://github.com/thehackerwithin/UofCSCBC2012/tree/master//) -
+[Forward To Google Feedback
+Form](https://docs.google.com/spreadsheet/viewform?formkey=dDlSWDEzMUt0Ri1TUDlTM21pUEwwSnc6MA#gid=0)
40 Lunch/Readme.md
View
@@ -0,0 +1,40 @@
+# Lunch
+
+Myriad options are available in a 5-15 minutes walking radius of the
+boot camp. Since your lunch break is only an hour long, the following
+options are recommended:
+
+[The Grounds of Being Divinity School
+Cafe](https://sites.google.com/site/groundsofbeing/home/) (in the
+basement of Swift Hall) in the main quadrangle offers a range of
+sandwiches and hot food from local restaurants as well as tea and
+coffee. See campus map\_ . \_map:
+[http://maps.uchicago.edu/pdfs/campus.pdf](http://maps.uchicago.edu/pdfs/campus.pdf)
+
+Hutchinson Commons, 1135 E. 57th Street. Food court style, includes
+Subway, Indian, Japanese, Chinese made-to-order stir-fry, and grill.See
+\`dining map\`\_\_ . \_diningmap:
+[http://dining.uchicago.edu/pdf/Regular%20Hours%201.26.12.pdf](http://dining.uchicago.edu/pdf/Regular%20Hours%201.26.12.pdf)
+\_\_diningmap\_
+
+Charles M. Harper Center, Booth School of Business, 5807 South Woodlawn
+Avenue. Cafeteria style, includes grill, made-to-order sandwiches,
+pizza, and salad bar.
+
+Medici Restaurant, 1327 E 57th Street. Pizza, burgers, pasta, etc.
+\_medici: [http://www.medici57.com](http://www.medici57.com)
+\_\_medici\_
+
+\`Medici Bakery and Deli\`\_\_, next door to the restaurant 1327 E 57th
+Street. A faster, smaller version of the Medici restaurant serves
+sandwiches, salads, ice cream, and to-go versions of the full Medici
+menu. \_medicibakery:
+[http://www.medici57.com/bakery.html](http://www.medici57.com/bakery.html)
+\_\_medicibakery\_
+
+\`Z&H Market Cafe\`\_\_ on 57th Street serves gourmet sandwiches and
+other delectables. \_zh:
+[http://www.zhmarketcafe.com/](http://www.zhmarketcafe.com/) \_\_zh\_
+
+\`Noodles Etc.\`\_\_, 1333 E. 57th Street. Pan-asian cuisine. \_noodles:
+[http://noodlesetc.com/](http://noodlesetc.com/) \_\_noodles\_
61 Readme.md
View
@@ -0,0 +1,61 @@
+# Welcome to the University of Chicago Software Carpentry Boot Camp!!
+
+## Where?
+
+The University of Chicago Software Carpentry Boot Camp will be located
+at : .
+
+## When ?
+
+The boot camp will last from 9am to 5pm on April 2 and 3, 2012. There
+will be a lunch break at 12:30pm on April 2 and a lunch break at 12pm on
+April 3. There will also be coffee breaks intermittently throughout the
+days.
+
+## Who?
+
+The boot camp will be led by Anthony Scopatz, Milad Fatenejad, Joshua R.
+Smith, and Katy Huff. It was organized by Software Carpentry, an online
+compendium of resources for scientific computation.
+
+## What?
+
+ -------- ---------------------------------------------------------------
+ Time Topic
+
+ 8:30 [Set
+ 9:00 Up](http://github.com/thehackerwithin/UofCSCBC2012/tree/master/
+ 12:00 0-SetUp/)
+ 1:00 [Shell](http://github.com/thehackerwithin/UofCSCBC2012/tree/mas
+ 2:00 ter/1-Shell/)
+ 3:00 [Lunch](http://github.com/thehackerwithin/UofCSCBC2012/tree/mas
+ 4:00 ter/Lunch/)
+ 9:00 [Python 1:
+ 11:00 Variables](http://github.com/thehackerwithin/UofCSCBC2012/tree/
+ 12:30 master/2a-PythonVariables/)
+ 1:30 [Python 2: Data
+ 2:30 Structures](http://github.com/thehackerwithin/UofCSCBC2012/tree
+ 4:00 /master/2b-PythonDataStructures/)
+ [Python 3: Flow
+ Control](http://github.com/thehackerwithin/UofCSCBC2012/tree/ma
+ ster/2c-PythonFlowControl/)
+ [Python 4: Functions And
+ Modules](http://github.com/thehackerwithin/UofCSCBC2012/tree/ma
+ ster/2d-PythonFunctionsAndModules/)
+ [Local Version
+ Control](http://github.com/thehackerwithin/UofCSCBC2012/tree/ma
+ ster/3a-VersionControlLocal/)
+ [Collaborative Version
+ Control](http://github.com/thehackerwithin/UofCSCBC2012/tree/ma
+ ster/3b-VersionControlRemote/)
+ [Lunch](http://github.com/thehackerwithin/UofCSCBC2012/tree/mas
+ ter/Lunch/)
+ [Debugging](http://github.com/thehackerwithin/UofCSCBC2012/tree
+ /master/4-Debugging/)
+ [Testing](http://github.com/thehackerwithin/UofCSCBC2012/tree/m
+ aster/5-Testing/)
+ [Documentation](http://github.com/thehackerwithin/UofCSCBC2012/
+ tree/master/6-Documentation/)
+ -------- ---------------------------------------------------------------
+
+
Please sign in to comment.
Something went wrong with that request. Please try again.