Tuesday 27 September 2011

Creating my own Markup Language.

Creating our own Markup Language

Inspired by my lifelong addiction to Football Manager I was thinking of creating a markup language with a purpose for football. The idea of this could be used with a real time location based infographic app/data viewer. This came out of a few hours work and is very much an example of understanding how markup works and what are its possibilities. Given more time, this example could become a lot more complex. 


The  < Matchinfo > is fairly self explanatory. The < ID > section refers to the associated info to that could be assigned to that specific stadium - ie travel info, average attendance, current people check-in there (read Facebook/Foursquare tie in).

< match2 >

  < matchinfo >
    < date > 2011-10-08 < /date >
    < stadium > Reebok
        < id > 16 < /id >
    < /stadium >
    < city > Bolton < /city >
    < kick-off > 15:00 < /kick-off >
    < time > 15:23 < /time >
  < /matchinfo >
< /match2 > 



This section describes a specific event.
The fictional event describes Rooney equalising for Man Utd at the Reebok, with Cahill at fault for the goal.

The  < match2 >  refers to which game it is in the league fixtures for that day.

Now we get onto the information of the specific event.
We can see the event which occurred was a shot (no 4 of the game), it was on target and resulted in a goal (the second of the game). The < placement > 301 < /placement >  refers to a grid reference given the the goal itself.
If you imagine the goal is split into 3 horizontal sections, each split into 4 boxes.

  < Event >
      < action >Shot
          < shotno > 04 < /shotno >
      < /action >
      < type > On Target < /type >
      < outcome > Goal
          < goalno > 2
      < /outcome >
      < placement > 301 < /placement >
  < /Event >


The idea of  Context  is to give a more human approach to the data and event.
It is given a rating between 1-10 as to how against the run of play the goal is. This has been given an 8 with 10 being completely against the run of play, 1 being very, very likely. The  timing refers to how this goal affects the scoreline - this being an equaliser.
The idea of  blame  is perhaps an unnecessary one but gives an indicator as to who was at fault in the game. In this respect Cahill can be seen as being at fault. This could always be set to  none  if the event was a moment of brilliance rather than poor defending or goalkeeping.

  < context >
      < run-of-play > Against < /run-of-play >
          < rating > 8 < /rating >
      < contraversial > no < /contraversial >
      < timing > equaliser < /timing >
      < goals > 1:1 < /goals >
      < blame > Cahill < /blame >
   < /context >
The Ball data would be the most important when thinking of a live feed graphic. The < assistfrom > & < endpoint > directly refers to the start and end point of the pass that led to the goal.Again, like the goal, the pitch would be split into a grid reference system. In this grid, the pitch would be split a1 - e5 with c straddling the half way line and a or e being either goal area or corner. There are also a few extra data entries connected to the pressure and assistfrom fields. The extra data assigned to assistfrom is the play. This related to either open play or dead ball situation. A dead ball situation could then be further extended to being a corner, free-kick, goalkick, etc.
   
     < assistfrom > d2
       < play > open < /play >
     < /assistfrom >
     < pressure > none
       < rating > 2 < /rating >
     < /pressure >
     < endpoint > b3
     < height > feet < /height >
     < /endpoint >
   < /ball >

The next section describes the players involved, their locations, affiliated ID's, image database #'s, etc.
From these ID's you could incorporate player profiles, stats from the match and the rest of the season and so on.

 < team > Man Utd
    < player >
      < position > attacker < /position >
      < name > Rooney < /name >
      < playerid > 0028910 < /playerid>
      < location > b3 < /location >
      < colour > Red < /colour >
      < number > 10 
      < img /> 289
    < /player>

    < player >
      < position > midfielder < /position >
      < name > Young < /name >
      < playerid > 0031518 < /playerid >
      < team > Man Utd < /team >
      < location > d2 < /location >
      < colour > Red < /colour >
      < number > 18 < /number >
      < img /> 315
    < /player >
< /team >

    
< team > Bolton
    < player >
      < position > defender < /position >
      < name > Cahill < /name > 
      < playerid > 0003206 < /playerid >
      < location > a4> < /location >
      < colour > White and Blue < /colour >
      < number > 06 < /number >
      < img/ > 32
    < /playe r>

    < player >
      < position > goalkeeper < /position >
      < name > Jaaskelainen < /name >
      < playerid > 0011222 < /playerid >
      < location >x2>< /location >
      < colour > Sky Blue < /colour >
      < number > 22 < /number >
      < img / > 112
    < /player >
< /team >

There is a lot which could be edited and streamlined into a more cohesive script and language. I could make use of putting each team into a separate <div>;

< team id="Bolton" >
  
  < player id="Cahill">
  < position > defender < position >
  ...

This could allow for better understanding of the script and use of easier manipulation by making separate sections for each team then player (div within div).

Monday 19 September 2011

Creating your own server


Today we've looked at creating our own servers.


We began by pinging the servers of some household names (google, facebook, twitter - the slowest, who'da thunk?!), then following the route of a packet between here and the US servers, and then having a look at the new IPv6 addresses including facebook's '2620:0:1cfe:face:b00c::3'.


Using Python once again, we created a script which is akin to Tim Henman's famous serve *run to the net* and volley approach.


By running our two scripts each in its own terminal window we could try and connect to a newly created socket, printing on the server side the sent & received data, and on the client facing side, printing a personalised message (in red here).


Here is "Tiger Tim's" serve[r].


Socket script


import socket


s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


s.bind(('127.0.0.1', 4900))
s.listen(1)


client_socket, address = s.accept()
print 'received connection from ', address


while True:
   data = client_socket.recv(4096)
   if not data:
      client_socket.close()
      break


   print 'received data', data


   bytes_sent = client_socket.send(data)
   print 'sent:', bytes_sent


s.close


And here is his volley (in a very abstract and perhaps incorrect analogy).


Connection script



import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect(('127.0.0.1', 4900))
s.send('Bugger off!')
print s.recv(4096)
s.send('Oh, okay. Come on in...')
print s.recv(4096)
s.close()

In a typically British Semi-Final kind of way, my first attempt crashed out, causing an outcry of (albeit, excpeted) anguish and demoralising anti-nationalism.


Why I hear you cry?


Because I spelt 'True' with a non-capitalised 't'.


Once again, Python had spanked me with its racket of discipline and grammar.


*spank* An artists impression of Python giving me a once over using my Henman metaphor.


I will learn soon enough to avoid the wrath of Python. And people shall flock to a hill named after my coding...

...only to leave with a bitter resentment of losing days to rained-off exasperation, filled with the false hopes of being part of a moment in history.

At least will be strawberries and cream.

Cheering on Java vs Snake.

I also managed to sort out my public folder on the University server.

It can be accessed here

Thursday 15 September 2011

Dictionaries

Creating a dictionary in Python


It's easier than you (I) would think!
And it has humoured me this morning. Really tickled my script-buds.


I created a dictionary called 'student'. Within the dictionary we assigned different values (see below for mine). You can then make queries within the dictionary to find if something exists in there or not.


I asked if we had any creative license with this, we were granted a small amount of creative license and I rolled with it like a stone gathering a shed-load of moss.


student = {'alcohol': '60%','facility_to_learn': '15%', 'tolerance': '5%', 'culinary_skills': '4%', 'project_management': '7%', 'arithmatic_skills': '10%'}


You can add extra values later by using this:


student['enthusiasm'] = '6.5%'


To query the dictionary you need to type something like:


'alcohol' in student


And it returns a Boolean (Bool) value (True or False).



>>> 'alcohol' in student
True


After multiple attempts I had created this.





Although this was humorous I then learnt that '4%' is not a numeric value, but a string. A string is literally a group of characters, not a number (or a percentage as I wanted). This meant you could not query whether this student had an alcohol rating of above 50% (student['alcohol']  > '50%').


Instead I had to rewrite my dictionary to get rid of my '%'s, which rendered my 'arithmatic_skills': '10%' not funny (add up original values as %'s to see the funny side). Bad Time Bear had come out to play :/ 
Having said that I managed to complete the task at hand.







However this can be hugely helpful when searching through databases and returning values of unknown quantities ie. you can return all the ' 'student IDs' > 000100 ' or all students whose ' course == Digital_Journalism ' etc.





I can't help but feel like I've created the geekiest form of top trumps ever but you can then add more students to your dictionary.
Firstly, you create new students with the same items and values (if each has an enthusiasm value it's easier to search).













Then you create a name for your database, in this case 'students' and include all the names of your dictionaries.


You can [import, then] use pprint to display the list of items in a much easier to read manner (pprint.pprint(lab)).










I also learnt that 6 > a . Profound.

Wednesday 14 September 2011

What a div

Yesterday I learnt the hard way not what to [try to] design when it comes to html.


I wanted to create a simple page with blocks representing different parts of the Earth (think 8 bit).
by ~inuit-joe


I created 4 parts to my 'HTML Earth'. 


Sky, Sea, Grass and Tree.


Simple, huh?


Yes, yes I am.

The problem came about by not following the worksheet.
All the other problems followed from there.

I managed to finally create 3  <div> sections which coloured in blue (#4392C1), a different blue (#62B3C6) and green (#458604).

The struggle came with getting the tree element in line with the rest.

The solution was to create a <div> within a <div> and then have my tree <div> alongside the others (by not aligning right - this caused the tree to move when zooming in/out of the page).

I then managed to position an image of leaves across my other <div>'s by using an absolute position in my paired CSS file.

#leaves{
position:absolute;
left:830px;
top:010px;
}

Simple links could be mode within each <div> with new <p></p> sections and using the text as hyperlinks to wiki entries, etc.

In a nutshell, my mini experiment didn't work. I probably would have been better off creating a less 'unusual' and 'different' page. But now I know.

Below is a screenshot of the laughable page (which could have been made in MS paint in a fraction of the time) and the HTML & CSS. 

Feel free to shout out easier/quicker ways and where I've gone wrong. Constructively though, not things like "You needn't have bothered today", I already know that! :p

HTML:

<html>
  <head>
    <title>Earth</title>
    <link rel="stylesheet" href="style1.css"/>
  </head>

<body>

<div id="bigdiv">

  <div id="secondarydiv">


  <div id="middiv">

      <div id="sky">
<p><a href="http://en.wikipedia.org/wiki/Sky">Sky</a></p>
<div id="skytext"><p>my wiki example text here</p>
     </div>
</div>
      
      <div id="grass">
<p><a href="http://en.wikipedia.org/wiki/Crust_(geology)">Grass</a></p>
      </div>
      
      <div id="sea">
<p><a href="http://en.wikipedia.org/wiki/Earth#Surface">Sea</a></p>
<div id="seatext"><p> my wiki example text here </p></div>
      </div>

  </div>

   <div id="tree">
     <p><a href="http://en.wikipedia.org/wiki/Biosphere">Tree</a></p>
   </div> 
  
</div>

      <div id="leaves">
<img src= "/Users/ma101lp/Desktop/leaves2.jpg" alt="leaves on tree"/>
 <caption><a href="http://en.wikipedia.org/wiki/Life">Leaves</a></caption>

<p></p>
      </div>
      
      <div id="nav">
<ul>
 <li>Our</li>
 <li>Planet</li>
 <li>In</li>
 <li>HTML</li>
      </div>


</div>


CSS:

body{
     background-color:#ffffff;
}


#bigdiv{
    height:1000px;
    width:1200px;
}

#secondarydiv{
}    

#middiv{
    height:999px;
    width:1000px;
    float:left;
}   

#sky{
    background-color:#4392C1;
    width:985px;
    height:350px;
    padding:10px;
    border:1px solid light blue;
}

#skytext{
    max-width:500px;
}

#grass{
    background-color:#458604;
    width:650px;
    height:300px;
    padding:10px;
    border:1px solid green;
    float:right;
}


#sea{
    background-color:#62B3C6;
    width:310px;
    height:300px;
    padding:10px;
    border:1px solid light blue;
    align:left;
}

#seatext{
    max-width:295px;
}

#treediv{
    float:right
    width:150px;
    height:650px;
}


#tree{
    background-color:#953804;
    width:150px;
    height:670px;
    padding:10px;
    border:1px solid brown;
    float:left;
}

#leaves{
position:absolute;
left:830px;
top:010px;
}

ul{
    list-style-type:none;
    margin:0px;
    padding:0px;
}

ul li{
    border:1px solid black;
    margin:0px;
    padding:0px;
    float:left;
}

#nav{
    border:1px solid black;
    margin:10px;
    padding:10px;
    align:centre
}


Tuesday 13 September 2011

Example Scripts

Python Practice Scripts



"Unlucky!"

Working on simple user input scripts. The premise is when you enter what course you are studying, the script either replies in a positive manner 'Same as me!', or a negative "Unlucky!".

course = 'Digital Journalism'
JCourse = raw_input ('Please enter the course:')

if JCourse == 'Digital Journalism': 
    print 'Same as me.'
else:
    print 'Unlucky!'

Passwords

Here we tested requesting user inputs to match our ultra secure, top secret password (abc123). The raw_input represents the user's input. When the incorrect password is typed and RETURN is pressed, the script prints 'Incorrect'.
Below is the script.


secret_password = 'abc123'
password = raw_input('Please enter the password: ')

while password != secret_password:
    print 'Incorrect'
    password = raw_input('Please try again: ')


Email Verifier

This script simply verifies and prints email addresses. A real world application of this script could be to search through a data base or website or something similar for either a certain type of email eg. gmail or addresses ending in .ru . The script could then be adapted to print the results into a new text file on your Hard Drive/USB etc (see tweetfeed example).

import re

strings = ['My email address is leon@email.com',
          'This is not my email address']

email_pattern = '[\w._-]+@[\w._]+\.[A-Za-z]+'

for string in strings:
    match = re.search(email_pattern, string)
    if match == None:
        print 'No email address in: "', string, '"'
    else:
        print match.group(), 'is an email address'


Tweetfeed

This script was adapted to search for a certain word from Twitter. It does not, in its current form, support hashtags or users, but could be with a few additional lines of script. This example searches for "london" every 5 seconds and was adapted to print the results to text file.

import urllib2
import json
import time

tweets_data = urllib2.urlopen('http://search.twitter.com/search.json?q=london').read()
tweets = [tweet['text'] for tweet in json.loads(tweets_data)['results']]

while True:
    time.sleep(5)
	for tweet in tweets:
    	print tweet.encode('utf-8', 'ignore')

******************************

I'll try and edit this to add its printing functionality command soon. 

******************************


This page was written on Day5 in HTML mode to practice writing direct in HTML. The "< pre >" tag is used to seperate the normal text to the example code text.



Resources

Python Docs, w3 Schools

And here is my creativity for the week.

Caution: Coding in Progress

Monday 12 September 2011

1st week

The words "Don't panic", closely followed by "I can see you're all panicking" cut through the silence on Monday morning. Zimmer was trying to calm the nerves.


I had no real idea what to expect from the next three weeks.


We gathered in the lecture theatre of the New Academic Building at Goldsmiths College for a quick introduction to our Digital Methods Bootcamp.
We were introduced to the computer labs and to both Python and Javascript within Emacs (luckily using an iMac rather than an eMac).


Between the hours of 10am and 5pm my mind melted beyond recognition, a bit like those candles you get at Cargo and the like, that smell of generic petals which ends up looking like the blood splatter on the face of the smiley from the Watchmen.


Yes, my mind was more jumbled and tenuous than that last comic book reference.


Day 2 morning was a little less mind boggling, and I even managed to work out how to adapt some Python script beyond what was on the handout which felt like a massive accomplishment after Day 1.
The afternoon session made my cerebral cortex misfire.


Day 3 was all about the written word. We were looking at manipulating and managing directories and files through mostly Terminal. Pipes (|)and grep were difficult to get to grips with, but I soon became a dab-hand at it (!). My favourite take-aways on the third day was the discovery of the built-in device files; "/dev" .
By using a move command in terminal, you can purge any folder/file by mv ~ /dev/null . There is also /dev/random which serves as a random number generator and /dev/full which always returns a 'disk full' message.


Our fourth and final day of the first week saw us work on some python scripts, writing in Emacs and executing them in terminal. It was great to start using some real world examples of the work we'd been looking at over the last few days. We used a few rss links, BBC News and Twitter searches to play with.
We also had Director Brauer of CAST come in and enthuse about the course, and more importantly us. It made us feel good to be getting started, and that perseverance was crucial at this stage. We heard rumours of the WSJ and Guardian speakers as well as real-time collaborations with Columbia University, a BBQ in our seminar room and sit-ups with our peers and lecturers in our booked time in the gym!


The week drew to a close we ended with some much needed drinks and musings on the last few days.


I then fell over a bell on the side of the road and into a traffic light.


(not my image)


Now I'm bedded in at the new flat and working hard in week two with html, xml and markup languages to look forward to.