Ene Uran 638 Posting Virtuoso

Just a short little C program to send beeps to the PC internal speaker. Beep(frequency_hrz, duration_ms) is a WinAPI function as is Sleep(ms).

Ene Uran 638 Posting Virtuoso

Powers of 2 are closly linked to the position values of binary numbers. The most right position is 2 to the power 0 = 1 then goes to the left with 2 to the power 1 = 2, 2 to the power 2 = 4 and such. If you want to know that a number fits this sequence, you can use this litle code.

Ene Uran 638 Posting Virtuoso
Gribouillis commented: Nice link. I will try it. +4
Ene Uran 638 Posting Virtuoso

A quick look at Tkinter's radio and check buttons:

# exploring multiple Tkinter radio buttons
# radio buttons only allow one item to be selected/checked
# ene

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

def rb_selected():
    # show checked/selected radio button item
    ix = rb_v.get()
    label['text'] = 'you selected %s' % mylist[ix]

root = tk.Tk()

# used by the radio buttons as index
rb_v  = tk.IntVar()

mylist = [
'apple',
'orange',
'banana',
'pear',
'apricot'
]

# list(range()) needed for Python3
rb = list(range(len(mylist)))
for ix, text in enumerate(mylist):
    # command is optional and responds to any rb changes
    rb[ix] = tk.Radiobutton(root, text=text, value=ix,
        variable=rb_v, command=rb_selected)
    rb[ix].grid(row=ix, column=0, sticky='w')

label = tk.Label(root, width=20)
label.grid(row=ix+1, column=0, pady=5, sticky='w')

# you can preset one radio button
# default is first button (ix=0)
rb_v.set(2)
# show initial selection
rb_selected()

root.mainloop()
# exploring multiple Tkinter check buttons
# check buttons allow more than one item to be selected/checked
# ene

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

def cb_checked():
    # show checked check button item(s)
    label['text'] = ''
    for ix, item in enumerate(cb):
        if cb_v[ix].get():
            label['text'] += '%s is checked' % item['text'] + '\n'


root = tk.Tk()

mylist = [
'apple',
'orange',
'banana',
'pear',
'apricot'
]

# list(range()) needed for Python3
cb = list(range(len(mylist)))
cb_v = list(range(len(mylist)))
for ix, text in enumerate(mylist):
    # IntVar() tracks checkbox status (1=checked, 0=unchecked)
    cb_v[ix] = tk.IntVar()
    # command is optional and …
Ene Uran 638 Posting Virtuoso

An enlightening look at Tkinter's grid layout manager:

# looking at the Tkinter grid() layout manager
#
# The size of a grid cell in a given row or column is
# determined by its largest widget.
#
# If you give a grid layout more space than it needs,
# it will fill this space from its center on out.
# A way around this is to use place() with a frame and
# then grid() within this frame.
#
# Grid does not have an anchor positioner like pack().
#
# You can use place() and grid(), but not pack() and grid()
# within the same container widget.
#
# You can put a child grid into a parent grid.
# Ene

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

root = tk.Tk()
root.title('Grid layout')
root['bg'] = 'yellow'

b1 = tk.Button(root, text="Button1")
b2 = tk.Button(root, text="Button2", bg='green')
b3 = tk.Button(root, text="Button3")
b4 = tk.Button(root, text="Button4")
b5 = tk.Button(root, text="Button5")
b6 = tk.Button(root, text="Button6")
b7 = tk.Button(root, text="Button7", bg='blue')
# button b8 has a 3 row text
b8 = tk.Button(root, text="\nButton8\n", bg='red')

b1.grid(row=0, column=1)
# use sticky=tk.E+tk.W or sticky='ew'
b2.grid(row=1, column=0, columnspan=3, sticky='ew')
b3.grid(row=2, column=0, pady=5)
b4.grid(row=2, column=1)
# gives the entire column=2 padx=10 padding!
b5.grid(row=2, column=2, padx=10)
b6.grid(row=3, column=2)
# forces button b7 to take up padded space too
b7.grid(row=4, column=2, ipadx=10)
# button b8 has a 3 row text, so give it rowspan=3
b8.grid(row=5, column=0, rowspan=3, columnspan=3, sticky='ew')

# …
Ene Uran 638 Posting Virtuoso

A mind is like a parachute, it only works when it is open.
-- Jesse Ventura

Ene Uran 638 Posting Virtuoso

On a notebook that you take from class to class, Windows Vista is simply unacceptable since it takes at least five minutes to boot up and just about the same to shut down. I hope Windows 7 offers some drastic improvement. I could care less for silly stuff like Paint, Wordpad, Mediaplayer or Games. Those things are easy to get for free and of better quality from a number of good folks.

jephthah commented: 100% +12
Ene Uran 638 Posting Virtuoso

Simply use list():

list1 = ['a', 'b', 'c', 'd']
# this will create a new list with a different mem ref
temp_list1 = list(list1)
for i in range(len(list1)):
    temp_list1[i] = "1"
print list1;              # ['a', 'b', 'c', 'd']
print temp_list1;         # ['1', '1', '1', '1']

For nested lists you need to use deepcopy() from module copy.

shadwickman commented: Well I learned something new about using list() :P +4
Ene Uran 638 Posting Virtuoso

You mean something like this:

# data string read from a file
data = """\
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 95 20 1 0 68 87 31017559 31017578 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 91.67 24 2 0 63 86 35247737 35247714 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 91.67 24 2 0 64 87 40549054 40549031 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 92 24 2 0 63 86 42462636 42462659 4.4 32.3
gnl|dbSNP|rs13484118 gi|62750812|ref|NC_005111.2|NC_005111 95 20 1 0 63 82 45774066 45774085 4.4 32.3
"""

new_data = ""
for line in data.split('\n'):
    # replace each space with a tab
    line = line.replace(" ", "\t")
    new_data += line + '\n'

# test only ...
print(new_data)

# now write new_data string to a file
lllllIllIlllI commented: ahh! Beat me too it :P +4
Ene Uran 638 Posting Virtuoso

In complete darkness we are all the same, it is only our knowledge and wisdom that separates us.
-- Janet Jackson

Ene Uran 638 Posting Virtuoso

Let's see if the Omron Smile Scan system works on holders of State of California short term debts and bonds. California has started pay off with I.O.U.'s rather than actual money.

jephthah commented: ouch :( +12
Ene Uran 638 Posting Virtuoso

Why did we get into such a mess?
Instant food
Instant credit
Instant war
Instant debt

.. just to mention four reasons.

jephthah commented: succinct +12
Ene Uran 638 Posting Virtuoso

The last update of MS IE did me in, after it fooled around with my 'favorite folders'. I am now a very happy Firefox user.

tux4life commented: Firefox FTW!! +12
Ene Uran 638 Posting Virtuoso

The debt per person in the USA is cheap compared to other countries. Let's celebrate with Chinese fireworks! I love the stench of burning sulfur from the fireworks, much better than the normal LA stench.

ahihihi... commented: yeah +1
Ancient Dragon commented: So do I :) +36
Ene Uran 638 Posting Virtuoso

History has been kind to Winston Churchill, as it usually is to those who help save the world,
-- George W. Bush.

Ene Uran 638 Posting Virtuoso

In Python it would look like:

fout = open("test1.txt", "w")
fout.write("save something ...\n")
fout.write("save something more ...\n")
fout.close()

# or C++ style (allowed in Python2)
fout = open("test2.txt", "w")
print >>fout, "save something ..."
print >>fout, "save something more ..."
fout.close()

# more like PERL
import sys

old = sys.stdout
sys.stdout = file("test3.txt", "w")
print "save something ..."
print "save something more ..."

# reset
sys.stdout = old
The_Kernel commented: Yep, that about covers it :-) +1
Ene Uran 638 Posting Virtuoso

Here is a general notebook widget class for Tkinter:

# testing a notebook widget class for Tkinter (modified)
# Python 2.5.4 ene

import Tkinter as tk

class Notebook(object):
    """
    a notebook widget class for Tkinter applications
    """
    def __init__(self, parent):
        self.active_page = None
        self.count = 0
        self.selected = tk.IntVar(0)
        # orientation of initial tab (can go 'bottom' too)
        side = 'top'
        # new tabs go
        self.side= 'left'
        # create notebook's initial page frame
        self.tab = tk.Frame(parent)
        self.tab.pack(side=side, fill='both')
        self.page = tk.Frame(parent)
        self.page.pack(fill='both')

    def __call__(self):
        """
        parent page reference
        """
        return self.page

    def add_page(self, pg, title):
        """
        add a new page to the notebook
        """
        rb = tk.Radiobutton(self.tab, text=title, indicatoron=0, variable=self.selected,
            value=self.count, command=lambda: self.display_page(pg))
        rb.pack(fill='both', side=self.side)
        # first page is slected by default
        if not self.active_page:
            pg.pack(fill='both', expand=True)
            self.active_page = pg
        self.count += 1
        # returns reference
        return rb

    def display_page(self, pg):
        """
        shows selected page, hides former page
        """
        self.active_page.forget()
        pg.pack(fill='both', expand=True)
        self.active_page = pg


# testing the module
if __name__ == '__main__':
    root = tk.Tk()
    # use width x height + x_offset + y_offset (no spaces!)
    root.geometry("400x200+100+50")
    root.title('Testing a Tkinter notebook widget')

    nb = Notebook(root)

    # create first page (notice the instance call)
    page1 = tk.Frame(nb())
    nb.add_page(page1, 'page 1')
    # put something on the page
    # text entry field, width=width in chars, height=lines text
    text1 = tk.Text(page1, width=60, height=12, bg='yellow')
    text1.pack(fill='both')
    text1.insert(tk.INSERT, ' this is page number 1')

    # create second page, also has a button
    page2 = tk.Frame(nb())
    nb.add_page(page2, 'page 2')
    # put something on the page …
Ene Uran 638 Posting Virtuoso

The only reason many people get lost in thought is because it's unfamiliar territory."
-- Paul Dontee

Ene Uran 638 Posting Virtuoso

PyQT has an interesting widget called a dial (circular slider). Here is a simple applcation:

# use a PyQT QDial knob to select a temperature
# show Celsius and corresponding Fahrenheit values
# as the knob is rotated
# tested with PyQT4.5 and Python3.0
# ene

import sys
# has minimal namespace conflicts
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyFrame(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(150, 150, 328, 440)
        self.setWindowTitle('Convert Temperature')
        
        self.dial = QDial(self)
        self.dial.setGeometry(QRect(10, 20, 311, 351))
        self.dial.setMinimum(-50)
        self.dial.setMaximum(310)
        self.dial.setPageStep(10)
        # initial dial pointer position
        dial_pos = 50
        self.dial.setSliderPosition(dial_pos)
        self.dial.setWrapping(True)
        self.dial.setNotchTarget(3.6)
        self.dial.setNotchesVisible(True)

        self.label_c = QLabel(self)
        self.label_c.setGeometry(QRect(30, 390, 121, 31))
        font = QFont()
        font.setPointSize(11)
        self.label_c.setFont(font)
        self.label_c.setAlignment(Qt.AlignCenter)

        self.label_f = QLabel(self)
        self.label_f.setGeometry(QRect(170, 390, 131, 31))
        font = QFont()
        font.setPointSize(11)
        self.label_f.setFont(font)
        self.label_f.setAlignment(Qt.AlignCenter)
        
        # start up
        self.show_temps()
        # update show_temps()
        self.connect(self.dial, SIGNAL("sliderMoved(int)"),
            self.show_temps)

    def show_temps(self):
        """
        get the C value from the dial label
        calculate F value and show
        """ 
        c = float(self.dial.value())
        s_c = "%0.1f Celsius" % c
        self.label_c.setText(s_c)
        f = c*9/5.0 + 32
        s_f = "%0.1f Fahrenheit" % f
        self.label_f.setText(s_f)
        

app = QApplication(sys.argv)
frame = MyFrame()
frame.show()
sys.exit(app.exec_())

Sorry, I am having real problems with my HP notebook, the keyboard is of very poor quality and misses keystrokes a lot!

Ene Uran 638 Posting Virtuoso

Those who know how to win are more numerous than those who know how to make proper use of their victories.
--- Polybius

Ene Uran 638 Posting Virtuoso

Draw a simple bar chart with PyQT:

# use PyQT to draw a simple vertical bar chart
# tested with PyQT4.5 and Python3.0
# ene

import sys
# simplified import, hopefully no namespace conflicts
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class BarChart(QWidget):
    def __init__(self, data, parent=None):
        QWidget.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(300, 300, 360, 320)
        self.setWindowTitle('A Simple Bar Chart')
        self.data = data

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        
        # set color and width of line drawing pen
        painter.setPen(QPen(Qt.black, 2))
        
        # drawLine(x1, y1, x2, y2) from point (x1,y1) to (x2,y2)
        # draw the baseline
        painter.drawLine(20, 280, 340, 280)        

        # set up color and width of the bars
        width = 20
        painter.setPen(QPen(Qt.red, width))
        delta = width + 5
        x = 30
        for y in self.data:
            # correct for width
            y1 = 280 - width/2
            y2 = y1 - y + width/2
            # draw each bar
            painter.drawLine(x, y1, x, y2)
            # add values to the top of each bar
            s = str(y)
            painter.drawText(x-8, y2-15, s)
            x += delta        

        painter.end()


# data to be graphed
data = [30, 45, 80, 150, 220, 180, 110, 75, 50, 35, 20, 10]
app = QApplication(sys.argv)
bc = BarChart(data)
bc.show()
app.exec_()
Ene Uran 638 Posting Virtuoso

The latest Python version has added some candy:

# Python3.1 allows formatting of thousands
# and defaults format indexing in print()
# ene

n = 123456789
print(format(n, ',d'))

"""
my display -->
123,456,789
"""

m = 1234567.8912
print(format(m, ',.2f'))

"""
my display -->
1,234,567.89
"""

amount = format(1234567, ',d')
price = format(1234.56, ',.2f')
# note that {} defaults to the proper arg index
print('{} bottles at ${} each'.format(amount, price))

"""
my display -->
1,234,567 bottles at $1,234.56 each
"""

I have Python25, Python26, Python30, and Python31 installed on my homely Vista computer. To easily select which Python version to use I like the IDE Editra (wxPython based) and its Launch plugin.

Ene Uran 638 Posting Virtuoso

I think we may have talked about this before, but I can't find it. Here is a way to use a sound file inside the Python code and play it. First create a base64 encoded string of the binary sound file:

# create a base64 encoded string from binary sound data
# and limit the length of each data line to n characters
# ene

import base64

def text_lines(data, n):
    """
    write a long one line text as lines of n char each
    """
    s = ""
    for ix, c in enumerate(data):
        if ix % n == 0 and ix != 0:
            s += c + '\n'
        else:
            s += c
    return s

# pick a wave file that is in the working folder
wave_file = "pop.wav"
# this is a binary read
data = base64.b64encode(open(wave_file, 'rb').read())
data = text_lines(data, 70)
print "wav_base64='''\\\n" + data + "'''"

"""
highlight and copy the resulting base64 wav string to embed in program
code, use wav = base64.b64decode(wav_base64) to decode to binary data:

wav_base64='''\
UklGRuABAABXQVZFZm10IBAAAAABAAEAESsAABErAAABAAgAZGF0YbsBAACAgICAgICAgIC
AgICAfX12aVtQS0hJSk5TZpWyv8LBwMC/vry2nWxLPTs9PT5AR05pn77BwcC/vruxlGtJP
T09PkBHU3qrv8DAv7+7tKiGWUA8PT4+Qk1tm7fAv7++ubKmhl1CPD0+P0NPbZayv8C/vbe
vooNdRD0+PkBIWXWVrru/vbmypo5uU0I+P0NLWG6JorO7vLm0rJyBZlBEQkNIUF5xiJ2wu
bq4s6qZg21ZTUhITFRhcoaaqLGzsayilIFvYFVQUFNZY29/j52orKunnpKFdmheWFVWWmF
seYiXoqmrqaKXi390amRfXmBka3aDj5ifoqGemZGIfXJpY2FiZmx0fYePlpqcmpSNhHpyb
Wloam91foaNk5eXlZGMhH12b2xqam1xd32Ei5CVlpSPiYF6dHFvbnByd36Fi4+SkY6KhoN
+end3d3h8gYaKjIyMioeDf3t4dnZ3eX2BhYiKi4uJhoJ+eXZ1dnd6fICFiY2PjoyHgnx3d
XNzdHZ6f4WKjpCPjIiEf3t3dHNzdXh8goeLjY2NiYWBfHh0cnJzdnl9gYSGh4aFg398eXd
2d3l8foCChIaIh4aEgQA='''

"""

Now you can transfer the result to your Python program and play the sound without having to attach the sound file:

# playing a base64 encoded wave sound string with wxPython's
# wx.SoundFromData(sound_data) and sound.Play()
# ene

import wx
import base64

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize, sound_data):
        wx.Frame.__init__(self, parent, -1, mytitle, size=mysize)
        self.SetBackgroundColour("blue")
        # use a small delay to display the frame before sound …
Nick Evan commented: Random rep for effort put in 'beginner' threads :) +18
sneekula commented: wonderful +8
Ene Uran 638 Posting Virtuoso

For those of you who like to calculate in fractions:

# Python30 has a module fraction that allows you to
# calculate with fractions, the result is a fraction
# is more precise than using floating point numbers
# ene

from fractions import Fraction

# Fraction(numerator, denominator)
# for instance fraction 2/3 would be Fraction(2, 3)
a = Fraction(2, 3)
b = Fraction(2, 5)
c = Fraction(3, 7)

print( "%s + %s = %s" % (a, b, a + b) )
print( "%s + %s + %s = %s" % (a, b, c, a + b + c) )
print( "(%s + %s)/(%s) = %s" % (a, b, c, (a + b)/c) )

"""
my display -->
2/3 + 2/5 = 16/15
2/3 + 2/5 + 3/7 = 157/105
(2/3 + 2/5)/(3/7) = 112/45
"""
Ene Uran 638 Posting Virtuoso

Did you have a bad day?

Ene Uran 638 Posting Virtuoso

Tkinter has some nice pop-up dialogs that can also be used for regular console programs. Here is an example to use if you want to get a filename from a pop-up window. It works with Python2x or Python3x, just read the comments:

# use Tkinter's file dialog window to get
# a file name with full path, you can also use
# this to get filenames for a console program
# askopenfilename() gives one selected filename

# with Python25 use ...
#import Tkinter as tk
#from tkFileDialog import askopenfilename

# with Python30 use ...
import tkinter as tk
from tkinter.filedialog import askopenfilename

root = tk.Tk()
# show askopenfilename dialog without the Tkinter window
root.withdraw()

# default is all file types
file_name = askopenfilename()

print(file_name)
Ene Uran 638 Posting Virtuoso

Here is an example without a titlebar and showing fullscreen:

# wx.Frame with no title bar and showing fullscreen
# modified from vegaseat's example

import wx

def exit(event):
    frame.Close(True)

app = wx.App(0)
# create a window, no-parent, -1 is default ID, style with no titlebar
frame = wx.Frame(parent=None, id=-1, pos=(50,100), size=(300,200), 
    style=wx.MINIMIZE_BOX)
frame.SetBackgroundColour('green')
frame.ShowFullScreen(True, style=wx.FULLSCREEN_ALL)

# provide exit for a frame without titlebar
quit = wx.Button(frame, id=-1, label='Exit', pos=(0, 0))
quit.Bind(wx.EVT_BUTTON, exit)

# show the window
frame.Show(True)

# start the event loop
app.MainLoop()
Ene Uran 638 Posting Virtuoso

A small Python/PyQT4 utility program to find out what kind of fonts your computer has:

# bring up a font dialog with PyQT4
# show the selected font using a sample text

import sys
# hopefully no namespace conflicts
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class FontDialog(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setGeometry(10, 100, 250, 110)
        self.setWindowTitle('QFontDialog')

        hbox = QVBoxLayout()

        button = QPushButton('Font Dialog')
        self.connect(button, SIGNAL('clicked()'), self.showDialog)
        
        # the label autosizes to the text
        text = "The quick brown fox jumps over the lazy dog"
        self.label = QLabel(text)
        self.label.move(130, 20)
        
        self.edit = QTextEdit()

        hbox.addWidget(button)
        hbox.addWidget(self.label)
        hbox.addWidget(self.edit)
        self.setLayout(hbox)

    def showDialog(self):
        font, ok = QFontDialog.getFont()
        if ok:
            # display the label's text in the selected font
            self.label.setFont(font)
        # display the font name in the edit box for copying
        self.edit.append(QFontInfo(font).family())


app = QApplication(sys.argv)
fd = FontDialog()
fd.show()
app.exec_()

Save the code as pqt_FontLister.pyw

Ene Uran 638 Posting Virtuoso

An example how to use the QPainter to create a wallpaper background:

# a simple window using PyQT 
# using a canvas with a texture/wallpaper background

import sys
# pray for minimal namespace conflicts
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class MyForm(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(100, 150, 350, 300)
        self.setWindowTitle("Creating a Canvas Wallpaper")
        
    def paintEvent(self, event):
        """create a painting canvas"""
        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing)
        # use the brush for a texture/wallpaper background
        # supply a background image file you have (add needed path)
        painter.setBrush(QBrush(QPixmap("BG_GoldSwirl.gif")))
        painter.drawRect(event.rect())
        
        # optionally write something in the wallpaper
        # (check the fonts available on your computer)
        painter.setFont(QFont('Freestyle Script', 48))
        painter.drawText(50, 160, "Hello World!")
        
        painter.end()


app =  QApplication(sys.argv)
form = MyForm()
form.show()
app.exec_()
Ene Uran 638 Posting Virtuoso

I got PyQT4 istalled and working on my Vista computer. Here is an example of my first program:

# display a bunch of random circles using PyQT4

import random
import sys
# pray for minimal namespace conflicts
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class DrawPoints(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(200, 200, 400, 400)
        self.setWindowTitle('Draw random Circles')

    def paintEvent(self, event):
        painter = QPainter()
        painter.begin(self)
        # pen sets the edge color of the circles
        painter.setPen(Qt.black)
        w = self.size().width()
        h = self.size().height()
        # draw 150 circles of random sizes, locations and colors
        for i in range(150):
            # color uses red, green, blue values (0 to 255)
            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)
            # brush sets the fill color of the circles
            painter.setBrush(QBrush(QColor(r, g, b)))
            # get center coordinates x,y of the circle
            x = random.randint(1, w-1)
            y = random.randint(1, h-1)
            # get the radius of the circle
            radius = random.randint(5, 80)
            # to draw circles match the radius
            painter.drawEllipse(QPoint(x, y), radius, radius)

        painter.end()


app = QApplication(sys.argv)
dp = DrawPoints()
dp.show()
app.exec_()
Ene Uran 638 Posting Virtuoso

Expanding on jrcagle post:

import shutil

source_file = r"C:\Python25\Atest\Bull\shutil_test.txt"
destination = r"C:\Python25\Atest\Bull\Test"

# this copies the source file to the destination directory
# the destination directory has to exist
# if the filename already exists there, it will be overwritten
# access time and last modification time will be updated
# the same filename is used
shutil.copy(source_file, destination)

destination2 = r"C:\Python25\Atest\Bull\Test\shutil_test2.txt"
# similar to above,
# but the new specified filename is used
shutil.copy(source_file, destination2)

destination3 = r"C:\Python25\Atest\Bull\Test\shutil_test3.txt"
# similar to above,
# but the new specified filename retains the original file dates
shutil.copy2(source_file, destination3)
iamthwee commented: love the paths! +18
Ene Uran 638 Posting Virtuoso

My advice, don't use the Python Shell for programming, use an editor. The Python Shell interative interpreter is only for very short tests. It is basically there to confuse beginners and discourage them from using Python. :)

Ene Uran 638 Posting Virtuoso

There would be no changes using a list of vowels, the 'in' operator works the same way:

first = raw_input("Enter a sentence :\n")
second = ""
#vowels = 'aeiou'
vowels = ['a','e','i','o','u']
for i in first:
    if i in vowels:
        second = second+i.upper()
    else :
        second = second+i

print second

using vowels = 'aeiou' is much simpler.

Ene Uran 638 Posting Virtuoso

Oh yes, Python has an array type, but you must import module array:

# module array has Python's array type

import array

# Python25 use 'c' as the character typecode
# Python30 uses unicode character typecode 'u'
char_array = array.array('c', 'hello world')

print(char_array[0])    # h
print(char_array)       # array('c', 'hello world')

# 'i' uses a signed integer of 2 bytes
int_array = array.array('i', [2, 4, -11])

print(int_array[2])     # -11
print(int_array)        # array('i', [2, 4, -11])

# 'f' uses 4 bytes and 'd' uses 8 bytes per element 
float_array = array.array('d', [1.0, 2.0, 3.14])

print(float_array[2])  # 3.14

for n in float_array:
    print(n)


# get more information on module array
help('array')

Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time. Arrays use up less space in memory, for a limited number of applications this is important.

scru commented: You knowledge of Python is astounding +5
Ene Uran 638 Posting Virtuoso

"A person should not be too stupid. Stupid people are screwed first. "

Ezzaral commented: Excellent! :) +17
Ene Uran 638 Posting Virtuoso

Two loops will do, or you can use a list comprehension:

rank = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
suit = ("c", "h", "s", "d")

card = []
for r in rank:
    for s in suit:
        card.append(r+s)

card = tuple(card)
print(card)

"""
my result made pretty -->
('Ac', 'Ah', 'As', 'Ad', '2c', '2h', '2s', '2d', '3c', '3h', '3s', 
'3d', '4c', '4h', '4s', '4d', '5c', '5h', '5s', '5d', '6c', '6h', 
'6s', '6d', '7c', '7h', '7s', '7d', '8c', '8h', '8s', '8d', '9c', 
'9h', '9s', '9d', '10c', '10h', '10s', '10d', 'Jc', 'Jh', 'Js', 
'Jd', 'Qc', 'Qh', 'Qs', 'Qd', 'Kc', 'Kh', 'Ks', 'Kd')
"""
Ene Uran 638 Posting Virtuoso

Man "I’d like to call you. What’s your number?"
Woman "It’s in the phone book."
Man "But I don’t know your name."
Woman "That’s in the phone book too."

William Hemsworth commented: hah xD +6
Ene Uran 638 Posting Virtuoso

Before Python 3.0 the wrapper Tkinter.py was called when you used 'import Tkinter'. Now Tkinter has followed wx, and turned into a more modern package approach with a directory named tkinter that uses _init__.py as the wrapper, which means you have to use 'import tkinter'. Here is an example:

# draw a circle with given center (x,y) and radius
# notice that Python25 uses 'Tkinter' and Python30 'tkinter'

# comment/uncomment for the correct Python version
# for Python25 use
#import Tkinter as tk
# for Python30 use
import tkinter as tk

def get_center(x1, y1, x2, y2):
    '''
    for a rectangle with ulc=(x1,y1) and lrc=(x2,y2)
    calculate the center (x,y)
    '''
    x = x1 + (x2 - x1)//2
    y = y1 + (y2 - y1)//2
    return x, y
    
def get_square(x, y, radius):
    '''
    given the center=(x,y) and radius
    calculate the square for the circle to fit into
    return x1, y1, x2, y2 of square's ulc=(x1,y1) and lrc=(x2,y2)
    '''
    x1 = x - radius
    y1 = y - radius
    x2 = x + radius
    y2 = y + radius
    return x1, y1, x2, y2

# create the basic window, let's call it 'root' 
root = tk.Tk()

# create a canvas to draw on
cv = tk.Canvas(root, width=300, height=300, bg='white')
cv.grid()

# draw a circle with given center (x,y) and radius
x, y = 150, 120
radius = 65
# to draw a circle you need to get the ul and lr corner coordinates
# of a square that the circle will fit …
Ene Uran 638 Posting Virtuoso

Is there a gui library that has already been ported to python 3? I'm interested in using some of the new python 3 features in the back end for my project.

For the time being you will have to use good old Tkinter that ships with Python3.0.

Ene Uran 638 Posting Virtuoso

A classic, Newton's method to estimate the square root of a number:

# estimate the square root of value v
# using Newton's Method

from math import sqrt

# value to estimate sqr for
v = 222

# initial guess
g = v/2.0

# loop n times
n = 7
for k in range(n):
    # Newton's method
    y = (g + v/g)/2.0
    g = y
    print( "%d) %0.8f  %0.8f  %0.8f" % (k+1, sqrt(v), g, sqrt(v)-g) ) 

"""
my output -->
1) 14.89966443  56.50000000  -41.60033557
2) 14.89966443  30.21460177  -15.31493734
3) 14.89966443  18.78102132  -3.88135690
4) 14.89966443  15.30073237  -0.40106795
5) 14.89966443  14.90492089  -0.00525646
6) 14.89966443  14.89966535  -0.00000093
7) 14.89966443  14.89966443  -0.00000000
"""
Ene Uran 638 Posting Virtuoso

You simply append the directory to PYTHONPATH before you import your custom module:

import sys
# appends to PYTHONPATH  the location of the example codes
sys.path.append(r'C:\Python25\Examples')
Ene Uran 638 Posting Virtuoso

Accidents happen (explains why I didn't get a Xmas present):

Ene Uran 638 Posting Virtuoso

One way to play music files of the popular MP3 music format, is to use the module pygame. Here is an example that works with a number of music file formats (you got to experiment):

# play a MP3 music file using module pygame
# (does not create a GUI frame in this case)
# pygame is free from: http://www.pygame.org/
# ene

import pygame

def play_music(music_file):
    """
    stream music with mixer.music module in blocking manner
    this will stream the sound from disk while playing
    """
    clock = pygame.time.Clock()
    try:
        pygame.mixer.music.load(music_file)
        print "Music file %s loaded!" % music_file
    except pygame.error:
        print "File %s not found! (%s)" % (music_file, pygame.get_error())
        return
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        # check if playback has finished
        clock.tick(30)


# pick MP3 music file you have ...
# (if not in working folder, use full path)
music_file = "Drumtrack.mp3"

# set up the mixer
freq = 44100     # audio CD quality
bitsize = -16    # unsigned 16 bit
channels = 2     # 1 is mono, 2 is stereo
buffer = 2048    # number of samples (experiment to get right sound)
pygame.mixer.init(freq, bitsize, channels, buffer)

# optional volume 0 to 1.0
pygame.mixer.music.set_volume(0.8)

try:
    play_music(music_file)
except KeyboardInterrupt:
    # if user hits Ctrl/C then exit
    # (works only in console mode)
    pygame.mixer.music.fadeout(1000)
    pygame.mixer.music.stop()
    raise SystemExit
Ene Uran 638 Posting Virtuoso

Resolving to surprise her husband, an executive's wife stopped by his office. When she opened the door, she found him with his secretary sitting in his lap.

Without hesitating, he dictated, "...and in conclusion, gentlemen, budget cuts or no budget cuts, I cannot continue to operate this office with just one chair."

Ene Uran 638 Posting Virtuoso

Here is a general example you can adopt, let us know if it works for your case:

# using module subprocess to pass arguments to and from an
# external program

import subprocess

# put in the corresponding strings for
# "mycmd" --> external program name
# "myarg" --> arg for external program
# several args can be in the list ["mycmd", "myarg1", "myarg2"]
# might need to change bufsize
p = subprocess.Popen(["mycmd", "myarg"], bufsize=2048, shell=True,
    stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)

# allow external program to work
p.wait()

# read the result to a string
result_str = p.stdout.read()
bugmenot commented: Good post, well commented, although not exactly what I was looking for ;) +2
Ene Uran 638 Posting Virtuoso

Just an application for lambda, and the use of a dictionary to mimic C's switch/case statement:

# lambda creates an anonymous function
# returnedExpr must be an expression, not a statement
# this code could form a simple calculator

import math

def do_op(op, a=1, b=1):
    """use of a dictionary similar to C's switch/case"""
    return {
    '+': lambda: a + b,
    '-': lambda: a - b,
    '*': lambda: a * b,
    '/': lambda: a / b,
    '//': lambda: a // b,   # floor
    '**': lambda: a ** b,   # power
    'sin': lambda: math.sin(a),
    'cos': lambda: math.cos(a),
    'asin': lambda: math.asin(a),
    'acos': lambda: math.acos(a)
    }[op]()

# 355/113.0 pi approx.
print do_op('/', 355, 113.0)  # 3.14159292035

# sqroot(25)
print do_op('**', 25, 0.5)    # 5.0

# asin(sin(0.5))
print do_op('asin', do_op('sin', 0.5))  # 0.5
Ene Uran 638 Posting Virtuoso

Why do all the extra work, if Python can do it for you?

result3=[
83,97,109,117,101,108,32,83,109,105,116,104,13,10,13,10,84,
104,97,110,107,32,121,111,117,32,102,111,114,32,108,111,111,
107,105,110,103,32,116,104,101,32,111,116,104,101,114,32,119,
97,121,32,111,110,32,116,104,101,32,105,110,99,114,101,97,115,
101,100,32,108,101,118,101,108,115,32,111,102,32,116,111,120,
105,99,32,99,104,101,109,105,99,97,108,115,32,105,110,32,116,104,
101,32,114,105,118,101,114,32,114,117,110,110,105,110,103,32,97,
108,111,110,103,115,105,100,101,32,109,121,32,104,111,109,101]

# show the text hidden in the list of ascii values
print "".join([chr(x) for x in result3])

I know, I know, not as much fun as the long way!

jlm699 commented: Sexy, simple method +1
Ene Uran 638 Posting Virtuoso

For the many of you who still want to know the solution, make variable 'a' a global:

words = ["aero", "aesthet", "andr", "arch", "arch", "ast", "baro",\
"biblio", "bio", "cardi", "chron", "cosm", "crat", "cycl", "dem", "dont",\
"dogma", "dox", "esth"]

answers = ["air", "sense", "man", "man", "chief", "ancient", "star", "weight",\
"book", "life", "heart", "time", "universe", "rule", "circle", "people",\
"tooth", "opinion", "belief", "feeling"]

a = 0

def test():
    global a
    a = a + 1
    print "What does", words[a], "mean?"
    ans = raw_input("> ")
    if ans == answers[a]:
        print "Correct!"
        test()
    else:
        print "That is incorrect. Try again."
        a = a - 1
        test()

test()
Ene Uran 638 Posting Virtuoso
Ancient Dragon commented: LOL :) +36
Ene Uran 638 Posting Virtuoso

Cause and effect about to happen: