bumsfeld 413 Nearly a Posting Virtuoso

Lunch time!

bumsfeld 413 Nearly a Posting Virtuoso

Another cup of very unhealthy black tea.

bumsfeld 413 Nearly a Posting Virtuoso

Sorry, module graphics.py does not work with module PIL!
You can only use .gif image files.

bumsfeld 413 Nearly a Posting Virtuoso
#Blast workbench using biopython

from Bio.Blast import NCBIWWW
##result_handle = NCBIWWW.qblast("blastn", "nr", "8332116")
fasta_string = "AATTCAGTGGCAAAAAAAAAACTCAAATTTTAGGGAAGGCCCTAATATTATCAAATAATTAGAGGGGGGG"

result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)


save_file = open("my_blast.xml", "w")

save_file.write(result_handle.read())
save_file.close()
result_handle.close()

result_handle = open("my_blast.xml")

from Bio.Blast import NCBIXML
for record in NCBIXML.parse(open("my_blast.xml")) :
    #We want to ignore any queries with no search results:
    if record.alignments :
        print "QUERY: %s..." % record.query[:60]
        for align in record.alignments :
            for hsp in align.hsps :
                print " %s HSP, e=%f, from position %i to %i" \
                % (align.hit_id, hsp.expect, hsp.query_start, hsp.query_end)
print "Done"
#Blast workbench using biopython

from Bio.Blast import NCBIWWW
##result_handle = NCBIWWW.qblast("blastn", "nr", "8332116")
fasta_string = "AATTCAGTGGCAAAAAAAAAACTCAAATTTTAGGGAAGGCCCTAATATTATCAAATAATTAGAGGGGGGG"

result_handle = NCBIWWW.qblast("blastn", "nt", fasta_string)


save_file = open("my_blast.xml", "w")

save_file.write(result_handle.read())
save_file.close()
result_handle.close()

result_handle = open("my_blast.xml")

from Bio.Blast import NCBIXML
for record in NCBIXML.parse(open("my_blast.xml")) :
    #We want to ignore any queries with no search results:
    if record.alignments :
        print "QUERY: %s..." % record.query[:60]
        for align in record.alignments :
            for hsp in align.hsps :
                print " %s HSP, e=%f, from position %i to %i" \
                % (align.hit_id, hsp.expect, hsp.query_start, hsp.query_end)
print "Done"
bumsfeld 413 Nearly a Posting Virtuoso
d1 = {'a': 1, 'bc': 2, 'def': 3, 'gh': 4, 'ijkl': 5}

# make shallow copy of d and process the copy
d2 = d1.copy()
for key in d1.keys():
    if len(key) < 3:
        del d2[key]

print(d1)  # {'a': 1, 'ijkl': 5, 'gh': 4, 'def': 3, 'bc': 2}
print(d2)  # {'ijkl': 5, 'def': 3}
bumsfeld 413 Nearly a Posting Virtuoso

I use this little batch file to force IDLE to work with Python 3.1.1

REM batch file to force IDLE to run with Python 3.1
REM save as IDLE31.bat
C:\Python31\Pythonw.exe -u C:\Python31\Lib\idlelib\idle.pyw

For discussion on 32bit versus 64bit see:
http://www.daniweb.com/forums/thread267106.html

bumsfeld 413 Nearly a Posting Virtuoso

Very interesting homework problem.

Note about your code:
input is Python function name and should not be used for variable name, also use open() rather then file(). Function file() has been removed in Python3.

bumsfeld 413 Nearly a Posting Virtuoso

Pretty wild coding with a little bit of Ruby thrown in!

Here is just one small hint using actual Python code:

def get_vowels(word):
    number_vowels = 0
    for c in word:
        if c in 'aeiouy':
            number_vowels += 1
    return number_vowels

def get_consonants(word):
    number_consonants = 0
    for c in word:
        if c not in 'aeiouy':
            number_consonants += 1
    return number_consonants

# test
word = 'deaf'
vowels = get_vowels(word)
consonants = get_consonants(word)
print("%s has %d vowels and %d consonants" % (word, vowels, consonants))
bumsfeld 413 Nearly a Posting Virtuoso

Let's test it:

class Test(object):
    def __init__(self,var1=123):
        self.var1 = var1

class Test2(Test):
    def __init__(self, var2=1234):
        Test.__init__(self)
        self.var2 = var2
        # test it ...
        print(self.var1, self.var2)  # 123 1234

t2 = Test2()
bumsfeld 413 Nearly a Posting Virtuoso

One way to look at this problem:

class Test(object):
    def __init__(self, var1=123):
        self.var1 = var1

    def show(self):
        print(self.var1)


class Test2(Test):
    # create self
    def __init__(self):
        # make inherited class Test part of self
        Test.__init__(self)
        self.show()  # 123
        self.var1 = 777
        self.show()  # 777


t2 = Test2()
bumsfeld 413 Nearly a Posting Virtuoso

Rebaked beans and with a turkey sandwich.

bumsfeld 413 Nearly a Posting Virtuoso

Here I thought that cow tipping was stepping on a cow's output and tipping in the process.

bumsfeld 413 Nearly a Posting Virtuoso

Can you show some code you have written by now?

bumsfeld 413 Nearly a Posting Virtuoso

I am starting to play around with IronPython, but I can't figure out how to convert any code to executable file that will run on Windows. There has got to be some kind of batch file.

bumsfeld 413 Nearly a Posting Virtuoso

The title has nothing to do with the homework, but it gets the attention and fools the teacher. Clever?

bumsfeld 413 Nearly a Posting Virtuoso

Nobody will do your homework, you got show some effort and some ideas how you want to solve this.

bumsfeld 413 Nearly a Posting Virtuoso

A&W root beer for me!

bumsfeld 413 Nearly a Posting Virtuoso

If waiters don't make any money, there would be no waiters!

bumsfeld 413 Nearly a Posting Virtuoso

The idea of a universal heal care is an honorable one. The problem is that the program will more than likely bankrupt the nation. Where are we going to get the several trillion dollars per year to pay for it? Answer: taxes. Our (both private and business) taxes will more than likely double over the next 5-10 years.

Who is paying now for all those folks that cannot pay their health bill?

bumsfeld 413 Nearly a Posting Virtuoso

Mississippi is the most obese state in the USA.

bumsfeld 413 Nearly a Posting Virtuoso

Many new computers come with Windows7(64bit) OS. You will be tempted to install something like Python 3.1.1 64bit version. However, many packages like PyQT and PyGame don't offer 64bit versions yet and will not work!

bumsfeld 413 Nearly a Posting Virtuoso

Recursive function can replace the while loop, but while loop is more efficient and faster.

bumsfeld 413 Nearly a Posting Virtuoso
# Python3 only

tup = (1, 2, 3, 4)
tup_bin = tuple(bin(n) for n in tup)
print(tup_bin)

"""output -->
('0b1', '0b10', '0b11', '0b100')
"""
bumsfeld 413 Nearly a Posting Virtuoso

Really Pythonic (elegant) ...

mylist = [
'192.168.255.1 00:01:02',
'172.14.0.1 00:0f:01',
'172.14.0.2 00:0f:01',
'172.14.0.3 00:0f:01'
'172.14.0.4 01:ff:dd:34',
'192.168.255.3 00:dd:01:ff'
]

# your exclude substring
exclude = '172.14'
newlist = [item for item in mylist if not item.startswith(exclude)]
print(newlist)

"""output -->
['192.168.255.1 00:01:02', '192.168.255.3 00:dd:01:ff']
"""
bumsfeld 413 Nearly a Posting Virtuoso

Another fine mess you've gotten me into.
-- Stan Laurel

bumsfeld 413 Nearly a Posting Virtuoso

Cottage cheese with fruit cocktail topping.

bumsfeld 413 Nearly a Posting Virtuoso

I got a summons for jury duty.

Does that mean you can send some criminal to the electric chair?

bumsfeld 413 Nearly a Posting Virtuoso

I got a job - cuts back on my gaming and posting.

Finally! Congratulations are in order!

Hope the job pays enough for you to survive on.

bumsfeld 413 Nearly a Posting Virtuoso

Note that kg and pound are weight units of measurement.
Gallon and liter are volume units of measurement.
Don't mix them!

You can use this code:

kg = float(raw_input("Enter number of kg: "))
lb = kg * 2.205
print kg, "kg =", lb, "pounds"

Or you can use this code:

gallon = float(raw_input("Enter number of gallons: "))
liter = gallon * 3.785
print gallon, "gallons =", liter, "liters"

Or you can use a generic value:

value = float(raw_input("Enter a number: "))
lb = value * 2.205
print value, "kg =", lb, "pounds"
liter = value * 3.785
print value, "gallons =", liter, "liters"
bumsfeld 413 Nearly a Posting Virtuoso

The question of embedding image files into programs came up. Tkinter makes this easy.

First create the base64 encoded image string:

# Base64encGIF2.py
# create base64 image string
# (read as binary file 'rb')
# Henri AB

import base64

# pick file you have in working directory or give full path
gif_file = "grape.gif"
# base64.encodestring() gives 76 char/line string
# base64.b64encode() gives all char on one line
mystr = base64.b64encode(open(gif_file, 'rb').read())
# customize to n char/line
# inserted '\n' is ignored by b64decode()
n = 68
b64_str = ""
for ix, c in enumerate(mystr):
    if ix != 0 and ix % n == 0:
        b64_str += '\n'
    b64_str += c

print "grape_gif='''\\\n" + b64_str + "'''"

"""select and copy resulting base64 gif string to your program -->

grape_gif='''\
R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9PT6Ai
8P8A/////////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYYfh8GIEvp
oUZcmtOKAO5rLMva0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYwYtYo3d4+DBxJ
WuSCAQ30+vNTGcxnOIARj3eTYhJDQ3woDGl7foNiKBV7aYeEkHEignKFkk4ciYaImJqb
kZ+PjZUjaJOElKanqJyRrJyZgSKkokOsNYa2q7mcirC5I5FofsK6hcHHgsSgx4a9yzXK
0rrV19gRADs='''

"""

Second, copy the resulting image string to your program, for eample:

# Base64encGIF_button2.py
# test base64 image string with Tkinter to form image button
# Henri AB

try:
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk

# base64 image string of grape.gif
grape_gif='''\
R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9PT6Ai
8P8A/////////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYYfh8GIEvp
oUZcmtOKAO5rLMva0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYwYtYo3d4+DBxJ
WuSCAQ30+vNTGcxnOIARj3eTYhJDQ3woDGl7foNiKBV7aYeEkHEignKFkk4ciYaImJqb
kZ+PjZUjaJOElKanqJyRrJyZgSKkokOsNYa2q7mcirC5I5FofsK6hcHHgsSgx4a9yzXK
0rrV19gRADs='''

root = tk.Tk()

# 'data=' converts base64 image string to an actual gif image
gif_image = tk.PhotoImage(data=grape_gif)

button = tk.Button(root, image=gif_image)
button.pack(padx=10, pady=10)
# optionally save button image from garbage collection
button.image = gif_image

root.mainloop()

Note that the base64 image string formatted to 68 char per line shows better on DaniWeb.

bumsfeld 413 Nearly a Posting Virtuoso

You can use icons provided by wxPython:

# the start of one small text editor with toolbar and image icons
# image icons are from the wx.ArtProvider
# notice that the wx.TextCtrl() surface has already some advanced
# features: select text, right click to cut, copy and paste etc.
# Henri AB

import os
import wx

class MyEditor(wx.Frame):
    def __init__(self, title):
        wx.Frame.__init__(self, None, -1, title,
            size=(500, 300))
        self.control = wx.TextCtrl(self, -1, style=wx.TE_MULTILINE)

        # statusBar at the bottom of the window
        self.CreateStatusBar()
        self.SetStatusText(" Click on the icon")

        # ToolBar at the top of the window
        toolbar = wx.ToolBar(self, -1,
            style=wx.TB_HORIZONTAL|wx.NO_BORDER)
        toolbar.SetToolBitmapSize(size=(24,24))
        toolbar.AddSimpleTool(wx.ID_OPEN,
            self.getBMP(wx.ART_FILE_OPEN),
            "Load", " Load a text file")
        toolbar.AddSimpleTool(wx.ID_SAVE,
            self.getBMP(wx.ART_FILE_SAVE),
            "Save", " Save the text file")
        toolbar.AddSimpleTool(wx.ID_ABOUT,
            self.getBMP(wx.ART_INFORMATION),
            "About"," About message")
        toolbar.AddSeparator()
        toolbar.AddSimpleTool(wx.ID_EXIT, self.getBMP(wx.ART_QUIT),
            "Exit"," Exit the program")
        toolbar.Realize()
        self.SetToolBar(toolbar)

        # bind the various toolbar icon click events to some action
        self.Bind(wx.EVT_TOOL, self.onLoad, id=wx.ID_OPEN)
        self.Bind(wx.EVT_TOOL, self.onSave, id=wx.ID_SAVE)
        self.Bind(wx.EVT_TOOL, self.onAbout, id=wx.ID_ABOUT)
        self.Bind(wx.EVT_TOOL, self.onExit, id=wx.ID_EXIT)

    def getBMP(self, pic_id):
        """get the bitmap image from the wxPython art provider"""
        return wx.ArtProvider.GetBitmap(pic_id, wx.ART_TOOLBAR,
            wx.Size(24, 24))

    def onAbout(self, e):
        """the about box"""
        about = wx.MessageDialog( self, " Very simple text editor \n"
            " using the wxPython GUI toolkit", "About Simple Editor",
            wx.OK)
        about.ShowModal()
        about.Destroy()

    def onLoad(self, e):
        """open text file"""
        self.dirname = ''
        mask = "Text (.txt)|*.txt|All (.*)|*.*"
        dlg = wx.FileDialog(self, "Choose file to load",
            self.dirname, "", mask, wx.OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            f = open(os.path.join(self.dirname,self.filename),'r')
            self.control.SetValue(f.read())
            f.close()
        dlg.Destroy()

    def onSave(self, e):
        """Save text file"""
        self.dirname = ''
        mask …
bumsfeld 413 Nearly a Posting Virtuoso

And the error you are getting is?

bumsfeld 413 Nearly a Posting Virtuoso

There is indentation error. Also, put in some test prints to see what you get.

bumsfeld 413 Nearly a Posting Virtuoso

Are you for real?

bumsfeld 413 Nearly a Posting Virtuoso

I started the year with a miserable cold.

'FFFFFuuuuuu!' is correct, but remember that if it isn't life threading, it isn't much to worry about. Let's just hope that all your other days are getting better this year.

bumsfeld 413 Nearly a Posting Virtuoso

People like to be popular, why not their password?

I use only popular words like racecar and spell them in reverse. :)

bumsfeld 413 Nearly a Posting Virtuoso

Just one nice French word (in the US it may be called Liberty word) translated as:
lacking social grace, sensitivity, or acuteness; awkward; crude; tactless.

Take your pick! I feel sorry for all the programmers that use if condition==true, as they are tactless and crude people lacking social grace! All of this because some ill educated person wrote another Java book.

bumsfeld 413 Nearly a Posting Virtuoso

There's one big, big difference between 'VernonDozier' and 'jwenting.'

bumsfeld 413 Nearly a Posting Virtuoso

Happy Australia Day too!

bumsfeld 413 Nearly a Posting Virtuoso

What's key?
Avoid using sum since it is Python function, could get you into trouble later.

bumsfeld 413 Nearly a Posting Virtuoso

Well, this should give you some hints, look at this code:
http://www.daniweb.com/forums/post1111987.html#post1111987

bumsfeld 413 Nearly a Posting Virtuoso

Dragging one image around the canvas with the mouse can be done using the Tkinter GUI toolkit as shown here:

# explore the Tkinter GUI toolkit
# drag one image on the canvas
# tested with Python 3.1.1 and Tkinter 8.5

import tkinter as tk

class MyCanvas(tk.Frame):
    def __init__(self, master, photo):
        tk.Frame.__init__(self, master)
        # use pack layout in the class
        # expand frame to fit as window is resized
        self.pack(expand='yes')
        self.master = master
        self.photo = photo
        self.canvas = tk.Canvas()
        self.canvas.pack(side='top', fill='both', expand='yes')
        # initial image upper left corner ('nw') at x=0 and y=0
        self.img = self.canvas.create_image(0, 0, image=photo, anchor='nw')
        # drag upper left corner of image
        self.canvas.bind("<B1-Motion>", self.move_image)

    def move_image(self, event):
        # delete the old image
        self.canvas.delete(self.img)
        # get the mouse position
        x = event.x
        y = event.y
        # create the new image at position x, y
        self.img = self.canvas.create_image(x, y, image=self.photo,
            anchor='nw')
        self.canvas.update()


root = tk.Tk()
root.title("drag upper left corner of image")
# pick an image file you have in your working directory
# or specify full path (without PIL you have to use .gif files)
image_file = "fun.gif"
photo = tk.PhotoImage(file=image_file)
MyCanvas(root, photo)
root.mainloop()

Should work with Python2 making minor modifications.

bumsfeld 413 Nearly a Posting Virtuoso

Here is modified (also added needed delay) and commented code from the pygame tutorial that shows how to load one image onto rectangle object and move the object:

# use pygame to bounce/move loaded image around the screen

import sys, pygame

pygame.init()

size = width, height = 320, 240
# this determines the move direction/speed in pixels
# speed[0] left or right
# speed[1] up or down
speed = [2, 2]
# color uses r, g, b tuple
black = 0, 0, 0
# white works better here
white = 255, 255, 255

# create the window
screen = pygame.display.set_mode(size)
# give the window a title
pygame.display.set_caption("watch the beach ball bounce")

# make sure the image file is in the working directory
# or give full path name
ball = pygame.image.load("ball.bmp")
# create rectangle object you can move
# it is used to put the image on
ballrect = ball.get_rect()

while True:
    for event in pygame.event.get():
        # window corner x will exit
        if event.type == pygame.QUIT:
            sys.exit()
    # move the rectangle object
    ballrect = ballrect.move(speed)
    # change direction if left or right boundry is reached
    if ballrect.left < 0 or ballrect.right > width:
        speed[0] = -speed[0]
    # change direction if top or bottom boundry is reached
    if ballrect.top < 0 or ballrect.bottom > height:
        speed[1] = -speed[1]
    # clear the screen with white background
    screen.fill(white)
    # put the image on the rectangle object
    screen.blit(ball, ballrect)
    # update screen
    pygame.display.flip()
    # small time delay
    milliseconds = 20
    pygame.time.delay(milliseconds)

The image …

bumsfeld 413 Nearly a Posting Virtuoso

If you use m==0 it will give you False unless m is zero.

bumsfeld 413 Nearly a Posting Virtuoso

Interesting, I've never used 2D arrays in Python but I would have hacked it to be useable in 'C-like' manner:

class sphere():
    def __init__(self, x=0.0, y=0.0, z=0.0):
        self.x = x
        self.y = y
        self.z = z

    def __str__(self):
        return "Coords: %s %s %s"%(self.x,self.y,self.z)


n = 10
m = 10
myArray = []

for i in xrange(n):
    myArray.append(map(sphere, xrange(m)))
    for j in xrange(m):
        myArray[i][j] = sphere(float(i), float(j), 0.0)

print "i=2,j=3: %s"%myArray[2][3]
print "i=6,j=1: %s"%myArray[6][1]
print "i=4,j=9: %s"%myArray[4][9]

Would this be seen as unPythonic? Or is it bad for other reasons? Just curious...

You can create myarray[x][y][z], but you still have to associate with the sphere object, that is where the dictionary mapping comes in handy.

bumsfeld 413 Nearly a Posting Virtuoso

You can include coordinate z into your key tuple by simply expanding vegaseat's code:

# create a large number of spheres referencing them
# with a (x, y, z):sphere_object dictionary pair

import visual as vs

spheres = {}
for x in range (0, 100):
    for y in range (0, 100):
        z = 0
        spheres[(x, y, z)] = vs.sphere(pos=(x, y, z), radius=1)

# to select a particular sphere use
x = 45
y = 55
z = 0
spheres[(x, y, z)].color = vs.color.red
bumsfeld 413 Nearly a Posting Virtuoso

Your area formula for regular polygons should be:

area = ((length**2) * numSides)/(4 * (math.tan(math.pi/numSides)))

Your result will be square units of whatever units of measurement your sides are. You cannot get degrees for the area!

bumsfeld 413 Nearly a Posting Virtuoso

Vegaseat left this ttk code somewhere showing you the way module ttk should be imported and applied:

# exploring the Tkinter expansion module ttk notebook
# tested with Python 3.1 and Tkinter 8.5   by  vegaseat

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
# use width x height + x_offset + y_offset (no spaces!)
root.geometry("%dx%d+%d+%d" % (300, 200, 100, 50))
root.title('test the ttk.Notebook')

nb = ttk.Notebook(root)
nb.pack(fill='both', expand='yes')

# create a child wdget for each page
f1 = tk.Frame(bg='red')
f2 = tk.Frame(bg='blue')
f3 = tk.Frame(bg='green')

# create the pages
nb.add(f1, text='page1')
nb.add(f2, text='page2')
nb.add(f3, text='page3')

# put a button widget on child f1
btn1 = tk.Button(f1, text='button1')
btn1.pack(side='left', anchor='nw', padx=3, pady=5)

root.mainloop()
bumsfeld 413 Nearly a Posting Virtuoso

Be aware that Python25 and Python26 use different MS C compilers and so do the modules they use. The C code syntax has to match these compilers, as they are not compatible.

bumsfeld 413 Nearly a Posting Virtuoso

Looking at your code you have quite a nightmare of errors in there and on top of that the all important indentations are all screwed up.

!) use the customary 4 space indentations, avoid tabs!!!!

2) you set n = 0 before you use it in range()

3) you ask for n but never pass it on to tile()

4) m==0 should be m = 0

5) range (n^2) should most likely be range(n) or range(n**2)

There are a few more, but I have to stop.

BTW, PIL has the paste() function that will make the whole thing one lot easier.