What is the difference between parenthesis and brackets in Python

Tuples and lists

Both are arrays, but tuples are immutable. This means that once you define a tuple, you cannot add elements, pop, append, remove an element, etc. You need to create a new tuple out of the old one every time you make a change.

  • Tuples (1,2,3,4,5,6) are great for static definition. They are hashable, lean and unequivocal.
  • Lists [1,2,3,4,5,6] are great for computation. They are mutable and queueable.

Both are addressed with integers in brackets.

Whether it is a list or a tuple, addressing one element is the same.

create a tuple with y = (“a”,”b”,”c”) and do this;

y = ("a","b","c")
print (y[0])
for i in y:
    print (i)

For lists and tuples, know this too;

for i in range(0,len(y)):
    print (i,y,y[i])

Now redefine y as a list and try it again. Same results?

shortest Python timezones example

assuming we import datetime and pytz, just for a little bit of brevity ….

print datetime.datetime.utcnow().replace(tzinfo=pytz.utc).\
   astimezone(pytz.timezone("US/Eastern")).strftime("%Y-%m-%d %H:%M")

Whoa Nelly, Break it down bro! Below is an example of getting a ‘Naive’ time. I.E. it will be the time of the computer you are using, but have no associated timezone designation. This example also will get an error if you can’t import datetime.

import datetime
nowVariable = datetime.datetime.now()
print nowVariable

But a naive time object is unaware of the timezone, and the pytz object library is a great addition to datetime, but again, the next example will make your time object timezone aware, but first it will test that your computer can import the pytz object library.

import datetime, pytz
nowVariable = datetime.datetime.now()
laTimeVariable = nowVariable.replace(tzinfo=pytz.timezone("US/Pacific"))
print laTimeVariable

Other timezones could be US/Mountain, US/Central, Europe/Rome, Australia/Perth, Asia/Hong_Kong, etc.

Now, if we want to print the ‘aware’ date object in a pretty format, we can say;

print laTimeVariable.strftime("%Y-%m-%d %H:%M %Z")

This is great to populate the display variable when the date and time are sent to the screen. But with many different timezones and everything happening on the world wide dub dub dub all over the world at all hours, internally to my python code, I might want to always store and calculate the time in one single standard timezone, only converting as the last step to display it to a local user.

To get the current universal time, naive and aware;

utcNaiveVariable = datetime.datetime.utcnow()
utcAwareVariable = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)

MySql backup and restore

Prerequisites include a MySql server, probably Linux, shell access and MySql services installed and running.

 Backing up and restoring large MySql databases is more difficult than working with small databases. Small databases are easily dealt with using the ubiquitous phpMySqladm administration tool associated with most administrator situations but when the database exceeds a certain size between 2 and 95 Megabytes, using html to download and upload the backup files becomes less desirable than an SSL transport such as sFtp.

1. Determine your MySql database name, MySql user name and password, your domain for mysql (sometimes localhost suffices)

mysqldump -uUserName -p -h mysql.MyDomainName.com DatabaseName >file.sql

This command ends with >file.sql, which redirects the output to the file named file.sql in the current working directory.

2. Use the mysql command to restore the backup file. In this case, DatabaseName could be a different database within the same server, allowing you to make test database, or it could be the same database name on another MySql server.

mysql DatabaseName -uUserName -p <file.sql

Since some versions of html make have difficulty with the ‘less than’ sign, here is another way of doing the same thing.

cat file.sql | mysql DatabaseName -uUserName -p <file.sql

In both these cases, the command is prompting for the password with the -p option.

Ascii Art

Create a python program to emulate lighting segments of LED displays.

Create a figlet program to display 7 line Ascii Art text, using the same symbol for all output.

Create figlet program to display n line Ascii Art text, where n=5 or greater.

Create a program based on the PIL library to convert well formatted Ascii art to a jpeg, png or gif.

Create a program based on the PIL library to read an image, find it’s outlines and produce an Ascii art equivalent.

Curling, just not Canadian Style Python 2.6.6 and the urllib2 library

In bash, getting a web page

curl http://web-atlanta.com/ >html.html

The bash curl command has nothing to do with Canadian Curling, which is like shuffleboard on ice amidst the tension garnered tolerating a joke about the Queen or the national health care system from a surfboard riding processed cheese eating upper Mexican from south of the barbarian line. In bash, curl is short for client url, a simple http request of a web address.

In Python

x = urllib2.urlopen("http://web-atlanta.com")
w = x.read()

And as a part of a class init

  def __init__(self,TableName,filename,url):
    self.sqhandle=sqlite3.connect(filename) # empty if noexist
    self.sq1cursor = self.sqhandle.cursor()
    self.filename = filename
    try:
      self.sq1cursor.execute('''CREATE TABLE '''
         +TableName+''' (somenum real, somestring text)''')
      self.sqhandle.commit()
    except:
      print TableName,"table already exists"
    self.samples = 0
    x = urllib2.urlopen(url)
    self.pagedata = x.read()

So if we instantiate a class we now have the html as classname.pagedata and sqlite3 handle and cursor as classname.sqhandle and sq1cursor

We need to do some things with sql like

    command = 'INSERT INTO '+table+' VALUES (' + x +', "'+ y +'")'
    try:
      classname.sq1cursor.execute(command)
      classname.sqhandle.commit()
    except:
      print command

sqlite3 insert a row

  def sqlinsert(sqhandle,sq1cursor,table,x,y):
    command = 'INSERT INTO '+table+' VALUES (' + x +', "'+ y +'")'
    try:
      sq1cursor.execute(command)
      sqhandle.commit()
    except:
      print "failed to ", command