Sat 10 September 2016
This is a theory I came up with a few months ago to reconcile some issues I have with the currently accepted model of the origin of the cosmos. I might expand more on it in the future. I'm mostly just putting it here as reference for myself. Taken from an email to my friend Patrick on July 13, 2016 An alternate explanation of the redshift of distance galaxies is that light decays as it moves, red shifting and losing energy because moving large distances requires effort. You asked "where does this energy go?" and I was stumped, but dark energy also poses questions about the law of conservation of energy. If light is redshifted by dark energy, where is that energy going? Does the universe just decrease in energy over time? Why did the universal expansion grind to a halt after the big band and then speed up again in recent eons? As I understand it these are the biggest gaps in the theory of dark energy. I wonder if maybe the energy lost by the universe expanding IS the dark energy. The entire universe is filled with background radiation. Currently this is 1e67 J of energy (assuming the universe is 3.6e80 m3 big and the CMB density is uniform at 4.19e-14 J/m3). The total amount of mass energy in normal matter is (wait for it) 3e69 J (using 3e52kg * c^2) . But the CMB started out as gamma rays which are 1e6 times more energetic than microwaves. So the energy "lost" to the CMB is about 1e73 J, or ~ 1e4 times more than the amount of mass. We currently think that dark energy is 70% of the universe and normal matter is about 5%, so my calculations are < 1e3 off, but since we're dealing with numbers on the order of 1e70 I think being 1e3 off is a pretty good first estimate. I can think of three possible tests for this. The first is to do the above math better. I don't have the chops make such estimates and judge if they are relevant. If that number narrows with better math then that's too big of a coincidence to ignore. Secondly we should be able to create dark energy by "destroying" light. One thing that's always bugged me is that light in theory can cancel itself out (two photos, opposite phase, same frequency in the exact same space). When sound waves do this, the energy is "lost" to heat (eg, noise canceling headphones). But if light waves annihilate, where does that energy go? According to my theory it should generate space! I don't know if it's possible to perfectly line up photos and if so if there's enough space generated to be measured, but it's a fun thought experiment if nothing else. Finally, is there a correlation between brightness of stars (light generating objects fulling tired light expansion) and the expansion of the universe? After the initial expansion there was a "dark age" as stars started burning the expansion picks up. The creation of stars could be a kick off event for dark energy ripping the universe in the second expansion. The more space you have, the more light gets redshifted, creating a runaway chain reaction. The first expansion was the universe burning through the CMB, the second is fueled by light given off by stars. https://xkcd.com/675/
Mon 14 March 2016
I'm finally relaunching my blog using [Pelican](http://blog.getpelican.com/). I previously hosted this blog using Jekyll and I briefly played around with Hexo. I finally settled on Pelican primarily because it's based in python, the server side language I am most familiar with. My transition started because I newly obsessed with [riot.js](http://riotjs.com) and want to include riot in the blog rather than using a thrid party service. Jekyll renders using markdown, which preserves HTML, but only with standard tags. It treats my custom tags ([ur-tabs](/simple-riot-js-tabs-widget.html), markdown, ur-form, etc.) as text and escapes the special characters (greater than and less than). I then switched to Hexo which is in javascript, a language I know fairly well and actually want to learn (unklike Jekyll's Ruby). But after many hours of tweaking it I couldn't get it just right. Specifically I had the opposite problem, I wanted to escape certain HTML characters but was unable to. For example, look at this code sample:

<div></div>
To make somthing like this I'd need a lot of &gt; and &lt; characters which is tedious and annoying. By default Pelican (and also Hexo) supports using markdown or html files, which are served with minimal processing. But Pelican renders the surrounding blog using Jinja2. I wanted more complex logic. Using my [modified JinjaReader](/updated-using-jinja2-in-pelican-templates.html) I can first render the templates with Jinja2. The above code sample was actually generated using the `filter escape` template tags.

<pre><code class="html">
{% filter escape %}
<div></div>
{% endfilter %}
</code></pre>
I'll go into the other technical difficulties here at a later date, but the other big issue I had was deploying to github. Pelican is traditionally deployed using the ghp-import command, which transfers a given directory to a branch. Specifically, because this is a github user page I needed to move the source material to a different branch (specifically source) and then deploy using the following command.

ghp-import -b master output/
git push origin master

That's it for now... Don't really know how to end these blog things... so um... Jinja2 whitespace coming soon!

Sun 13 March 2016

For this blog I decided I would roll my own code samples rather than used codepen or jsfiddle. So I made my own custom tab widget. This uses riot.js as the sole dependancy and comes with a minimum amount of css. All that is needed is a series of `<ur-tab title="SOME TITLE">` elements inside of a `<ur-tabs>` element.


<ur-tabs>
  <ur-tab title="Some Content">
    <p>Sed fermentum lorem vitae leo sodales...</p>
  </ur-tab>
  <ur-tab title="More Content">
    <p>Lorem ipsum dolor sit amet, consectetur...</p>
    <p>Sed at luctus neque, at mollis nunc. Sed...</p>
  </ur-tab>
</ur-tabs>

I prefer this to the usual way to do HTML tabs because the HTML is minimal. Other implimentations (eg jQureyUI) has the tabs and content segregrated separately, which means you need a large amount of HTML to accomplish little. Here's the result of the above example.

Sed fermentum lorem vitae leo sodales, ac placerat lacus ornare. Duis semper nulla vitae pharetra aliquam. Curabitur leo urna, euismod eget blandit eu, condimentum ut nisi. Sed ultricies mi nunc, in vulputate nibh eleifend et. Cras faucibus massa nec elementum varius. Quisque diam justo, blandit eget erat vel, suscipit lobortis nulla. Aenean non risus vel lorem scelerisque ultricies at ac orci. Pellentesque a lacinia libero. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse cursus scelerisque iaculis. Duis erat sapien, auctor in auctor quis, dapibus non elit. Proin varius malesuada est in tincidunt. Aenean commodo quis eros placerat malesuada. Suspendisse potenti. Proin nunc nisl, porta nec velit in, feugiat maximus diam. Aliquam erat volutpat. Suspendisse arcu dolor, porta vel nisl quis, pellentesque tincidunt massa. Donec bibendum eleifend arcu, non elementum mauris ornare at. Quisque eget diam eu mauris consequat fringilla. Ut convallis mollis neque. Donec id tortor ac diam consectetur faucibus nec eget nunc.

Sed at luctus neque, at mollis nunc. Sed accumsan libero ac lorem pharetra elementum eget sed mi. In eu mi non mi laoreet sagittis. Aliquam venenatis consectetur lacus a maximus. Suspendisse sit amet quam non ipsum placerat mattis at et dui. Donec sit amet nunc sagittis, tincidunt sem id, tincidunt augue. Nulla in sollicitudin arcu, ut tristique est. Aliquam erat augue, placerat et vulputate congue, scelerisque quis urna. Suspendisse ante urna, commodo vel lorem eu, elementum imperdiet lorem. Proin fermentum dolor enim, quis porta massa egestas in. Aliquam interdum est nec elit aliquam gravida. Sed in libero et diam lacinia rutrum in sed lorem. Integer ut nisl ut purus iaculis aliquam.

Todo: obviously this is not very feature rich yet. If anyone takes interest in using this I will implement these sooner. In the mean time I plan on just making these as I need them.

  • Load tab content via ajax
  • Choose the starting tab to be active
  • Use `<yield to="title">` to allow more complicated title tabs
  • Make title optional
Tue 02 February 2016

After my last post I tried importing code fragments into jinja templates using the include tag. I ran into the following error multiple times: TypeError: no loader for this environment specified. This is because I was rendering the html as a string, rather than loading the file from the file system. This means there is no context with which to include a template.

To fix this we create an Environment and use a file system loader. I want to be able to import files directly from that template directory, so I set up the path to be relative to the filename. I'm still getting the metadata from HTMLReader.read(), and I would like to make the path lookup a bit more elegant, but for now this will do


# Anywhere in pelicanconf.py
from pelican.readers import HTMLReader
from jinja2 import FileSystemLoader
from jinja2.environment import Environment
import arrow

class JinjaReader(HTMLReader):
  def get_meta_data(self,text):
    lines = [l.strip() for l in text.split("")[0].split('\n') if l.strip()]
    out = {}
    for line in lines:
      i = line.index(":")
      out[line[:i]] = line[i+1:]
    for key,value in out.items():
      out[key] = self.process_metadata(key,value)
    return out
  def read(self,filename):
    env = Environment()
    BASE_DIR = "content/"
    TEMPLATE_DIR = BASE_DIR+"/".join(filename.split(BASE_DIR)[-1].split("/")[:-1])
    env.loader = FileSystemLoader(TEMPLATE_DIR)
    text = env.get_template(filename.split(TEMPLATE_DIR)[-1]).render()
    metadata = self.get_meta_data(text)
    text = ""+"".join(text.split("")[1:])
    return text, metadata

READERS = {
  'html': JinjaReader
}
Mon 01 February 2016

I recently decided to switch to Pelican as a static site generator for this blog. I chose pelican because I am very familiar with Python and would like to be able to add custom features. The first thing I wanted to do was render HTML templates using Jinja2. Luckily this can be done without hacking the core. I'll put the solution here. Feel free to hit me up on twitter with questions or even if you want the explanation better explained.

The simple solution is to add a custom reader. This can all be done inside the pelicanconf.py file of the project. Just extend the HTMLReader class to render the final result and add a setting to use this new class instead of HTMLReader


# Anywhere in pelicanconf.py
from pelican.readers import HTMLReader
from jinja2 import Template

class JinjaReader(HTMLReader):
  def read(self,filename):
    body, metadata = super(JinjaReader,self).read(filename)
    return Template(body).render(), metadata

READERS = {
  'html': JinjaReader
}
Fri 22 January 2016

Opening external links in new tabs, carousels, spamming visitors; as a developer there are many ideas that clients insist on that I am opposed to. But one of the more persistent one annoyances is a header bar with `position: fixed`. I am personally opposed to it because most users understand how to scroll up (they did scroll down, right?), and it takes up valuable screen space on mobile phones. So I decided to make a scroll header. Similar to angular or material design or the address bar in mobile chrome, the top nav of the site stays hidden until the user scrolls up. The header is slowly revealed until it is fully visible and then stays fixed as long as the user is scrolling up. When the user scrolls down again the header subtly disappears exactly as it would at the top of the page. I also made a live demo on jsfiddle if you prefer.


var header = document.querySelector("header");
var last_scroll = 0;
var header_y = -header.scrollHeight;
window.addEventListener("scroll",function() {
  var fixed = false;
  if (window.scrollY<2*header.scrollHeight) {
    //havent scrolled past header
    header_y = -header.scrollHeight;
  } else {
    header.className = "fixed"; // you may prefer header.classList.add("fixed")
    header_y = header_y - (window.scrollY-last_scroll);
    header_y = Math.min(header_y,0);
    header_y = Math.max(header_y,-header.scrollHeight);
    header.style.top = header_y + "px";
  }
  last_scroll = window.scrollY;
  if (window.scrollY == 0) {
    header.className = ""; // you may prefer header.classList.remove("fixed")
    header.style.top = 0;
  }
});

Here's the css I used. Really you can change whatever you want except the final line, so don't feel married to any of this.


body {
  padding-top: 50px;
}

header {
  background: white;
  left: 0;
  line-height: 50px;
  height: 50px;
  padding: 0 5px;
  position: absolute;
  right: 0;
  top:0;
}
/* This is the only crutial piece of css */
header.fixed { position: fixed; }
Sun 08 February 2015
I started making my own paint clone to run in the browser a few months ago, and despite the fact that it's definitely not ready for prime time I decided to push it to an externally visible url. The current instance is visible [here][1]. Of course the first step in building a project is naming the project, everything after that is just "coding it up". So I settled on "Yet Another Paint Clone" for now. Although quite a mouthful it abbreviates to "Why a PC?" The only reason I still use a PC is the Linux program [Kolourpaint][2]. Otherwise I have converted my workflow 100% to Chromebooks, so the cumbersome name is good for now. [1]: http://chriscauley.github.com/paint/ [2]: http://en.wikipedia.org/wiki/KolourPaint Screenshot of first release of my program Above is a screenshot illustrating many of the programs capabilities. Full current features are: * Open/Save images to localstorage * Save images as png (right click -> "save image as...") * Foreground/background colors (fully supported for fill, brush, circle, rectangle, and eye dropper) * Paint brush with custom size (unlabeled number input at bottom of tools) * Paint bucket (algorithm adopted from [William Malone's blog][3]) * Select tool (currently only for moving a selection around) * Rect and circle tool * Canvas resizer * Eye Dropper (color selector) [3]: http://www.williammalone.com/articles/html5-canvas-javascript-paint-bucket-tool/ That's about it for now. Hopefully I'll have a functional version with file IO and a more smooth interface by the end of February. Stay Tuned.
Fri 25 July 2014
I recently had to set up Twitter and Google authentication for a django project I worked on and found the documentation to be a bit lacking for [Python Social Auth][1], so I thought I would document a quick set up here for anyone who is interested. We will need all of the following settings: [1]: http://psa.matiasaguirre.net/docs/index.html

#Step 2
INSTALLED_APPS = (
  ...
  'social.apps.django_app.default',
)

TEMPLATE_CONTEXT_PROCESSORS = (
  ...
  'social.apps.django_app.context_processors.backends',
  'social.apps.django_app.context_processors.login_redirect',
)

# see step 2 for more info
AUTHENTICATION_BACKENDS = (
  'social.backends.facebook.FacebookOAuth2',
  'social.backends.google.GoogleOAuth2',
  'social.backends.twitter.TwitterOAuth',
  'django.contrib.auth.backends.ModelBackend',
)

#Step 3
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = ""
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = ""

#step 4
SOCIAL_AUTH_TWITTER_KEY = ""
SOCIAL_AUTH_TWITTER_SECRET = ""

#step 4
SOCIAL_AUTH_FACEBOOK_KEY = ""
SOCIAL_AUTH_FACEBOOK_SECRET = ""
1) `pip install python-social-auth` or what ever you prefer 2) Add all of the settings above and run `python manage.py syncdb` to set up the appropriate tables. I will only be talking about twitter and google, but there are dozens of other options [as seen in the docs][1] or on the [projects github page][2]. 3) Create a pair of Google OAuth keys: * Log into the google developer console here: [https://console.developers.google.com/project][3] * Create project, then click on project name. * Under APIs & AUTH, select APIs and enable the Google+ API * Under APIs & AUTH, click "Create new Client ID" * Select "Web application". If my domain is example.com I will enter in the following: [1]: http://psa.matiasaguirre.net/docs/index.html [2]: https://github.com/omab/python-social-auth [3]: https://console.developers.google.com/project

AUTHORIZED JAVASCRIPT ORIGINS
http://example.com

AUTHORIZED REDIRECT URI
http://example.com/complete/google-oauth2/

* I had no trouble with the above, but everything I read online said the above was the most tricky step. Verify the protocol (http vs https) domain, subdomain, port (none above, but my dev server is :8013) and trailing slashes. * Now You have keys! `SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET` is your "CLIENT SECRET" on the Googly Plus and `SOCIAL_AUTH_GOOGLE_OAUTH2_KEY` is your "CLIENT ID" 4) Create a pair of Twitter keys: * I found twitter super easy, but for completion sake... * Go to [https://apps.twitter.com/app/new][4] and fill in the forms. I used my raw domain (http://example.com) as my callback url and twitter did not seem to care. * Go to the API Keys tab * Put the key and the Secret in the corresponding settings fields as seen above. 5) Create a pair of facebook keys: * Go to [https://developers.facebook.com/apps/?action=create][5] and click the green “Create New App” button. * In the settings of the newly-created application, click “Add Platform”. From the options provided, choose Web, and fill in the URL of the site eg http://example.com * Copy the App ID and App Secret, and place them into settings.py file: [4]: https://apps.twitter.com/app/new [5]: https://developers.facebook.com/apps/?action=create

SOCIAL_AUTH_FACEBOOK_KEY = ""
SOCIAL_AUTH_FACEBOOK_SECRET = ""
6) Add the links to your header template. My full login section looks like this now:

    <li>
      <a href="{% url 'login' %}">
        <i class="fa fa-user"></i> Login with Username
      </a>
    </li>
    <li>
      <a href="{% url 'social:begin' 'google-oauth2' %}">
        <i class="fa fa-google-plus"></i> Login with Google+
      </a>
    </li>
    <li>
      <a href="{% url 'social:begin' 'twitter' %}">
        <i class="fa fa-twitter"></i> Login with Twitter
      </a>
    <li>
      <a href="{% url 'social:begin' 'facebook' %}">
        <i class="fa fa-facebook"></i> Login with Facebook
      </a>
    </li>
7) Add "pipelines" to settings: This is optional but I found that most of the customizations I wanted were already programmed in what python-social-auth calls "pipelines". Specifically I wanted 'social.pipeline.social_auth.associate_by_email', which will connect an account to a prexisting account if the email matches. This is not recommended if you do not trust the OAuth service to validate email addresses, but since I'm only using Google, Facebook, Twitter, and GitHub, I'm not so worried about it.

PIPELINE = (
  'social.pipeline.social_auth.social_details',
  'social.pipeline.social_auth.social_uid',
  'social.pipeline.social_auth.auth_allowed',
  'social.pipeline.social_auth.social_user',
  'social.pipeline.user.get_username',
  # 'social.pipeline.mail.mail_validation',
  'social.pipeline.social_auth.associate_by_email',
  'social.pipeline.user.create_user',
  'social.pipeline.social_auth.associate_user',
  'social.pipeline.social_auth.load_extra_data',
  'social.pipeline.user.user_details'
)
Wed 07 May 2014
# Dictionaries One of the most powerful data types in all of programming is the dictionary. Also known as a "linked-list" or "hash table" (or just object in javascript), the dictionary stores values according to keys. These both the keys and values can be any python object, but in practice they are limited to strings to avoid complications. Dictionaries are defined similar to lists in that they use commas to separate each key-value pair, however they use braces `\{}` instead of brackets `[]` and colons to link a key to a value. The general form is `\{key: value1, key2: value1 ...}`, but for clarity they are usually written on multiple lines.

>>> student_scores = {
        'chris': 10,
        'june': 20,
    }

>>> student_scores['chris']
10

>>> student_scores['chris'] = 15
>>> student_scores['chris']
15

>>> student_scores['tony'] = student_scores['chris'] + 10
>>> student_scores['tony']
25
If you want to iterate over student scores, the default iteration of a dictionary just cycles through they keys. It's important to remember that the orders of these keys is not fixed and that the order of a dictionary shifts to what is most efficiently accessed in RAM. Python provides a few convenient methods to iterate over values of a dictionary (with `dictionary.values()`) or key value pairs (with `dictionary.items()`).

>>> # the result of the following would be the same as `for score in dictionary.keys()`
>>> for name in student_scores:
       print name
chris
tony
june

>>> for name, score in student_scores.items():
       print name + " has " + str(score) + " points"
june has 10 points
tony has 25 points
chris has 15 points

>>> total = 0
    for score in student_scores.values():
       total = total + score

>>> average = total / 3
>>> average
16
# datetime Quite possibly the most tedious thing a programmer has to deal with on a daily basis is handling dates and times. Python provides the datetime library to created `date` or `time` or `datetime` objects. It also has a `timedelta` object which can be used find the difference between two of the afformentioned objects. We're going to focus only on `datetime` and `timedelta`.

>>> import datetime
>>> now = datetime.datetime.now() #1
>>> now
datetime.datetime(2014, 5, 7, 10, 51, 34, 712761)

>>> my_bday = datetime.datetime(1893,6,20) #2
>>> my_age = now - my_bday
>>> my_age
datetime.timedelta(11279, 39175, 182607)

>>> dir(my_age)
['__abs__', '__add__', '__class__', '__delattr__', '__div__', '__doc__', '__eq__', '__floordiv__',
 '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__',
 '__mul__', '__ne__', '__neg__', '__new__', '__nonzero__', '__pos__', '__radd__', '__rdiv__',
 '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmul__', '__rsub__', '__setattr__',
 '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'days', 'max', 'microseconds', 'min',
 'resolution', 'seconds', 'total_seconds']

>>> print my_age.total_seconds()
974544775.182607
This illustrates many important points: 1) `datetime.datetime.now()` returns a datetime object for the time it was instantiated. `datetime.date.today()` is a similar function returning a date. 2) datetimes and dates take in integers representing divisions of time in decreasing order. This is often times written as `datetime.datetime(year,month,date,[hour,[minute,[second,[microsecond]]]])`. Here the brackets on `[hour]` implies that it is optional (defaulting to 0, midnight, if not included). The brackets inside the brackets for `[hour,[minute,[second...]]]` implies that if minute is optional even with hour and so on. For this reason all of the following are the same: new years 1980.

datetime.datetime(1980,1,1)          # bare minimum required! year, month and day
datetime.datetime(1980,1,1,0)        # zero hour!
datetime.datetime(1980,1,1,0,0)      # zero minute
datetime.datetime(1980,1,1,0,0,0)    # zero second
datetime.datetime(1980,1,1,0,0,0,0)  # zero microsecond
## Exercises * Lincoln was in office from March 4, 1861 to April 15, 1865. How man days was this? * Write a function that returns the English day of week that a date occurs. You'll probably need `dir(some_datetime)` or a little google to figure this one out. # Classes and object oriented programming Object Oriented Programming (or OOP) is the practive of creating custom data types that interract with each other. Data stored as "attributes" and functions stored as "methods". In python "everything is an object", meaning that for every piece of data you can do a `dir(variable)` to get a list of the methods and propreties that a given variable has. Note that for every integer, `dir(some_int)` will be the same as any other integer. Any two strings also have identical methods and properties. That's because all integers are instances of the class `int`. All strings are instances of the class `str` By convention, classes are named WithCamelCase, capitalizing the letters of each word (annoyingly this rule does not apply to types, where int, str, datetime, type, and bool are not capitalized). A class is defined similary to a function.

import math

class Point():
    """
    A point in XYZ space that can be subtracted from other points to get distance
    """
    x = 0
    y = 0
    z = 0
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z
    def distance_to(self,second_point):
        if second_point.__class__ != self.__class__:
            raise TypeError("Method distance_to requires a second point as an argument")

        dx = self.x - second_point.x
        x2 = dx*dx

        dy = self.y - second_point.y
        y2 = dy*dy

        dz = self.z - second_point.z
        z2 = dz*dz

        return math.sqrt(x2 + y2 + z2)

origin = Point(0,0,0)

points = [
    Point(1,1,1),
    Point(1,2,3),
    Point(3,2,4),
    Point(0,0,1),
]

for point in points:
    print "Point is " + str(origin.distance_to(point)) + " from the origin"
Here the `class Point` is defined and it has properties x, y, and z and methods __init__ and distance_to. Note that __init__ is what is called when point is called to instanciate a new instance `Point(0,0,0)`. Also note that both methods have a hidden value passed into them, `self`, which is a reference to the point itself. This is useful because we can now make a new `class Sphere` that inherits from `Point`.

import math

class Point():
    """
    A point in XYZ space that can be subtracted from other points to get distance
    """
    x = 0
    y = 0
    z = 0
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z
    def distance_to(self,second_point):
        dx = self.x - second_point.x
        x2 = dx*dx

        dy = self.y - second_point.y
        y2 = dy*dy

        dz = self.z - second_point.z
        z2 = dz*dz

        return math.sqrt(x2 + y2 + z2)

class Sphere(Point):
    """
    A point with radius.
    """
    r = 0
    def __init__(self,x,y,z,r):
        super(Sphere,self).__init__(self,x,y,z)
        self.r = r
    def distance_to(self,second_sphere):
        center_distance = super(Sphere,self).distance_to(self,second_sphere)
        return center_distance - self.r - second_sphere.r
    def collides(self,second_sphere):
        return self.distance_to(second_sphere) < 0
Tue 29 April 2014
# 1 - for loops and lists While loops allow you to repeat a set of code over and over until a `break` statement is reached or until the conditional of the while loop is met. This can be used to cycle through individual items, but for convenience sake you can also use `for ... in ...:` syntax, which is known as a for loop.

print "entering loop"
for letter in "ABCDEFG":
    print letter

print "exiting loop"
The output of this would look like

entering loop
A
B
C
D
E
F
G
exiting loop
Just like with a while loop, the for loop repeats the indented code, but each time the code is repeated the value of the variable `letter` changes to the next letter in the sequence. In this case the sequence is a string so the items in the string are each character. Most types in python can be iterated in some way (integers cannot). A list is a series of python objects that can be iterated over. For example, part of a game of battleship might look something like this:

ship_positions = ['A1','A2','A3','G4','H4','I4','J4']
def check_guess(guess):
    for position in ship_positions:
        if guess == position:
            print "hit!"
            return True
    print "miss!"
    return False
Here a guess of 'H4' will first try 'A1'. Since they are not equal, the code inside the if statement will not execute and the for loop will repeat. When it gets to 'H4', it will `print "hit!"` and the function will exit when True is returned. The `print "miss!"` line will not execute because it returned before the for loop was completed. `guess("J5")` will try every value in `ship_positions` and when none match it will `print "miss!"` and `return False`. We could write a function to simplifie this simple behavior, but since this is common python provides the `in` operator (not to beconfused with `for ... in ...:`). The following is equivalent to the program above:

ship_positions = ['A1','A2','A3','G4','H4','I4','J4']
def check_guess(guess):
    if guess in ship_positions:
        print "hit!"
        return True
    print "miss!"
    return False
The above is a list of strings, but a list can be a mixture of any objects. In python we can use the `range(i)` function to create a list of numbers of length `i`. We can also use the function `len(variable)` to get the integer length of a variable. Note that range gives a list starting with 0, because this is usually programatically more convenient.

>>> word = "Constantinople"
>>> print "The word " + word + " is " + str(len(word)) + " letters long."
The word Constantinople is 14 letters long.
## Exercises 1. Write a program that will count to 100 by 5s (printing 0,5,10...100). There are many ways to solve this using what we've learned so far. 2. Save five names to a list. Print out the names. Then try to print the individual letters of each of the names (hint: you can put a loop inside a loop by indenting twice). 3. Range is very versitile in that it can take 1-3 arguments. Try each of the following. Can you deduce what range is doing with the extra arguments?

print range(1,10)
print range(1,20)
print range(0,20,2)
print range(0,105,5)
# 2 - A few string methods Last week we asked for a `raw_input` where we wanted a number. If the user enters an invalid value, then trying to turn the input into an integer results in a `ValueError`.

>>> some_number =raw_input("Enter a number: ")
Enter a number: a
>>> print some_number
a
>>> int(some_number)
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: 'a'
What we want is a function that checks to see if `some_number` is a number. As you can imagine, if there was a built in function for everything we could want to do for a string then it would be impossible to memorize all the built in functions and naming variables would become very difficult. Instead a string has a variety of "methods". Think of these as functions that automatically use the string as an argument.

>>> not_a_number = 'a'
>>> a_number = '1'
>>> not_a_number.isdigit()
False
>>> a_number.isdigit()
True
If there was a function `isdigit` you would write `isdigit(some_variable)`, but all strings have a method `isdigit` which determines if the string can be turned into an `int` and returns `True` or `False` accordingly. So we use the method on the string to tell if is a number by writting `some_variable.isdigit()` To see all of the methods of a string we can use the `dir` built in function, which prints a list of all possible methods of the variable. `dir` will always show the same thing for any two strings, but will return a different list of methods for a different type.

>>> print dir('a')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', 
'__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__',
'__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', 
'__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', 
'_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 
'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 
'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> print dir([1,2])
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', 
'__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__',
'__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
Looking at this we can see many useful methods for strings and lists. I'll briefly describe a few of these. We'll ignore the "magic methods" or those starting with underscores, "_". These are advanced and outside the scope of this class. Don't worry about memorizing this list just yet. This is mostly just to give you an idea of what each method can do.

>>> some_string = "This is a string"
>>> print some_string.lower()
this is a string
>>> print some_string.upper()
THIS IS A STRING
>>> print some_string.title()
This Is A String
>>> print some_string.startswith('t')
False
>>> print some_string.startswith('T')
True
>>> print some_string.lower().startswith('t')
True
>>> print some_string
this is a string
And now their definitions: * `str.lower()` - return the string with all letters lowercase. * `str.upper()` - return the string with all letters uppercase. * `str.title()` - return the string with the first letter of every word capitalized. * `str.startswith(string)` - takes in a string as an argument and returns `True` or `False` depending on whether or not the string starts with the string argument. * `some_string.lower().startswith('t')` - This shows that you can "chain" methods together. Because `str.lower()` returns a string, you can apply `.startswith('t')` to the result. * The last line is to illustrate that the string has not changed And now some `list` methods:

>>> a_list = range(3)
>>> print a_list
[0,1,2]
>>> a_list.append("monkey")
>>> print a_list
[0,1,2,"monkey"]
>>> a_list.insert(1,666)
>>> print a_list
[0,666,1,2,"monkey"]
>>> a_list.sort()
>>> print a_list
[0,1,2,666,"monkey"]
And now the definitions: * `list.append(variable)` - adds the variable to the end of the list. This increases the length of the list by one. * `list.insert(position,variable)` - inserts the variable at the position. This will increase the length of the list by one. * `list.sort()` - sorts the list. * Notice that neither of these return a value. Instead the variable `a_list` itself is changed. This is very different then the methods of a string. If you want to keep the original list, you must save it as a different variable.

def number_input(prompt):
    value = raw_input(prompt)
    while not value.isdigit():
        value = raw_input("Sorry, the value must be a whole number ")
    return int(value)
# 3 - Hangman! And now, two days into the class, we finally have all to tools to write a somewhat interesting program. This is going to consist of two files, a library of functions we'll use and a program that uses those tools to play hangman. Let's start with the latter, a file we'll call `hangman.py`.

from utils import *
word = get_random_word()
error_count = 0
correct_letters = ''
wrong_letters = ''
guessed_letters = ''
win = False

welcome_user()

while error_count < 6:
    draw_board(error_count,word,guessed_letters)
    guess = get_guess(guessed_letters)
    guessed_letters = guessed_letters + guess
    if guess in word:
        correct_letters = correct_letters + guess
    if not guess in word:
        wrong_letters = wrong_letters + guess
        error_count = error_count + 1
    if check_word(correct_letters,word):
        win = True
        break

print_message(win,word)
This imports from various functions from `utils.py`.

import random
import os
from var import word_list, HANGMAN_PICS

def get_random_word():
    return random.choice(word_list).lower()

def welcome_user():
    print "H A N G M A N\n\n"
    print "Welcome to hangman! Guess the word one letter at a time before you are hung."
    print "You can make 6 mistakes before you are hung."

def draw_board(error_count,word,guessed_letters):
    os.system('clear')
    print HANGMAN_PICS[error_count]
    word_string = ""
    for letter in word:
        if letter in guessed_letters:
            word_string = word_string + letter
        if not letter in guessed_letters:
            word_string = word_string + "_"
        word_string = word_string + " "
    print word_string
    print "\nYou have " + str(6-error_count) + " guesses remaining."

def get_guess(guessed_letters):
    while True:
        guess = raw_input("Pick a letter: ").lower()
        if len(guess) > 1:
            print "Please only pick one letter"
            continue
        if guess in guessed_letters:
            print "You already guessed " + guess
            print "Please choose a letter other than these ones:"
            print guessed_letters
            continue
        if not guess in "abcdefghijklmnopqrstuvwxyz":
            print "You should only pick letters."
            continue
        return guess

def check_word(guessed_letters,word):
    for letter in word:
        if not letter in guessed_letters:
            return False
    return True

def print_message(win,word):
    print "\n============\n"
    if win:
        print "Good job, you guessed the word!"
        print "It was '" + word + "'. Remember this word, it saved your life!"
    if not win:
        print "Sorry, you did not guess the word, so we had to strangle you to death."
        print "That sucks."
        print "The word was '" + word + "'. I'll write it on your tombstone."
Which uses a few very long but boring variables I moved to `var.py`.

word_list = ['ant', 'baboon', 'badger', 'bat', 'bear', 'beaver', 'camel', 'cat', 'clam', 'cobra', 'cougar', 'coyote', 'crow', 'deer', 'dog', 'donkey', 'duck', 'eagle', 'ferret', 'fox', 'frog', 'goat', 'goose', 'hawk', 'lion', 'lizard', 'llama', 'mole', 'monkey', 'moose', 'mouse', 'mule', 'newt', 'otter', 'owl', 'panda', 'parrot', 'pigeon', 'python', 'rabbit', 'ram', 'rat', 'raven', 'rhino', 'salmon', 'seal', 'shark', 'sheep', 'skunk', 'sloth', 'snake', 'spider', 'stork', 'swan', 'tiger', 'toad', 'trout', 'turkey', 'turtle', 'weasel', 'whale', 'wolf', 'wombat', 'zebra']
HANGMAN_PICS = ['''

  +---+
  |   |
      |
      |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''

  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========''']
Sat 19 April 2014
Pure CSS Golden Rectangle The [golden ratio](http://en.wikipedia.org/wiki/Golden_rectangle "Wikipedia: Golden Rectangle") has long fascinated mankind because blah blah blah... And the [golden rectangle](http://en.wikipedia.org/wiki/Golden_rectangle "Wikipedia: Golden Rectangle") has aesthetic properties because of yadda yadda yadda... If you don't already know about this magical number, I'm not the person to educate you. Trust me, it's cool. About a year ago I decided to create the golden rectangle in pure CSS as a way to learn about inheritance and to prepare myself to create more complex fractals in CSS/HTML. The golden rectangle has sides with a ratio of 1.618... which is special because, if you divide the rectangle into a square and another rectangle, the sides of the inner rectangle has the same ratio as the outer rectangle. It is made by repeating the same rectangle scaled down, rotated, and embedded into itself over and over. So we start with embedded divs, the first of which has a set size and the remaining are 62% (1/1.618x100%) the size to its parent div.

#golden1 > div {
  height: 191px;
  left: 0;
  position: relative;
  width: 309px;
}

#golden1 div {
  background: rgba(255,255,255,0.1);
  outline: 1px black solid;
}

#golden1 div > div {
  height: 61.8%;
  width: 61.8%;
  z-index: 100;
}    

<div id="golden1">
  <div>\\{ ... \\}</div> <!-- One unit cell -->
</div>
    

Then the child divs are placed at the top right corner, outside of the parent div using absolute positioning. The children are then rotated a quarter turn to create the golden rectangle. If you hover over any of the rectangles in the following figure, the :hover pseudo class will rotate the child and all of it's ancestor divs. This forms the golden rectangle.


#golden2 { height: 100%; overflow: hidden; width: 100%; }
#golden2 > div {
  height: 191px;
  left: 0;
  position: relative;
  width: 309px;
}

#golden2 div {
  background: #999;
  outline: 1px black solid;
}

#golden2 div > div {
  height: 61.8%;
  left: 100%;
  position: absolute;
  -webkit-transform: rotate(0deg);
  -webkit-transform-origin: top left;
  -webkit-transition: -webkit-transform ease-in 1s;
  transform: rotate(0deg);
  transform-origin: top left;
  transition: transform ease-in 1s;
  top: 0;
  width: 61.8%;
  z-index: 100;
}

#golden2 div:hover {
  background: #FFc;
}

#golden2 div:hover > div {
  -webkit-transform: rotate(90deg);
  transform: rotate(90deg);
}    

<div id="golden2">
  <div>\\{ ... \\}</div> <!-- One unit cell -->
</div>
    
Next, :before (circle) and :after (background) elements are added to create colors. This creates the golden spiral. In the final product, all squares inside the golden rectangle are set to the same colors (red, blue, and yellow), which is then hue rotated to product a unique set of colors at each level. The hue rotation adds up as you go down the DOM tree, creating a wide array of colors with only 3 color declarations. In this example, if you hover over a div it will remove hue-rotate for all child divs.

#golden3 {
  height: 371px;
  left: 0;
  position: relative;
  width: 600px;
}
@media (max-width: 980px) {
  #golden3 {
    height: 290px;
    width: 470px;
  }
}
@media (max-width: 530px) {
  #golden3 {
    height: 160px;
    width: 258px;
  }
}
#golden3 div > div {
  -webkit-filter: invert(1) hue-rotate(72deg);
  filter: invert(1) hue-rotate(72deg);
}
#golden3 div > div {
  height: 61.8%;
  left: 100%;
  position: absolute;
  -webkit-transform: rotate(90deg);
  transform: rotate(90deg);
  -webkit-transform-origin: top left;
  transform-origin: top left;
  top: 0;
  width: 61.8%;
  z-index: 100;
}
#golden3 div:before,
#golden3 div:after {
  content: "";
  display: block;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
}
#golden3 div:before {
  background: #ffff00;
  border-radius: 100% 0 0 0;
  box-shadow: inset 12px 0px 15px #0000ff;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  width: 61.8%;
  z-index: 2;
}
#golden3 div:after {
  background: #ff0000;
  width: 100%;
  z-index: 1;
}
#golden3 div:hover div:not(:hover) {
  -webkit-filter: hue-rotate(0deg);
  filter: hue-rotate(0deg);
}    

<div id="golden3">
  <div>\\{ ... \\}</div> <!-- One unit cell -->
</div>
    
Sat 19 April 2014
I missed out on the [April Recreational Programming Group](http://txrxlabs.org/blog/smcameron/recreational-computer-programming-group-april-2014/) because I was at PyCon. He presented on a really cool texture genreator. It's written in Processing so I decided to see how easy it is to run it using [processing.js](http://processingjs.org/). TL;DR - Really easy. The only necessary change I had to make to the code was to add a note to preload the image. Normally processing will execute assuming that the image file is local, but the DOM hasn't yet loaded the image. To do this you just add a comment to preload the image:

/* @pjs preload="13940260644_7fe66ea59c_c.jpg" */;
String source_image_file = "13940260644_7fe66ea59c_c.jpg";
int xdim = 300;//1400;
int ydim = 300;//700;
int nparticles = 50000;
I also resized it and changed the image. I wanted to add the ability to input an image url via a text field and so that any visitors can change the image. This, it turns out isn't possible. The preload string cannot use a javascript variable. Also since the image is loaded via ajax, cross site scripting considerations prevent it. I could do this using a django app that would dynamically rewrite the pde file, but I don't want to host a place for people to randomly upload images. If Steve is impressed with this I might do it, bu it hardly seems worth booting up a VPS. Also I added a button for freezing the image so that you can easily save the image. I might eventually create a txrxlabs.org subdomain for hosting this and other projects, but for now this is all I'm doing:

Tue 15 April 2014
## 0 - Introduction ### Why we program * Humans make mistakes when repeating simple actions, computers do not. Computers also do these things much more quickly than we can. * Smarter people have solved problems, computers give us access to those solutions. * Once you write a program, you can pass it onto others (or your future self). ### Why python * Very readable, very "human friendly". * Batteries included (common problems are already solved in advance). * Strong community (others solve problems so you do not have to). * Open source is amazing. * Object oriented, customizable. Much of the material here is lifted from [Invent Your Own Computer Games with Python](http://inventwithpython.com/chapters/) and if you are lost more detailed explanations can be found there. You will want to install python 2.7.6 for windows (first link [here](https://www.python.org/downloads/windows/) ) or type `python` in a mac or Linux terminal to get started. # 1 - Math and Variables ## Integers Open the interactive prompt and type `2+2`. Python evaluates this expression and prints the result on the line below like this:

>>> 2+2
4
If you do not see the `>>>` characters then you are most likely in the editor not the prompt. In python, arithmatic uses the following operators:
2+2addition
2-2subtraction
2*2multiplication
2/2division
Order of operations is the same in python as in math, evaluating from left to right, parentheses first, then multiplication and division followed by addition and subtraction. Try these in your prompt and feel free to make up your own.

>>> 2+2+2+2+2
10

>>> 3*10 + 2
32

>>> 2 *  8+1
17

>>> 2 * (8+1)
18
As you can see, the spacing does not matter when writing these expressions. Typically one space is put between every number and operator so that the code is easy to read, but this is not a requirement. The only rule (for now) on spacing is that you can not add spacing to the begining of the line. We will explain this as the class goes on. ### Excercises Try each of the following by typing them into the interpreter. 1. 6+4*10 2. (6+4)*10 (Compare this to #1, and note that Python uses parentheses just like you would in normal math to determine order of operations!) ## Variables Computers store values in memory for later usage. In order for humans to reference values and remeber what they represent, we name the values. Try the following:

>>> 2+2
4

>>> count = 2+2
>>>
Notice that the in the second line, the `4` was not printed afterwards. This is because the interactive prompt stored it as the variable `count`. If you do not store it as a variable, the prompt assumes that you want to see the answer (otherwise the value is lost and typing `2+2` accomplishes nothing). `count` now has a value of `4` and can be used anywhere a number can be used.

>>> count
4

>>> count + 1
5

>>> count * 1000 + 300
4300

>>> new_count = count * 2
>>> new_count
10

>>> count = count + 1
>>> count
5

>>> new_count
10
The last few lines are very important. Unlike the value of `4` or `9` or `8675309`, the value of `count` is not fixed. It can be modified as needed. It can also be used to create new variables, but once the value of `new_count` is created, modifying `count` has no affect on `new_count`. Variable names can any combination of letters, numbers and underscores as long as the first character is NOT a number. Other characters (spaces, periods, etc) cannot be used as variable names. ### Exercise What is the value of x after entering in the following lines? Try to figure it out in your head before trying it in the interpreter.

x = 1
y = 2
z = x + y
x = y + 2
z = y * 5
x = 4
y = x * z + 15
# 2 - Strings In python, any series of characters surrounded by quotation marks or apostrophes is considered a string. Strings can be added with the `+` operator, and for strings this is called "concatenation". Here are some examples of how strings and integers interact.

>>> name = "Chris"
>>> print("Hello" + name) #1
HelloChris

>>> print("Hello " + name + ". How are you?")
Hello Chris. How are you?

>>> print("one\ttwo\tthree\n1\t\2\t3") #2
one     two     three
1       2       3

>>> people_in_car = 4
>>> print("There are " + people_in_car + " people in the car.") #3
Traceback (most recent call last):
  File "", line 1, in 
TypeError: cannot concatenate 'str' and 'int' objects

>>> print("There are " + str(people_in_car) + " people in the car.") #4
There are 4 people in the car.

>>> print(1 + int("2"))
3

>>> print(str(1) + "2")
12

>>> int("two") #5
Traceback (most recent call last):
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: 'two'
There are several important things here. First off the comment. Any code after a `#` is ignored by python. This allows you to leave notes for humans to read. It is used above to connect lines of code to these notes: 1) You strings are added together EXACTLY as they are typed. If you want to have spaces, you must specify them. Also note the print function. Basically anything in side the parenthesis after `print` is displayed to the user. This will become very important once we start writing programs. 2) Certain characters that can not be typed can be make with escape characters. This is backslash followed by the escape character. Here we use `\t` for a tab and `\n` for a line break. Other important characters are `\"` and `\'` which allow you to put a quote or an apostrophe in a string and `\\` which represents a literal backslash. 3) In Python you cannot add strings and integers together. You can in some languages, but in Python it will raise a `TypeError` meaning you tried to do something with the wrong `type` of variable. 4) `str(some_int)` and `int(some_str)` will convert integers and strings to strings and integers respectively. For this reason `int` and `str` are reserved words and you cannot name a variable with these names. 5) Some strings cannot be converted to integers. These will raise a `VauleError` because a bad value was provided. ### Exercises: 1. Create a string with an apostrophe, such as: I can not figure out this problem 2. Create a string with both single and double quotes in the string. 3. Try to figure out each of the following before typing them in

'one plus one is ' + '1' + '1'

'Na na ' * 8 + 'batman!'

'I' + 'love' + 'bees'
4. What is wrong with the following example:

brothers_age = 21
my_age = 23
print("I am " + my_age - brothers_age + " years older than my brother.")
#3 - The `raw_input` Function Another `type` in python is the function. A function takes in any number of arguments (variables passed into the function) and returns a value. You have already seen two functions above, the `int` and `str` functions that take in any type and returns a new variable corresponding to the type you asked for. The `raw_input(some_string)` function prints the argument you give it and then waits for the user to enter in any code via the keyboard. When the user hits enter, `raw_input` then returns the value entered in as a string.

>>> name = raw_input("Type your name and press enter: ") #1
Type your name and press enter: Chris

>>> print("Hello " + name + "! I hope you are feeling well.")
Hello Chris! I hope you are feeling well.

>>> age = raw_input("How old are you? ")
How old are you? 30

>>> seconds = int(age) * 365 * 24 * 60 * 60 #2
>>> print("That's " + str(seconds) + " seconds. Make every one count!")
1) I copied and pasted this from my python terminal so this is how it should look AFTER someone types in "Chris" and presses enter. 2) Note that types need to be converted back and forth as you go from concatenating strings to integer arithmatic. #4 Guess the number We now going to write a program called "Guess the number". It is best to write this in the editor and use the run option from the menu (if you are in IDLE) because unlike the above examples, this is a multi-line program. Guess the number has the following steps: 1) pick a random number 2) ask the user for a guess 3) compare their guess to our random number 4) if they guessed the right number, congratulate them 5) if not, repeat from step 2 Here is the full program we will use (copied directly from the source material, chapter 4). Feel free to paste this into your editor as is to save on typing.

# This is a guess the number game.
import random #4.1

print('Hello! What is your name?')
my_name = raw_input()
guesses_taken = 0 
number = random.randint(1, 20) #4.2
print('Well, ' + my_name + ', I am thinking of a number between 1 and 20.')

while True: #4.3
    print('Take a guess.') # There are four spaces in front of print.
    guess = raw_input()
    guess = int(guess)

    if guess > 20: #4.4
        print("Bad guess, keep it below 20")
        continue

    if guess < 1:
        print("The number must be greater than 1, try again")
        continue

    guesses_taken = guesses_taken + 1

    if guess < number: 
        print('Your guess is too low.') # There are eight spaces in front of print.

    if guess > number:
        print('Your guess is too high.')

    if guess == number:
        print('You got it!')
        break

    if guesses_taken > 5:
        print("You're all out of guesses")
        break

if guess == number:
    guesses_taken = str(guesses_taken)
    congrats = 'Good job, ' + my_name + '! You guessed my number in ' + guesses_taken + ' guess'
    if guesses_taken > 1:
        congrats = congrats + "es"
    print(congrats + "!")
else:
    number = str(number)
    print('The number I was thinking of was ' + number)
There is a lot to cover here, so I will break it into sub sections. ### 4.1 - `import` Statements If you had to write everything in one file, programming would become very tedious very quickly. In python, you can pull in code from other programs with import. Here you are importing a full module with `import module_name`. This imports an entire module of code that can be accessed by the module name followed by a period and then the name of the variable inside that module you want to access. You can also import only individual variables with the following syntax:

import random
number_1 = random.randint(0,20) # returns a random variable between zero and 20

from random import randint
number_2 = randint(0,20) # same as above, though not necessarily the same number
In various circumstances it is better to do this one way or another. Generally, if you want to import one or two things from a module you use `from module import var1, var2...` while if you want to import a lot of things you will use `import module`. ### 4.2 - The `random` module Python is described as "batteries included" because many of the basic operations of programming are included in the default library. If you want to learn more about any given module, I recommend the [Python Module of the Week](http://pymotw.com/2/contents.html) blog over the official documention. A few useful functions found in random include: * `random.random()` - returns a random number between zero and one. * `random.randint(min_value,max_value)` - returns a random integer between the values given * `random.choice(sequence)` - returns a random value from any sequence. Right now we only know strings, but there are many other data types that can be used. Some other great builtin libraries are: * `datetime` - a module used to handle dates, times, and datetimes (combination of the two). * `sys` and `os` - modules for controling the computer that the program is running on (file structure manipulation and accessing other programs) * `urllib` and `urllib2` - handle http connections with python * `math` - advanced math functions ### 4.3 - `while` Statements Programming relies heavily on flow control - the ability to move between parts of a program. In olden days, this would be "GOTO LINE 34", but in python and most modern languages we use programming blocks. The `while` keyword tells python to execute the programming block continuously as long as the condition is `True`. For example, this will repeat forever since `True` is always `True`.

while True:
    print("This will never stop!")

print("This will never happen")
The first print command is inside the while loop because it is indented 4 spaces (other languages usually wrap this code in braces, `{}`). Because the part between the `while` and the colon is the conditional. Since `True` is always `True`, it never stops! In the our "Guess the number" game, `guesses_taken` starts out as 0 and gets larger by 1 every time the program loops. At the end of the first loop, it goes up to the top of the while loop and repeats until `guesses_taken` is equal to 6. The other way to stop a `while` loop is with the keyword `break`, which terminates the code exactly where it is used whether or not the conditional is `False` ### 4.4 - `if` Statements Another type of programming block is the `if` statement. Just like the `while` statement, `if` starts takes in a conditional, followed by a conditional and a colon. Any code indented after `if conditional:` is inside the block. Since we re already in a while loop, the `if` block is indented 8 spaces instead of 4.

if True:
    print("This will always print")

if False:
    print("This will never print")

my_variable = random.randint(0,1)
if my_variable == 1:
    print("This will print half of the time")
## Conditionals and Booleans `True` and `False` are the only two members of the type `bool`. In python, when you use any variable or expression as a conditional, it is converted to booleans. For example the following are equavalent:

students = 16
if students:
    print("There are students")

if bool(students):
    print("There are not students")
Here you can see that 16 is considered `True` as far as conditionals are concerned. For integers, any integer except 0 will be considered `True`. For strings, any string except an empty string, `""`, is considered `True`. Values can be compared using a number of boolean operators. All of the following examples evaluate as `True`.
OperatorExampleHow Example is Read
>4 > 2"Four is greater than two"
<1 < 2"Two is less than Four"
== 2 == 2"Two is equal to two"
== 2 != 1"Two is not equal to one"
These operators can be used with almost any data type, but in practice only equality and in equality are terribly useful for strings.

# Ask the user for a password and 
password = "my_secret1!1"
password2 = raw_input("What's the password: ")
if password2 == password:
    print("Correct!")
if password2 != password:
    print("Fail!")
## Functions A function is a mini-program within a program. We have already seen the funciton `raw_input()` and `int()` and `str()`. Each of these take in one argument and return an argument. Writing your own functions can simplify code and make programming much less repetative. For example, we know how to use `raw_input()` and `int()` to get a number from a user and turn it into an integer instead of a string. We can turn this into a new function as follows:

def square(number):
    return number*number

def number_input(prompt):
    number = raw_input(prompt)
    return int(number)
The value in parenthesis is called the argument of a funciton. Each of the above functions have one argument, but a function can have as many arguments as desired.

def bigger_of_two(a,b):
    if a > b:
        return a
    return b

def display_welcome():
    print("Welcome to my program.")
Notice that in the `bigger_of_two` function there is no `if b < a` necessary. This is because if `a` is larger than `b`, the function `return a`, thus immediately exiting the program. Even if the `return` is inside of a `while` loop or multiple `if` statements, the `return` will cause the function to close. Also note that the `display_welcome` program does not have a `return` statement. When the indentation ends, the funciton automatically terminates returning `None`. ## Exercises 1. Write an `is_even(number)` function that returns `True` if a number is divisible by 2 and `False` if it is not. 2. For the super lazy, write an `is_odd(number)` function that uses the above function to tell if a number is NOT divisible by 2. 3. Write an `is_any_odd(some_list)` function that returns `True` if it finds any odd numbers in a list. 4. Write a `check_sum(some_string,digit)` function that does the following: - cycle through a string, add all numbers (individual digits) in the string together. - ignore any non numeric numbers. - `return True` if the last digit in the sum of all numbers is equal to the digit argument (hint: use `last_digit = my_sum%10`) - Otherwise `return False`.
Wed 12 March 2014
#serpinski-triangle {
  background: #EEEE00;
  height: 300px !important;
  margin: 0 auto;
  overflow: hidden;
  position: relative;
  width: 300px !important;
}
#serpinski-triangle div {
  height: 50%;
  float: left;
  overflow: hidden;
  position: relative;
  width: 50%;
}
#serpinski-triangle:before, #serpinski-triangle div:before {
  background: black;
  bottom: 0;
  content:"";
  display: block;
  height: 141.421356237%;
  left: 0;
  position: absolute;
  width: 70.710678118%;
  -webkit-transform: rotate(45deg);
  -webkit-transform-origin: 0 100%;
}
<div id="serpinski">
  <div>
    <div> ... </div> <!--               -->
    <div> ... </div> <!-- One unit cell -->
    <div> ... </div> <!--               -->
  </div>
</div>
A pure css Serpinski Triangle I made. The each unit cell has three divs, and to extend the fractal one level you just add three more divs in each empty div. Each div is `width: 50%; height: 50%;` of the parent div. The divs are then floated, making a square with three squares inside of it, and the forth quadrant is empty. Normally pure css trangles are made using elements with `width: 0; height: 0` and a border with asymetrick coloring. If you are unfamiliar with this technique, you can read more at [CSS Tricks](http://css-tricks.com/snippets/css/css-triangle/ "Pure CSS Triangle"). However, because borders can't be percentages, this doesn't work with fractals. Instead we use a square, rotated pseudo elements (the `div:before` in the above css). The parent of the pseudo element is overflow hidden. Here's the full CSS. Feel free to email me if you want to know more. I may post more on this later.