Wednesday, February 10, 2016

w5d3 - Django, and the perils of paint-by-numbers

Today was more Django. I wish I could say it was enlightening, but it's still mostly cut, paste, and pray.  We're working on a super-simplistic ecommerce site with several pages of pseudo products. My only real extension was working on adding images to pages via templating, with each product associated with a particular picture.  I got all the elements working ok (a links field added to the model, images in the static files folder, but I just could not figure out the templating syntax.  Eventually, with an instructors help, I was able to get the images working.

Perhaps more interestingly, I looked into the python scripts that comprise Django. Holy spiderweb, batman! Every module references several other modules.  I had some idea of trying to unravel the underpinnings of Django,but I'm not sure that's reasonable in one human life time.  Instead, I think I will try to work out how the render function works, and especially how it parses the templating script.


All of this section makes me very uncomfortable.  Python was just feeling reasonably comfortable.  Even if I didn't know how to make something work, I understood enough to ask google for help in an intelligent way.  So much of Django is just magic so far.  I often don't even know  how to formulate a searchable question.  Hopefully, familiarity through repetition will make the framework more approachable.

Tuesday, February 9, 2016

w5d2 - git

So, yes, we did cover the basic git intro today.  After several tutorials online and today's class, I feel I'm getting the hang of it.

Honestly, the concept is pretty simple.  I get the idea of version control.  I even get the idea of branching, pulling from a repository, pushing, etc.  I could, do local commits since the beginning of class, a month ago, thanks to code academy and others.

The information that was missing, and that I'm still not 100% sure on, is "git best practices".  It was never clear from the tutorials that renaming a file would screw up your git commit history.  Renaming files is standard practice in most of the world, as is moving a file while reorganizing content.  With git, though, those things are REALLY BIG DEALS.  Yes, there are work-arounds, but it's just another layer of complexity at this point.

Some day, when I really understand how things work, I'll come back to this idea and write my own tutorial just on 'best practices'.  As I understand them now:

1) One project per (hard drive) folder.  Each project may contain multiple files.
2) One folder to one github repository.
3) Pick descriptive files names at the start, and stick with them.
4) Use git version control rather than renaming files to roll back changes as needed.
5)  Commit only code that is functional, since each commit could potentially be a roll-back point.  Getting broken code from a rollback makes it harder to deal with bugs that arose subsequent to that commit.
6) There are plenty of instructions available for generating ssh keys, and for walking newbies through the establishment of a new repository.  There's not enough on the care of ssh keys and the consequences of screwing up your passphrase.

I think it's all working ok now, though.

One interesting thing I discovered:

In the process of playing with git, I was looking back over older projects.  Early in the first week, I wrote a module that would print out (to the terminal) the names of variables discovered via dir(), with the magic variables removed for clarity.  the script would also print out the type of each variable and its value (via eval(var) - unsafe in settings where strangers can access the code, but probably ok if you're using it for internal debugging).

The point of the table was to illustrate a point made in class about following the variables in your code.  I suppose it's not terribly useful at this point...

The reason I brought it up, though, is that I managed to refactor 4 functions into 4 lines of code with, probably, a gain in clarity.  The "variable_printer.py" script has both the old and new versions, along with instructions for use.

Hooray for refactoring!

w5d2 - git, finally. And some refactoring.

20160206_173651 We had a long weekend in the center of Costa Rica, near Arenal. My plant-obsessed photos are here.  It was a magnificent experience, and a welcome respite from the unrelenting heat and brown foliage of Guanacaste. It was also a welcome chance to rest my brain after the feast of the first 4 weeks.

On returning, I managed to finish my refactoring of the Blackjack game from Week 3.  Because what else would you do after 5 hours of driving across Costa Rica?  A playable demo is here.  The github is here.

On Jeremy's (one instructor) advice, I reworked the play-handling such that each turn was handled by a method in the Game class, rather than passing the dealer's hand to a method in each player instance.  As Jeremy pointed out, you really don't want classes on the same organizational level talking to each other directly.  I also cleaned up a lot of detritus and cleaned up some variables (i.e. temporary variables used only within a particular method don't need to be 'self'd.), swapped out a few for iterators for list comprehensions, etc.

The other big changes were to add betting game play (with blackjacks handled appropriately), the ability to add or remove players after each round (and even to sit out a round, then come back in).  I also built a new function for my 'entry validation' module that refuses to accept an answer that is in a list.  (If you're adding a player, you don't want to have duplicate names.)  My existing validation functions only checked whether an entry was in a list of acceptable answers.  Also, it now uses a 6-deck shoe that gets restored when it reaches 75% used.  Take that, card counters!

The game still doesn't handle doubling bets, insurance, or splitting a hand.  Splitting a hand would be the hardest to add since the Player class is currently configured to hold only one hand per instance.  To split hands, I would have to make each player have an array of Hand instances (analogous to how the Game instance has an array of player instances).  All of the player Hand methods would have to be updated to "for hand in player.hands: <do thing>".  Maybe there's an easier way, but I can't see it right now. I need to focus on the Django projects we're working on now, so I'll leave Blackjack as-is.

To be fair, it's in pretty good shape, and I'm reasonably happy with it.

Thursday, February 4, 2016

w4d4- half way

I've officially been at GoCode for 4 weeks now.  It seems impossible that it's been so long.  I'm both blown away by how much I've improved, and appalled at how far there is still to go.

We kept working with django today, reviewing the basic MVC architecture and how we can use python to manage the pieces.  The most interesting, and most difficult, thing we learned was the django template formatting, and the use of templates to integrate content drawn from a database.

My personal victory today was figuring out how to pull data from two tables in the app-associated database and to get chosen bits to show up in the same page.  The pseudo-python of the templating language led me to believe that I could manipulate it in ways that it just couldn't work.

My other discovery was finding the source code for python modules.  I really enjoyed reading such high quality work.  I want to get to the place where I can follow and appreciate what each part is doing.

I also got the blackjack game working, with money bets.  I have a few more tweaks, and I should be ready to show it off.

This midterm weekend is for travel.  I'll be away tomorrow and monday.  No blog, alas.  I look forward to seeing what the second half of the class brings.

w4d3 - Ironically, we built a blog using Django today. Also refactoring hell.

In our first day of working with Django, we built a blog.  It's not really useful, of course, and it just runs off a local host, but...it works!

Part of the project was learning the MVC (Model View Controller) scheme. We used some basic regex to detect the url request (/home, /about, /blog, /blog/page1, etc), served up an html template formatted with info pulled from a freshly-made sqlite database.

I won't lie - it's pretty exciting to see all the pieces I've been working on for months coming together.  I like seeing how a framework operates, too.  I want to dig into the django modules and see exactly what each piece is doing.

After working on the basic web stuff all day, though, (and building a blog once in code-along, and once from notes), I went back to refactor my blackjack game from last week.  I've added betting to the game, and greatly simplified the structure to make sure class instances are not interacting directly (i.e. the dealer's hand object had been passed from the game.play() method to each player in turn to evaluate win/loss/push).  Of course, changing so much broke a ton of things and I've been hours in fixing it.  I see why people hate refactoring.  It's just a few hundred lines long, but there's so much to keep track of.

In a side note, I've been working on learning shortcuts in the text editor to speed things up.  Today I figured out how to set bookmarks so I didn't have to scroll past walls of text every time I wanted to look another function up.  I find that using bookmarks keeps my attention focused much better.

Speaking of which, I failed, again, at an early bed time.  Soon, perhaps, I can port this blog to a site of my own devising.

Tuesday, February 2, 2016

w4d2 - API, SQL and python

I love how we're integrating different elements now.  The project today was to use python and the Open Weather api to get a 16-day forecast for a city, to take the resulting json-formatted data and push it to an sqlite database we initialized.We're still at the super basic level and dealing with canned scenarios, but I can see the pieces interacting.

It's also really fun (is that word I want here?  I'm sticking with it) to be able to have python interact with the world beyond my computer.  Almost everything I've done so far has run off text files or output to the terminal.  Now I can request information directly from the web, and push to a local database.

The 'extension' project was to build a python script that would ask a user for city and use their answer to query Open Weather for a forecast, then put that into the sql database.  Not too challenging by itself.  A step deeper, though, and I was looking through the documentation for how queries in the Open Weather api are structured.  It's a whole mini-language hiding in almost plain site in the url!

I'd always known the extra long URLs that look like random gibberish must hold some meaning, but I'm getting an idea of just how much information is packed into URLs.  Yesterday's toy server essentially replicated a directory tree in how web pages were stored and accessed.  Every word or character in the url had a counterpart in the directory tree the information was pulled from.

As part of my own investigations, I found a 20 MB file correlating the numeric code Open Weather uses to represent each weather station in their network.  It's 209,000 lines of text!  Small by many measures, but huge for me.  Opening it and using it required finding the json module for python, then porting the info to my sqlite database.  Not too difficult, once I found all the pieces I needed.

The harder realization was that there are multiple entries for cities.  Some entries refer to different weather stations in the same city, while others refer to cities of the same name in disparate places. (Paris, Texas!).  There are country codes in the data set to narrow the options some, but the codes are simple two-letter abbreviations.

Next step: a lookup table for code/country name.  Getting the code into python was pretty easy, but getting the data into SQL was impossible due to utf-8 conflicts with module (I think).  StackOverflow searches took me to some info on converting utf-8 to ASCII.  I can make it work, but information is lost as non-ASCII characters in country names are stripped. Eventually, I decided to just let it rest for now.  I can add unicode to the long list of things to investigate further.

I did manage to get the project working, and now it's once again 1130 PM and I'm almost cross-eyed with exhaustion.

Monday, February 1, 2016

W4D1 - Local Web Server, regex, and madness

Today we played with using a simple python script (handed to us) to run a local web server.  It gave us a chance to see a "GET" request and to do some simple string parsing using real info.  Also: super-basic templates (dynamically replace "###Title###" in an html file with "My Page Title" as the web server sends a GET request for the page) and using a function lookup dictionary to have a function return the relevant html string in response.

The last exercise is what kept me up until 11 (on a school night!).  Using regex to pull up the relevant function based on match to the GET request.  Even with the regex patterns pre-loaded, it was a challenge since I've only every done a copy-paste from a stackoverflow thread (with a little modification on my part).  Understanding the output from a re.match function and routing that output to a function was...interesting.  I'm not sure if it's my unfamiliarity that makes it so hard, or if I'm just missing something really obvious.

I've wanted to learn regex better for some time.  I played around with Learn Regex the Hard Way.  I suspect I'll have to come back after boot camp to really work with it.  Or maybe I can do the recommended one exercise a day while I'm here to at least get started.  It's such a powerful tool!  Plus, I'm fascinated by patterns so the thought of a mini-language devoted to describing patterns is a real lure.

In the mean time, I went to the tutorials point page and figured out enough to work through the homework.