sneekula 969 Nearly a Posting Maven

You might have set host initially to something that makes sense.

sneekula 969 Nearly a Posting Maven

I wonder which beach you went to?

sneekula 969 Nearly a Posting Maven

Here would be one number of hints:

'''
file data1.txt looks like this:
A233;Apple;FOOD;1;5.00
A345;Blanck CD 10;DATA;10;0.25
B453;Pasta;FOOD;1;12.00
T545;USB-Memory 16GB;DATA;1;25

each line represents:
identity, name, category, quantity, price
'''

class Billing(object):
    def __init__(self, identity, name, category, quantity, price):
        self.identity = identity
        self.name = name
        self.category = category
        self.quantity = quantity
        self.price = price

# create a list of instances of class Billing
bill_list = []
for line in open("data1.txt"):
    #print(line)  # test
    #print(line.split(';'))  # test
    identity, name, category, quantity, price = line.split(';')
    quantity = int(quantity)
    # remove trailing new line char from price
    price = price.rstrip()
    price = float(price)
    #print(identity, name, category, quantity, price)  # test
    bill_list.append(Billing(identity, name, category, quantity, price))


print("------------------  F O O D  -------------------")
header = ('Product', 'Qty', 'Price/each', 'Price total')
print("%-18s %-5s %-6s %-10s" % (header))
total_food = 0
for bill in bill_list:
    if bill.category == "FOOD":
        totalprice = bill.quantity * bill.price
        sf = "%-18s %2d %10.2f %12.2f"
        print(sf % (bill.name, bill.quantity, bill.price, totalprice))
        total_food += totalprice

print("Total food = %0.2f" % total_food)

print('-'*48)

print("------------------  D A T A  -------------------")
header = ('Product', 'Qty', 'Price/each', 'Price total')
print("%-18s %-5s %-6s %-10s" % (header))
total_data = 0
for bill in bill_list:
    if bill.category == "DATA":
        totalprice = bill.quantity * bill.price
        sf = "%-18s %2d %10.2f %12.2f"
        print(sf % (bill.name, bill.quantity, bill.price, totalprice))
        total_data += totalprice

print("Total data = %0.2f" % total_data)

You still have to bring in your identity file and then search for bill.identity matches.

sneekula 969 Nearly a Posting Maven

This might give you some hints:

'''
file gemstone.csv looks like this:
valid gemstone owing mark channels code
No Diamond 26.06 20 218 (KJQ:10E)2
Yes Diamond 15.43 25 36 (DRX:25H)7
No Sapphire 11.44 51 141 (XKL:31L)4
No Zircon 79.68 23 60 (BYA:26Ix8
No Moonstone 79.41 11 67 (BWC:79L)4
Yes Garnet 109.69 17 215 (ECO:67B)5
No Pearl 61.16 30 128 (GAZ:36A)6
Yes Opal 44.2 9 162 (ZPK:85T)8
No Emerald 103.13 70 181 (GYN:99F)3
No Ruby 59.09 3 48 (UKI:10I)6
No Amethyst 36.94 35 71 (IUQ:42Z)3
No Diamond 5.45 79 28 (EHX:17T)8
No Amethyst 102.26 11 224 (ZTG:03L)8
No Sapphire 13.01 7 62 (ZBY:68T)9
No Garnet 121.96 93 43 (KHP:59H)3
Yes Garnet 47.13 31 156 (LnQ:15E)1
No Emerald 119.71 30 219 (IWZ:72J)4
No Zircon 38.99 120 98 (VTK53Q)1
No Pearl 91.76 135 80 (STE:05N)8
No Garnet 26.18 13 154 (KTD:90A)1
'''

from collections import Counter
import pprint

with open("gemstone.csv") as fin:
    gem_list = []
    for row in fin:
        gem_list.append(row.split()[1])

# eliminate header/title row
gem_list = gem_list[1:]

gem_cntr = Counter(gem_list).most_common()
pprint.pprint(gem_cntr)

print('-'*24)

# last element
print(gem_cntr[-1:])

'''
[('Garnet', 4),
 ('Diamond', 3),
 ('Zircon', 2),
 ('Pearl', 2),
 ('Amethyst', 2),
 ('Sapphire', 2),
 ('Emerald', 2),
 ('Opal', 1),
 ('Moonstone', 1),
 ('Ruby', 1)]
------------------------
[('Ruby', 1)]
'''
sneekula 969 Nearly a Posting Maven

One way to do this:

def make_userid(user):
    first, last = user.split()
    user_id = first[0] + last
    return user_id

user = "John Doe"

user_id = make_userid(user)

print(user_id)  # JDoe
sneekula 969 Nearly a Posting Maven

The factorial function is part of the math module in later versions of Python:

''' math_factorial.py
tested with Python 2.7.3
'''

from math import factorial

for k in range(1, 101):
    print("factorial of {} = {}".format(k, factorial(k)))

print(type(factorial(10)))       # <type 'int'>
print(type(factorial(100)))      # <type 'long'>
print(len(str(factorial(100))))  # 158
print(len(str(factorial(69))))   # 99
sneekula 969 Nearly a Posting Maven

Another option is to make a DailyExpenses.pth text file that contains the directory name where you can find the DailyExpenses.py file. You can save the path file in Python's "site-packages" directory.

sneekula 969 Nearly a Posting Maven

You could also use a list of instances of class Persons like shown in the example here:

# format: ni_number firstname lastname age
data_str = '''\
55512 Bart Simpson 45
45622 John Smith 58
46231 Alicia Sands 27
'''

fname = "data123.txt"

# write test data file
with open(fname, "w") as fout:
    fout.write(data_str)



class Persons:
    def __init__(self, ni_number, name, age):
        self.__ni_number = ni_number
        self.__name = name
        self.__age = age

    def show(self):
        '''for a quick test'''
        # formating string
        sf = " ni_number = {}\n name = {}\n age = {}\n"
        return sf.format(self.__ni_number, self.__name, self.__age)


# read the data file back in and process
with open(fname, "r") as fin:
    person_list = []
    for line in fin:
        mylist = line.split()
        print(mylist)  # test
        # unpack the list
        ni_number, first, last, age = mylist
        name = first + ' ' + last
        # create a list of instances of class Persons
        person_list.append(Persons(ni_number, name, age))

print('-'*20)
# test one of the instances
inst1 = person_list[0]
print(inst1.show())


''' console output -->
['55512', 'Bart', 'Simpson', '45']
['45622', 'John', 'Smith', '58']
['46231', 'Alicia', 'Sands', '27']
--------------------
 ni_number = 55512
 name = Bart Simpson
 age = 45

'''
sneekula 969 Nearly a Posting Maven

Hint:

class Sentence:
    def __init__(self, text):
        self.text = text
        self.word_list = self.text.split()
        #print(self.word_list)  # test

    def get_first_word (self):
        return self.word_list[0]

    def get_all_words(self):
        "I let you work out what to return"
        pass

# create an instance of class Sentence(text)
# this is your input text
text = "I'm going back" 
sent1 = Sentence(text)

print(sent1.get_first_word())  # I'am

# get the whole text
print(sent1.text)  # I'm going back

# a hint for module sent1.get_all_words()
# create the words from self.word_list
for word in sent1.word_list:
    print(word)

'''
I'm
going
back
'''
sneekula 969 Nearly a Posting Maven

Shows you how to assign a text font to the various Tkinter text oriented widgets:

''' tk_font_explore1.py
different ways to assign a text font to certain Tkinter widgets
snee
'''

try:
    # Python2
    import Tkinter as tk
    import tkFont as tkf
except ImportError:
    # Python3
    import tkinter as tk
    import tkinter.font as tkf

root = tk.Tk()
# set size of root
w = 350
h = 300
root.geometry("%dx%d" % (w, h))
root.title('setting Tkinter text fonts')

helv12 = tkf.Font(family="Helvetica", size=12, weight="bold")
helv16 = tkf.Font(family="Helvetica", size=16, weight="bold")

# FYI
# the instance of Font() can yield information
# get pixel width of a text in a given font, handy info
print(helv16.measure('label_2'))  # 71
print(helv16.cget('family'))      # Helvetica
print(helv16.actual())
''' result ...
{'family': 'Arial', 'weight': 'bold', 'slant': 'roman', 
'overstrike': 0, 'underline': 0, 'size': 16}
'''

frame = tk.Frame(root, bg='yellow')
frame.pack(side='top', fill='both', expand='yes')

label_1 = tk.Label(frame, text='label_1', font=helv12)
label_1.pack(pady=5)

label_2 = tk.Label(frame, text='label_2', font=helv16)
label_2.pack(pady=5)

# change helv16 (need to use a copy of the instance)
helv16a = helv16.copy()
helv16a.config(weight='normal', underline=1, slant='italic')
label_3 = tk.Label(frame, text='label_3', font=helv16a)
label_3.pack(pady=5)

# another way to set fonts using just a tuple
cosa24 = ('Comic Sans MS', 24, 'bold')
label_4 = tk.Label(frame, text='label_4', font=cosa24)
label_4.pack(pady=5)

# tuple examples of common fonts (some might be just on Windows)
#myfont = ('times', 20, 'bold')
#myfont = ('times', 12, 'normal')
#myfont = ('courier', 20, 'bold')
#myfont = ('helvetica', 20, 'bold italic')
#myfont = ('verdana', 20, 'bold italic')

# you can also use font designation this way
label_5 = tk.Label(frame, text='label_5', font='courier …
sneekula 969 Nearly a Posting Maven
sneekula 969 Nearly a Posting Maven

Another look at the Tkinter GUI toolkit and its grid layout manager:

''' tk_grid_test101.py
explore the Tkinter grid layout
don't mix pack() and grid() within same frame container widget
place() and grid() can be used in the same frame

'''

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

root = tk.Tk()
w = h = 200
root.geometry("%dx%d" % (w, h))
root.title("buttons in frames")

frame1 = tk.Frame(root, bg='yellow')
frame1.pack(side='top', fill='both', expand='yes')

frame2 = tk.Frame(root, bg='green')
frame2.pack(side='top', fill='both', expand='yes')

# these buttons are in frame1
btn1 = tk.Button(frame1, text=" button1 ")
btn2 = tk.Button(frame1, text=" button2 ")
btn3 = tk.Button(frame1, text=" button3 ")
btn4 = tk.Button(frame1, text=" button4 ")
# these buttons are in frame2
btn5 = tk.Button(frame2, text=" button5 ")
btn6 = tk.Button(frame2, text=" button6 ")

# lay out buttons ...
# these buttons are in frame1
btn1.grid(row=0, column=0, pady=5)
btn2.grid(row=1, column=0)
btn3.grid(row=1, column=1, padx=5)
btn4.grid(row=1, column=2)
# these buttons are in frame2
btn5.grid(row=0, column=0, pady=5)
btn6.grid(row=1, column=0)

root.mainloop()

Thanks vegaseat for this hint!
Display --> http://prntscr.com/l8g34

sneekula 969 Nearly a Posting Maven

line 15
return estimate
should be outside the loop

sneekula 969 Nearly a Posting Maven

You can insert a print statement for testing the progress, and see how the higher values bubble to the end and lower values bubble to the start of the list:

myList=[43,21,12,80,3,2,35]
print(myList)
print('-'*30)

end = len(myList)-1
while (end != -1):
    swapped = -1
    for i in range(0, end):
        if myList[i] > myList[i+1]:
            temp = myList[i]
            myList[i] = myList[i+1]
            myList[i+1]= temp

            print(myList)  # test print to follow progress of sort

            swapped = i
    end = swapped

print('-'*30)
print(myList)

'''
[43, 21, 12, 80, 3, 2, 35]
------------------------------
[21, 43, 12, 80, 3, 2, 35]
[21, 12, 43, 80, 3, 2, 35]
[21, 12, 43, 3, 80, 2, 35]
[21, 12, 43, 3, 2, 80, 35]
[21, 12, 43, 3, 2, 35, 80]
[12, 21, 43, 3, 2, 35, 80]
[12, 21, 3, 43, 2, 35, 80]
[12, 21, 3, 2, 43, 35, 80]
[12, 21, 3, 2, 35, 43, 80]
[12, 3, 21, 2, 35, 43, 80]
[12, 3, 2, 21, 35, 43, 80]
[3, 12, 2, 21, 35, 43, 80]
[3, 2, 12, 21, 35, 43, 80]
[2, 3, 12, 21, 35, 43, 80]
------------------------------
[2, 3, 12, 21, 35, 43, 80]
'''

Also the C type swap

        temp = myList[i]
        myList[i] = myList[i+1]
        myList[i+1]= temp

can be replaced with a Python tuple swap

myList[i+1], myList[i] = myList[i], myList[i+1]

sneekula 969 Nearly a Posting Maven

Let's give it a try:

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

app = QApplication(sys.argv)

# ----- start your widget test code ----


# create the label
label = QLabel()
label.show()
# insert a text string
label.setText('Hello fron DaniWeb!')
print(sys.argv)


# ---- end of widget test code -----

app.exec_()

''' my console output -->
['C:\\Python33\\BS\\pqt_sys_argv.py']
'''

QApplication() expects a list, but you can feed it an empty list if you don't want to putz around with sys.argv

from PyQt4.QtCore import *
from PyQt4.QtGui import *

app = QApplication([])

# ----- start your widget test code ----


# create the label
label = QLabel()
label.show()
# insert a text string
label.setText('Hello fron DaniWeb!')


# ---- end of widget test code -----

app.exec_()
Gribouillis commented: good help +13
sneekula 969 Nearly a Posting Maven

"You only live once, but if you do it right, once is enough."
~~~ Mae West

sneekula 969 Nearly a Posting Maven

Here is an example that gets the size of the image and centers the splash screen:

# a Tkinter splash screen 
# (uses a GIF image file, does not need PIL)
# tested with Python27

import Tkinter as tk

class SplashScreen(tk.Toplevel):
    def __init__(self, master, image=None, timeout=1000):
        """
        create a splash screen from a specified image file
        keep splash screen up for timeout milliseconds
        """
        tk.Toplevel.__init__(self, master, relief='raised', borderwidth=5)
        self.main = master

        # don't show main window
        self.main.withdraw()
        self.overrideredirect(1)

        # use Tkinter's PhotoImage for .gif files
        self.image = tk.PhotoImage(file=image)
        self.after_idle(self.centerOnScreen)

        self.update()
        self.after(timeout, self.destroySplash)

    def centerOnScreen(self):
        self.update_idletasks()
        # get the width and height of the image
        self.width, self.height = self.image.width(), self.image.height()

        xmax = self.winfo_screenwidth()
        ymax = self.winfo_screenheight()

        x0 = self.x0 = xmax/2 - self.width/2
        y0 = self.y0 = ymax/2 - self.height/2
        self.geometry("%dx%d+%d+%d" % (self.width, self.height, x0, y0))
        self.createSplash()

    def createSplash(self):
        # show the splash image
        self.canvas = tk.Canvas(self, height=self.height, width=self.width)
        self.canvas.create_image(0,0, anchor='nw', image=self.image)
        self.canvas.pack()

    def destroySplash(self):
        # bring back main window and destroy splash screen
        self.main.update()
        self.main.deiconify()
        self.withdraw()

# test it ...
if __name__ == "__main__":
    import os

    # main window
    root = tk.Tk()
    s = "This was a test of the gif image splash screen"
    lbl = tk.Label(root, text=s, bg='yellow')
    lbl.grid(row=0, column=0, padx=5, pady=5)

    # pick a splash screen GIF image file you have in the working folder
    # otherwise give full path
    image_file = "TWEEK600.gif"
    assert os.path.exists(image_file)
    s = SplashScreen(root, timeout=5000, image=image_file)

    root.mainloop()
Ene Uran commented: thank you +12
sneekula 969 Nearly a Posting Maven

Use the Python module timeit to test the speed of a function. Here is an easy way:

'''get_timing.py
use Python module timeit in a wrapper
modified vegaseat code
works with Python2 and Python3
'''

def get_timing(fs, number=10000, module="__main__"):
    """
    this wrapper can be used to time any function
    pass full function call in as a string eg. 'func(arg1, arg2)'
    number = number of timeit loops
    module namespace is autodetected
    """
    import timeit
    import inspect
    # extract function name
    q1 = fs.split('(')
    f = eval(q1[0])
    # extract arguments
    q2 = q1[1].strip(')')
    if q2:
        args = eval(q2)
    else:
        args = None
    name = f.__name__
    # get module namespace
    module = inspect.getmodule(f).__name__
    if args == None:
        st1 = "%s()" % (name)
    elif type(args) == tuple:
        st1 = "%s%s" % (name, args)
    elif type(args) == str:
        st1 = "%s('%s')" % (name, args)
    else:
        st1 = "%s(%s)" % (name, args)
    st2 = "from %s import %s" % (module, name)
    t = timeit.Timer(st1, st2)
    # elapsed time is in microseconds
    print("Function %s took %.2f microseconds/pass" % \
        (st1, 1000000*t.timeit(number=number)/number))
    # optional ...
    return eval(fs)

def gcd3(x, y):
    """greatest common denominator, non-recursive"""
    while y:
        x, y = y, x % y
    return x

def test():
    pass

# testing ...
if __name__=="__main__":
    import math

    # no arguments
    print(get_timing('test()'))

    # one argument
    print(get_timing("math.log(1000)"))

    # two arguments
    print(get_timing('gcd3(1251, 3357)'))
vegaseat commented: nice +14
sneekula 969 Nearly a Posting Maven

We must believe in luck. For how else can we explain the success of those we don't like?
~~~ Jean Cocteau

sneekula 969 Nearly a Posting Maven

"Borrow money from a pessimist - they don’t expect it back."
~~~ E. Fudd

sneekula 969 Nearly a Posting Maven

This Tkinter example moves a ball (circle) in a horizontal line, but you can change that to a vertical line:

# a Tkinter moving ball that wraps around

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

root = tk.Tk()
root.title("Tkinter Moving Ball")

w = 420
h = 300
cv = tk.Canvas(root, width=w, height=h, bg='black')
cv.pack()

# create 50x50 square box for the circle boundries
box = (0, 120, 50, 170)
# create the ball object
# give it a tag name for reference
cv.create_oval(box, fill="red", tag='red_ball')

# endless animation loop till window corner x is clicked
x = 0
# set x, y increments
dx = 1
dy = 0
while True:
    # move the ball by given increments
    cv.move('red_ball', dx, dy)
    # 15 millisecond delay
    # higher value --> slower animation
    cv.after(15)
    cv.update()
    # when left side of ball hits wall reset
    x += dx
    if x >= w:
        print(x) # test
        cv.move('red_ball', -x, dy)
        x = 0


root.mainloop()

Should give you enough of a hint.

sneekula 969 Nearly a Posting Maven

Using those Tkinter tags:

# which widget has been clicked?

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

def clicked(event):
    """display the clicked oval's name"""
    # 'current' matches the item under the mouse pointer
    root.title( widget_list[cv.find_withtag('current')[0]-1] )


root = tk.Tk()
root.title('Click on ovals')

cv = tk.Canvas()
cv.pack()

oval1 = cv.create_oval(10, 30, 40, 50, fill='red', tags='click')
oval2 = cv.create_oval(50, 70, 80, 90, fill='blue', tags='click')
oval3 = cv.create_oval(90, 110, 120, 130, fill='green', tags='click')

# in order of creation
widget_list = ['oval1', 'oval2', 'oval3']

# left mouse click = '<1>'
cv.tag_bind('click', '<1>', clicked)

root.mainloop()

Not sure if this is new?

vegaseat commented: different approach +15
sneekula 969 Nearly a Posting Maven

Tired of turtles? Here some clever German educators have added advanced options to the venerable Tkinter turtle module:

# frog is a somewhat advanced turtle graphics module
# get frog-1.0.1.zip from:
# http://www.zahlenfreund.de/python/frog.html
# see also:
# http://pypi.python.org/pypi/frog/1.0.0
# unzip and copy frog.py into the Python lib/site-packages folder
# or use it in the working folder
# to make frog.py work on Python32 change line 51 to
# from PIL import ImageGrab

import frog

def draw_square(side=50):
    """
    kermit draws a square
    starts at the center of the pond
    """
    for n in range(4):
        kermit.move(side)
        kermit.turn(90)

def draw_triangle(side=50):
    """
    kermit draws a square
    """
    for n in range(3):
        kermit.move(side)
        kermit.turn(120)

# pond forms the canvas
pond = frog.Pool(width = 400, height = 400)
pond.title = "Watch Kermit move and draw"
pond.bgcolor = "lightblue"
# kermit forms the drawing pen
kermit = frog.Frog(pond)
kermit.shape = "frog"
kermit.bodycolor = "green"

draw_square(100)
# turn kermit 160 degrees
kermit.turn(180)
draw_square(100)

kermit.turn(90)
draw_triangle(100)

kermit.turn(180)
draw_triangle(100)

try:
    # use a wave sound file you have
    kermit.sing("boing.wav")
except:
    print("no soundfile")

s = "Kermit has moved a total of %0.1f pixels" % kermit.way
pen = frog.Frog(pond, visible=False)
pen.jumpto(-170, 140)
pen.color = "red"
pen.font = "Arial",8,"bold"
pen.write(s)

pond.ready()

A revisit.

sneekula 969 Nearly a Posting Maven

The Python module pygame is a GUI for games, animated or otherwise. Here is some simple animated drawing code:

# exploring the Python module pygame
# pygame free from: http://www.pygame.org/
# or: http://www.lfd.uci.edu/~gohlke/pythonlibs/
# bubble circles up the screen

import pygame as pg
import random

def draw(screen, background, width, height):
    # create a few random values
    x = random.randint(10, width)
    y = random.randint(100, height)
    radius = random.randint(20, 50)
    # random (r, g, b) color, avoid black (0, 0, 0)
    r = random.randint(20, 255)
    g = random.randint(20, 255)
    b = random.randint(20, 255)
    # bubble up until circle center (x, y) reaches top
    while y > 0:
        background.fill(pg.color.Color('black'))
        # draw.circle(Surface, color, pos, radius, width)
        # width of 0 (default) fills the circle
        pg.draw.circle(background, (r, g, b), (x, y), radius, 3)
        y -= 1
        # put the circle on the screen
        screen.blit(background, (0, 0))
        # update the screen
        pg.display.flip()

def main():
    pg.init()
    # create the pg window, give it a caption and bg color
    width = 680
    height = 460
    screen = pg.display.set_mode((width, height))
    pg.display.set_caption(' random bubbles')
    background = pg.Surface(screen.get_size())
    background.fill(pg.color.Color('black'))
    clock = pg.time.Clock()
    # the pg event loop ...
    while True:
        # quit when window corner x is clicked
        # there is a small delay
        for event in pg.event.get():
            if event.type == pg.QUIT:
                raise SystemExit
        draw(screen, background, width, height)
        # use a frame rate of 30 to avoid flickering
        clock.tick(30)

if __name__ == "__main__":
    main()
vegaseat commented: nice example +14
sneekula 969 Nearly a Posting Maven

Crazy Horse the great leader and warrior of the Teton Sioux.

sneekula 969 Nearly a Posting Maven

In war, truth is the first casualty.
-- Aeschylus (Greek dramatist 525 BC - 456 BC)

sneekula 969 Nearly a Posting Maven

Working people always finance the rich folks gala events.

debasisdas commented: agree agree agree..... +0
sneekula 969 Nearly a Posting Maven

I would imagine that Dallas and Arlington Home Inspectors listen to the sound of all those Dollar bills the are cheating their unsuspecting customers out of.

Seriously, I find that classical music is best for any good programming language.

sneekula 969 Nearly a Posting Maven

MASH

sneekula 969 Nearly a Posting Maven

You don't always sort a list of strings alphabetically, sometimes you want to sort by the length of the string:

# sort a list of strings by length of string

text = "I have taken a vow of poverty to annoy me send money"

mylist = text.split()

print( "Original list: \n%s\n" % mylist )

mylist_sorted = sorted(mylist, key=len, reverse=True)
print( "Sorted by length of word: \n%s" % mylist_sorted )

"""my result -->
Original list: 
['I', 'have', 'taken', 'a', 'vow', 'of', 'poverty', 'to', 'annoy',
 'me', 'send', 'money']

Sorted by length of word: 
['poverty', 'taken', 'annoy', 'money', 'have', 'send', 'vow', 'of',
 'to', 'me', 'I', 'a']

In a similar fashion you can find the longest word in a list of words:

# find the longest word in a text

text = "I have taken a vow of poverty to annoy me send money"

# Python25 and higher allows key
word_list = text.split()
print( "The longest word is %s" % max(word_list, key=len) )
sneekula 969 Nearly a Posting Maven

He was a devout Christian, so may the Lord bless him!

sneekula 969 Nearly a Posting Maven

Here is a basic example of the use of Sqlite3

# test the sqlite3 module, write and read a database file
# note that Python25 and higher versions have sqlite3 builtin
# sqlite3.connect(database, timeout=5.0, isolation_level=None,
#   detect_types=0, factory=100)
# timeout=5.0 --> allows multiple access for 5 seconds (for servers)
# isolation_level=None -->  autocommit mode
# detect_types=0 --> native types TEXT, INTEGER, FLOAT, BLOB and NULL
# factory=100 --> statement cache to avoid SQL parsing overhead
# tested with Python26 and Python31
# Source:  Sneekula

import sqlite3

# create/connect to a permanent file database
con = sqlite3.connect("my_db.db3")
# for temporary testing you can use memory only
#con = sqlite3.connect(":memory:")

# establish the cursor, needed to execute the connected db
cur = con.cursor()

# create/execute a table:
# (optionally used capital letters to show commands)
cur.execute('CREATE TABLE IF NOT EXISTS clients \
    (id INT PRIMARY KEY, \
    firstname CHAR(60), \
    lastname CHAR(60))')

# insert several lines at once using a
# list of (id, firstname, lastname) tuples
# use try/except or the existing db will complain about
# the non-unique id since it is already in the db
try:
    clients = [
    (107, "Ella", "Fitzgerald"),
    (108, "Louis", "Armstrong"),
    (109, "Miles", "Davis")
    ]
    cur.executemany("INSERT INTO clients (id, firstname, lastname) \
        VALUES (?, ?, ?)", clients )
except:
    pass

# add another client
# again, use try/except or the existing db will complain about
# the non-unique id if it is already in the db
try:
    new_client = (110, "Benny", "Goodman")
    cur.execute("INSERT INTO …
sneekula 969 Nearly a Posting Maven

Typical Dutch humor.

sneekula 969 Nearly a Posting Maven

Actually quite simple using button["text"]:

# explore Tkinter button as simple toggle

import Tkinter as tk  # for Python3 use import tkinter as tk

def toggle_text():
    """toggle button text between Hi and Goodbye"""
    if button["text"] == "Hi":
        # switch to Goodbye
        button["text"] = "Goodbye"
    else:
        # reset to Hi
        button["text"] = "Hi"


root = tk.Tk()
root.title("Click the Button")

button = tk.Button( text="Hi", width=12, command=toggle_text)
button.pack(padx=100, pady=10)

root.mainloop()
vegaseat commented: very good example +10
sneekula 969 Nearly a Posting Maven

"Invent Your Own Computer Games with Python" is a free e-Book that teaches you how to program in the Python programming language. Each chapter gives you the complete source code for a new game, and then teaches the programming concepts from the example. Many examples are written with the GUI toolkit module pygame, see:
http://inventwithpython.com/

Editor's note:
Thanks snee, this chapter in the e-Book has a very nice introduction to pygame programming ...
http://inventwithpython.com/chapter16.html

sneekula 969 Nearly a Posting Maven

I am hoping for a robotic laser beam lawn mower. :)

sneekula 969 Nearly a Posting Maven

I modified the code in the previous post to join two images into one:

# use a drawing bitmap and wx.MemoryDC to create a canvas you can
# draw on and optionally save the drawing to an image file
# here we draw two images side by side and save the combined image
# vegaseat code modified by sneek

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, title, mysize):
        wx.Frame.__init__(self, parent, -1, title, size=mysize)
        # create a bitmp for display and optional saving
        self.show_bmp = wx.StaticBitmap(self)
        # get the width and height for the blank bitmap
        w, h = self.GetClientSize()
        # create a blank bitmap as a drawing background
        # should be large enough to fit the 2 images side by side
        draw_bmp = wx.EmptyBitmap(w, h)

        # put a canvas on top of draw_bmp
        canvas = wx.MemoryDC(draw_bmp)

        # fill the canvas white
        canvas.SetBrush(wx.Brush('white'))
        canvas.Clear()

        # pick 2 image files you have in the working folder
        # (can be a .jpg, .png, .gif, .bmp image files)
        # note that filenames are case sensitive in Linux
        image1 = wx.Bitmap("Duck_right.jpg")
        image2 = wx.Bitmap("Duck_left.jpg")

        # draw the 2 images side by side
        canvas.DrawBitmap(image1, 0, 0)
        canvas.DrawBitmap(image2, w/2, 0)

        # this also shows your drawing
        self.show_bmp.SetBitmap(draw_bmp)

        # get the image object
        myimage = self.show_bmp.GetBitmap()
        # save it to a file
        myimage.SaveFile("joined_pic1.jpg", wx.BITMAP_TYPE_JPEG)


app = wx.App(0)
# make width w large enough to have the 2 images next to each other
w = 610
# make height h large enough to fit the max height of …
sneekula 969 Nearly a Posting Maven

A man walks into a bar and asks the bartender, "If I show you a really good trick, will you give me a free drink?" The bartender considers it, and then agrees. The man reaches into his pocket and pulls out a tiny rat. He reaches into his other pocket and pulls out a tiny piano. The rat stretches, cracks his knuckles, and proceeds to play the blues.

After the man finished his drink, he asked the bartender, "If I show you an even better trick, will you give me free drinks for the rest of the evening?" The bartender agrees, thinking that no trick could possibly be better than the first. The man reaches into his pocket and pulls out a tiny rat. He reaches into his other pocket and pulls out a tiny piano. The rat stretches, cracks his knuckles, and proceeds to play the blues again. The man reaches into another pocket and pulls out a small bullfrog, that begins to sing along with the rat's music.

While the man is enjoying his free drinks, a stranger confronts him and offers him $100,000 for the bullfrog. "Sorry," the man replies, "he's not for sale." The stranger increases the offer to $200,000 cash up front. "No," he insists, "he's not for sale." The stranger again increases the offer, this time to $500,000 cash, tax free too. The man finally agrees, and turns the frog over to the stranger in exchange for the money.

"Are you …

ahihihi... commented: :D tad funny +0
sneekula 969 Nearly a Posting Maven

If there is no space in the rank or name you can do it this simple way:

mydata = """\
<Ranking: AA (John)>
<Ranking: CA (Peter)>
<Ranking: TA-A (Samantha)>
"""

rank_list = []
for line in mydata.split('\n'):
    print line, line.split()  # testing
    if line:
        rank_list.append(line.split()[1])

print
print rank_list
    
"""my result -->
<Ranking: AA (John)> ['<Ranking:', 'AA', '(John)>']
<Ranking: CA (Peter)> ['<Ranking:', 'CA', '(Peter)>']
<Ranking: TA-A (Samantha)> ['<Ranking:', 'TA-A', '(Samantha)>']
 []

['AA', 'CA', 'TA-A']
"""
sneekula 969 Nearly a Posting Maven

Just testing wxPython's wx.TextCtrl widget used as an edit field for input and output of text based data:

# testing wxPython's
# wx.TextCtrl(parent, id, value, pos, size, style)
# a widget used for text data input or output
# note:
# style=wx.TE_PROCESS_ENTER is needed for Linux to
# respond to the enter key event!!!
# snee

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.SetBackgroundColour("yellow")

        s = "Enter name below:"
        edit_label = wx.StaticText(self, wx.ID_ANY, s)
        # create a single line edit input area
        self.edit = wx.TextCtrl(self, wx.ID_ANY, value="",
            style=wx.TE_PROCESS_ENTER)
        # put the cursor in edit
        self.edit.SetFocus()
        # respond to enter key when focus is on edit
        self.edit.Bind(wx.EVT_TEXT_ENTER, self.onEnter)

        # create a scrolled multiline text output area
        self.text_out = wx.TextCtrl(self, wx.ID_ANY, value="",
            style=wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY)
        
        # use a box sizer for vertical widget layout
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(edit_label, 0, wx.LEFT|wx.TOP|wx.EXPAND, border=10)
        sizer.Add(self.edit, 0, wx.ALL|wx.EXPAND, border=10)
        sizer.Add(self.text_out, 2, wx.ALL|wx.EXPAND, border=10)
        self.SetSizer(sizer)

    def onEnter(self, event):
        """the Enter key has been pressed, do something"""
        # GetValue() gives a string
        name = self.edit.GetValue()
        s = "You entered the name: " + name + '\n'
        # text output, either method works
        #self.text_out.AppendText(s)
        self.text_out.WriteText(s)
        # clear edit input space
        self.edit.Clear()


app = wx.App(0)
# create a MyFrame instance and show the frame
MyFrame(None, 'testing wx.TextCtrl()', (300, 480)).Show()
app.MainLoop()

Notice the special requirement for Linux users.

Gribouillis commented: Useful test. Thanks also for linux users :) +2
sneekula 969 Nearly a Posting Maven

Here is a simple number project:

Prime numbers are positive integer numbers that are only divisible by itself or one. For example 2, 3, 5, 7, 11, 13, 17, are prime numbers, by convention 1 is not a prime number.

Palindrome numbers are numbers in which the decimal digits are the same read left to right as they are read right to left. For example 77, 131, 1441.

Your mission is to write a script that determines and prints all palindrome prime numbers less than 100000. Exclude the simple stuff like one digit numbers.

vegaseat commented: interesting +14
sneekula 969 Nearly a Posting Maven

"The hardest thing in the world to understand is the income tax."
~~~ Albert Einstein

sneekula 969 Nearly a Posting Maven

An apple turnover and a cup of hot chocolate.

sneekula 969 Nearly a Posting Maven

Kindly go to the C++ forum.

I went to the C++ forum, but nothing happened. :)

Nick Evan commented: :) +0
sneekula 969 Nearly a Posting Maven

I made an attempt on user friendly data entry with just such a simple temperature converter program, see:
http://www.daniweb.com/forums/showthread.php?p=992595#post992595

sneekula 969 Nearly a Posting Maven

The ultimate user friendly Temperature Converter program. If you put an 'F' or 'f' on the end of the temperature you enter it will give you Celsius. Otherwise it simply assumes you entered a Celsius value and want Fahrenheit:

# a Fahrenheit/Celsius program easy on the user
# tested with Python25
# snee

def f2c(t):
    """given t Fahrenheit return Celsius"""
    return 5/9.0 * (t - 32)

def c2f(t):
    """given t Celsius return Fahrenheit"""
    return 9/5.0 * t + 32

def extract_number(s):
    """
    extract the numeric value from string s
    (the string can contain only one numeric value)
    return the number or None
    """
    ts = ""
    for c in s:
        if c in '1234567890.-':
            ts += c
    if ts:
        # convert number to int or float
        return eval(ts)
    else:
        return None

def pick_cf(s):
    """given a numeric string s select f or c calculation"""
    t = extract_number(s)
    print('')
    if not t:
        print("***need a number***")
        return False
    if 'f' in s.lower():
        print( "%0.2f Fahrenheit is %0.2f Celsius" % (t, f2c(t)) )
    else:
        print( "%0.2f Celsius is %0.2f Fahrenheit" % (t, c2f(t)) )
    return True
    
prompt = """
Enter a temperature ending with an F to calculate Celsius
otherwise the temperature is assumed to be Celsius and will
give the result in Fahrenheit (press just enter to quit): """

while True:
    s = raw_input(prompt)
    if not s:
        break
    s = pick_cf(s)

Yes Gloria, if you entered $12.99 it will give you the Fahrenheit temperature of 12.99 Celsius.

Ene Uran commented: nicely done bud +8
Lardmeister commented: good thinking +6
sneekula 969 Nearly a Posting Maven

Which Computer Language would you like to know more about, or even start to learn?

sneekula 969 Nearly a Posting Maven

What does not destroy me, makes me stronger.
~~~ Friedrich Nietzsche

sneekula 969 Nearly a Posting Maven

Be careful when you fight the monsters, lest you become one.
~~~ Friedrich Nietzsche

sneekula 969 Nearly a Posting Maven

Fibonacci numbers and prime numbers are always a hot topic! Your contribution is welcome!