Ene Uran 638 Posting Virtuoso

Better not sorry then not safe

Ene Uran 638 Posting Virtuoso

Big Bangs happen all the time. We are just too far way to observe them. I wonder what the opposite of a Big Bang is?

Ene Uran 638 Posting Virtuoso

The first problem could be kind of easy:

n = 11
for odd_number in range(1, n+1, 2):
    print( odd_number )

"""
1
3
5
7
9
11
"""
Ene Uran 638 Posting Virtuoso

Here is the code to sort a dictionary of dictionaries:

# sorted display of a dictionary of dictionaries

def dict_of_dict_sort(dd, key):
    """
    print out selected items from a dictionary of dictionaries dd
    sorted by a given key
    """
    for k in sorted(dd, key=lambda x: dd[x][key]):
        print( k, dd[k]['age'], dd[k]['country'] )


user_dict = {
'Bill': {'age': 39, 'country': 'USA'},
'Dave' : {'age': 26, 'country': 'Canada'},
'Olaf' : {'age': 33, 'country': 'Sweden'}
}

# display sorted by age
dict_of_dict_sort(user_dict, 'age')

"""my result -->
Dave 26 Canada
Olaf 33 Sweden
Bill 39 USA
"""
Ene Uran 638 Posting Virtuoso

Chicken nuggets with beer.

Ene Uran 638 Posting Virtuoso

Something only Microsoft could dream up. I understand that in the European version of Windows the space is avoided. The kludge itself is from a programmer within Microsoft.

Ene Uran 638 Posting Virtuoso

A very simple way:

# create a string where the index gives the grade
grade_str = 'F'*60 + 'D'*10 + 'C'*10 + 'B'*10 + 'A'*11
# ask for grade number input
grade = int(raw_input("Enter the student's grade (0 to 100): "))
# index the result
print "Grade letter =", grade_str[grade]

However, don't hand this in as assignment because your instructor will know it's not yours.

Ene Uran 638 Posting Virtuoso

This is often referred to as the little-known "Microsoft kludge"

Ene Uran 638 Posting Virtuoso

You can concatenate tuples, the trick is to wrote the one element tuple correctly:

users =  ('user1','user2','user3')

# from input ...
new_user = 'user4'

# concatenate tuples, notice the way a one element tuple is written
users = users + (new_user, )

print users  # ('user1', 'user2', 'user3', 'user4')
Ene Uran 638 Posting Virtuoso

This problem has been around for a long time and not just with Python:

# the "Microsoft kludge", quoting a string within a string fixes the 
# space-in-folder-name problem, tells the OS to use the whole string
# including spaces as a single command
# (make sure filename does not contain any spaces!)
os.system('"C:/Program Files/IrfanView/i_view32.exe" ' + filename)
JasonHippy commented: Nicely done....How did I miss that?! +4
Gribouillis commented: nice trick +5
pysup commented: Perfect +1
Ene Uran 638 Posting Virtuoso

That is because I made a test file from your posting and put it into the working directory, the same directory the code file is in.

Since you have the real thing you can replace
fname = "violate.dat"
with
fname = r"C:\HourlyATC\viols.lis"

Ene Uran 638 Posting Virtuoso

Those modules are often written by instructors in colleges to keep their students from simply copying existing code, spreading confusion for the rest of us! There is a similar module out called graphics.py, that is a wrapper for Tkinter. Again nothing but a pain in the butt.

Ene Uran 638 Posting Virtuoso

It easier to make fun of something you don't understand, than trying to understand it.

For instance a frequent phrase used by US politicians:
"The Canadian and British Health Care System is a complete failure."

If you say it often enough it becomes the truth!

Ene Uran 638 Posting Virtuoso

"Dutch treat" in Holland is
"op zijn Amerikaans"
("in an American way")

Ene Uran 638 Posting Virtuoso

Don't get even!
Get odd!

Ene Uran 638 Posting Virtuoso

Try
ascii += cs_string

Ene Uran 638 Posting Virtuoso

Did you use the .msi binary installer to install Python?

How are you trying to open python.exe?

Normally you find the IDE called Idle.pyw somewhere in the Python folders (like C:\Python31\Lib\idlelib) and double click on it to get going. Doing any programming out of the Python shell directly is f****cking ugly!

Ene Uran 638 Posting Virtuoso

cTurtle.py has nothing to do with C. It is simply someones hack of the turtle.py with a few extra methods added. See the beginning of file cTurtle.py for details. You can also run it, as it has a built-in demo.

It comes in two versions, one for Python2 and another for Python3.

In similar fashion, there is also the module frog, here you can use a picture of a frog or anything you like, and it has even sound effects. Great for entertaining kids of any age! See:
http://www.daniweb.com/forums/post953952.html#post953952

Ene Uran 638 Posting Virtuoso

Try something like this:

label = list(range(len(files)))
    for k, fname in enumerate(files):
        image = Image.open(filedir+"/"+fname)
        ##((width, height))
        image.thumbnail((160, 240))
        photo = ImageTk.PhotoImage(image)
        label[k] = Label(image=photo)
        label[k].image = image # keep a reference!
        #label[k].pack()  # pack when you want to display it


        #print files
    return ...
Param302 commented: Thank you so much, I want to display multiple images, but today I have seen you have figured it out 11 years ago, really thank you so much! +0
Ene Uran 638 Posting Virtuoso

You could take each labelobject an append it to a list.

Ene Uran 638 Posting Virtuoso

Try something like:
lineA = fin.readline()[lpa].strip()

Ene Uran 638 Posting Virtuoso

See if something like this will do, but be careful that all the slicing doesn't steal some data:

def extract_number(data_str):
    """
    extract the numeric value from a string
    (the string should contain only one numeric value)
    return the numeric part of the string or None
    """
    s = ""
    for c in data_str:
        if c in '1234567890.-':
            s += c
    if s:
        return s
    else:
        return None


def extract_between(text, sub1, sub2):
    """
    extract a substring from text between first
    occurances of substrings sub1 and sub2
    """
    return text.split(sub1, 1)[-1].split(sub2, 1)[0]


# test file
fname = "violate.dat"

mylist = []
flag = False
for line in open(fname):

    if flag == True:
        mylist.append(line)
        flag = False
    if "FCITC" in line:
        flag = True

newlist = []
for item in mylist:
    temp1 = item[:16]
    #print(temp1)  # test
    temp1 = extract_number(temp1)

    temp2 = item[35:83]
    #print(temp2)  # test
    temp2 = temp2[6:28].replace(']', ' ')
    temp2 = temp2.strip()
    #print(temp2)  # test

    temp3 = item[96:144]
    #print(temp3)  # test
    temp3 = extract_between(temp3, '[B]', '[/B]').rstrip()
    #print(temp3)  # test

    newlist.append((temp1, temp2, temp3))


print('-'*40)

for tup in newlist:
    print(tup)

"""my show -->
('690.4', '5567 IND RIV      115', 'Base Case')
('-756.5', '6106 I-STATE      230', '7890 OSCEOLA      230   9190 AGNES-RX')
('589.3', '5704 TAFT         230', ' 2883 INTERCSN     230   5352 CAN ISL')
('1905.9', '6101 MCINTOSH     230', ' 9100 RECKER       230   9150 LKAGNES')
('1119.9', '2167 WINDERME     230', '5353-5800')
('-1121.7', '467 POINSETT     230', '351 ORANGE R     230    354 ORANGE R')
('1776.3', '461 CAPE K       230', '461 CAPE K       230   5703 IND RIV')
('899.9', '5704 TAFT         230', …
majestic0110 commented: nice answer! +5
Ene Uran 638 Posting Virtuoso

Also in Python3 'pg_r' would be a byte string and module re will complain without converting 'pg_r' to a string first.

Ene Uran 638 Posting Virtuoso

self.panel everywhere except the most important line 12

panel=wx.Panel(self,-1)
needs to be
self.panel=wx.Panel(self,-1)

Ene Uran 638 Posting Virtuoso

Are you sure you posted in the right place? This is not the Mindreader Forum!

Ene Uran 638 Posting Virtuoso

Hint:
Looks to me like you are creating the same label over and over again.

Ene Uran 638 Posting Virtuoso

I don't think getting the values will be a problem, because I've heard of GetValues() and Google it for help.

The problem is: the self.panel doesn't at all work...

One more question:

viewm=wx.Menu()
viewm.Append(202,"About")        self.Bind(wx.EVT_MENU,self.About,id=302)

def About(self,event,id=302):
    about=wx.AboutDialogInfo()

-but it doesn't work. How do I specify the ID when defining the function?

Thanks

You don't need the id as a method parameter, but at least try to match the id in the lines above, 202 is not the same as 302.

self.panel will work if you use it throughout the class! Search for 'panel' with your editor.

Ene Uran 638 Posting Virtuoso

Pythons normally don't come with a handle, this must be a new breed.

Ene Uran 638 Posting Virtuoso

In this case you have to set a flag like this:

import sys

# there is a commandline
if len(sys.argv) > 1:
    mylist = []
    # sys.argv[0] is the program filename, slice it off
    flag = False
    for element in sys.argv[1:]:
        if element == '-f':
            flag = False
        if flag == True:
            mylist.append(element)
        if element == '-n':
            flag = True


else:
    print "usage %s element1 element2 [element3 ...]" % sys.argv[0]
    sys.exit(1)

# if the arguments were -n 1 2 3 4 -f abc.txt
# mylist should be  ['1', '2', '3', '4']
print(mylist)
Ene Uran 638 Posting Virtuoso

Give this a try:

import sys

# there is a commandline
if len(sys.argv) > 1:
    mylist = []
    # sys.argv[0] is the program filename, slice it off
    for element in sys.argv[1:]:
        mylist.append(element)
else:
    print "usage %s element1 element2 [element3 ...]" % sys.argv[0]
    sys.exit(1)

# if the arguments were 1 2 3 4 5
# mylist should be ['1', '2', '3', '4', '5']
print(mylist)
Ene Uran 638 Posting Virtuoso

There is another Python version called IronPython that uses Python syntax. It runs independent from the normal CPython version and allows access to the large GUI libraries of .NET and Mono. Here is an example:

# create a window with a button and click event using ironpython
# ironpython gives access to the Windows .NET or Linux Mono libraries
# download ironpython from:
# http://www.codeplex.com/ironpython
# tutorial at:
# http://www.zetcode.com/tutorials/ironpythontutorial/
#
# to distinguish the filename from normal Python use prefix ip_
# if you save this file as "ip_buttonWin1.py"
# compile it with something like:
# C:\IronPython 2.6\ipy.exe "ip_buttonWin1.py"
#
# clr -> Common Language Runtime

import clr

clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")

from System.Windows.Forms import Application, Form, Button, ToolTip
from System.Drawing import Size, Point

class IForm(Form):

    def __init__(self):
        # set form title, position, size
        self.Text = 'Button'
        self.CenterToScreen()
        self.Size = Size(300, 150)

        btn = Button()
        btn.Parent = self
        btn.Text = "Quit"
        btn.Location = Point(50, 50)
        # click on the button to call OnClick()
        btn.Click += self.OnClick
        # mouse over button calls OnEnter()
        btn.MouseEnter += self.OnEnter

        # optional tooltip
        tooltip = ToolTip()
        # tooltip for the button
        tooltip.SetToolTip(btn, "Don't be a Quitter")

    def OnClick(self, sender, args):
        self.Close()

    def OnEnter(self, sender, args):
        #print sender, type(sender)
        self.Text = "mouse entered button area"


Application.Run(IForm())

Since i have a Windows XP machine I installed
IronPython-2.6.msi
and for the .NET framework (free from MicroSoft)
NetFx20SP1_x86.exe

See the details in file Readme.html that comes with the installation.

Lardmeister commented: useful +10
Ene Uran 638 Posting Virtuoso

You can trap error details this way:

import datetime as dt

def ObtainDate():
    isValid=False
    while not isValid:
        userIn = raw_input("Type Date dd/mm/yy: ")
        try: # strptime throws an exception if the input doesn't match the pattern
            d1 = dt.datetime.strptime(userIn, "%d/%m/%y")
            isValid=True
#Perhaps set another try here.
            print d1, type(d1)  # 2003-07-15 00:00:00 <type 'datetime.datetime'>
            "convert datetime object to a 10 character string"
            d2 = str(d1)[:10]
            print d2, type(d2)  # 2003-07-15 <type 'str'>
        except ValueError, what_error:
            print what_error
            print "Try again! dd/mm/yy\n"
    Fname = "data.dat"
    newFname = d2 + Fname
    return newFname

print ObtainDate()  # 2003-07-15data.dat
Ene Uran 638 Posting Virtuoso

You can also check into the use of the PyQT GUI toolkit. It is available free and even works with Python 3.1. There is an example here that should work with your application:
http://www.daniweb.com/forums/post979747.html#post979747

It has a few extras, like clicking on the table column header to sort by that column.

Ene Uran 638 Posting Virtuoso

I don't think it's possible because py2exe does not include any source, only the byte code compiled files in case you go for the zip file option.

Ene Uran 638 Posting Virtuoso

It's not quite as simple!

However you use Portable Python. It installs a portable version of Python right on an inexpensive USB flash drive (plan on 150MB for each version). You can use the flash drive now on Windows computers that do not have Python installed. It comes in Python25, Python26 and Python30 flavors. See:
http://www.portablepython.com/releases/

Portable Python 1.1 based on Python 2.5.4 -->
Python25
Django-1.0.2-final (for web development)
IPython-0.9.1
Matplotlib-0.98.5.2 ( for graphic plotting)
Numpy-1.2.1 (for high speed arrays)
PIL-1.1.6 (for image manipulation)
Py2exe-0.6.9 (packed python code to .exe files)
PyGame-1.8.1 (the python game toolkit)
PyReadline-1.5
PyScripter v1.9.9.6 (a very nice IDE to write programs with)
PyWin32-212 (window extension library)
Rpyc-2.60 (remote python)
Scipy-0.7.0b1 (a high spped scientific toolkit)
SPE-0.8.4.c (another very nice IDE)
VPython-3.2.11 (for 3D scientific modeling)
wxPython-unicode-2.8.9.1 (a popular GUI toolkit)

Portable Python 1.1 based on Python 2.6.1 -->
Python26
Django-1.0.2-final
IPython-0.9.1
PIL-1.1.6
Py2exe-0.6.9
PyGame-1.8.1
PyReadline-1.5
PyScripter v1.9.9.6
PyWin32-212
Rpyc-2.60
SPE-0.8.4.c
wxPython-unicode-2.8.9.1

Ene Uran 638 Posting Virtuoso

Wow, I knew about ascii_letters and stuff but I didn't think they could be used with choice(). The var information was helpful too! Thanks a million :).

FYI,
upper = list(string.ascii_uppercase)

Ene Uran 638 Posting Virtuoso

Give us your code and we will help you understand.
For instance:

def myloop():
    for x in range(5):
        y = 2*x
    return y

# this will give 8, since the last x in the loop was 4
print(myloop())
Ene Uran 638 Posting Virtuoso

Take a looky here:

import string

print(string.digits)
print(string.ascii_lowercase)
print(string.ascii_uppercase)

# optional ...
#help(string)

Also, all your many deletes are not needed, since variables are handled very well by Python's excellent built-in memory manager. On top of that, the variables in functions are local and are deleted after the function is done anyway.

What you consider a variable is simply an identifier of an object in Python and gets used for other objects if need be. Identifiers are part of an internal dictionary with identifier:object pairs. Since the identifier is a dictionary key, only one unique name can exist.

Ene Uran 638 Posting Virtuoso

A similar table, this time we use PyQT's QTableView and QAbstractTableModel which allows the items in the table to be sorted by simply clicking on the header titles:

# use PyQT's QTableView and QAbstractTableModel
# to present tabular data
# allow sorting by clicking on the header title
# tested with Python 3.1.1 and PyQT 4.5.2
# ene

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

class MyWindow(QWidget):
    def __init__(self, data_list, header, *args):
        QWidget.__init__(self, *args)
        # setGeometry(x_pos, y_pos, width, height)
        self.setGeometry(300, 200, 420, 250)
        self.setWindowTitle("Exploring PyQT's QTableView")

        table_model = MyTableModel(self, data_list, header)
        table_view = QTableView()
        table_view.setModel(table_model)
        # enable sorting
        table_view.setSortingEnabled(True)

        layout = QVBoxLayout(self)
        layout.addWidget(table_view)
        self.setLayout(layout)


class MyTableModel(QAbstractTableModel):
    def __init__(self, parent, mylist, header, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.mylist = mylist
        self.header = header

    def rowCount(self, parent):
        return len(self.mylist)

    def columnCount(self, parent):
        return len(self.mylist[0])

    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()
        return QVariant(self.mylist[index.row()][index.column()])

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return QVariant(self.header[col])
        return QVariant()

    def sort(self, col, order):
        """sort table by given column number col"""
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.mylist = sorted(self.mylist,
            key=operator.itemgetter(col))
        if order == Qt.DescendingOrder:
            self.mylist.reverse()
        self.emit(SIGNAL("layoutChanged()"))


header = ['First Name', 'Last Name', 'Age', 'Weight']
# a list of (name, age, weight) tuples
data_list = [
('Heidi', 'Kalumpa', '36', '127'),
('Frank', 'Maruco', '27', '234'),
('Larry', 'Pestraus', '19', '315'),
('Serge', 'Romanowski', '59', '147'),
('Carolus', 'Arm', '94', '102'),
('Michel', 'Sargnagel', '21', '175')
]

app = QApplication([])
win = MyWindow(data_list, header)
win.show()
app.exec_()

Not sure what is going on …

Ene Uran 638 Posting Virtuoso

Thanks vegaseat for the newer PyQT style info. Here is a relatively simple way to display tabular data using a function to create an html coded table:

# PyQT's QLabel widget can display html formatted text
# used here to display data in a nice table
# tested with Python 3.1.1 and PyQT 4.5.2
# ene

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

class MyForm(QWidget):
    def __init__(self, html_table):
        QWidget.__init__(self)
        # setGeometry(x_pos, y_pos, width, height)
        # widget will expand to fit lable size
        self.setGeometry(100, 150, 1, 1)
        self.setWindowTitle("html formatted data table")

        label = QLabel(html_table)

        # use the grid layout manager
        grid = QGridLayout()
        # addWidget(widget, row, column, rowSpan=1, columnSpan=1)
        grid.addWidget(label, 0, 0)
        self.setLayout(grid)


def make_html_table(data_list):
    """
    use a list of data tuples and create the html code
    of a html formatted table containing the data items
    """
    rows = len(data_list)
    columns = len(data_list[0])
    # color is in hex format "#RRGGBB"
    html = '<table border="5" bordercolor="#0000cc" cellspacing="5" '
    html += 'cellpadding="5" width="5" bgcolor="#ffff66">\n'
    for row in range(rows):
        html += '<tr>\n'
        for col in range(columns):
            item = data_list[row][col]
            html += "    %s%s%s\n" % ('<td>', item, '</td>')
        html += '</tr>\n'
    html += '</table>\n'
    return html


# a list of (name, age, weight) tuples
# the first tuple is the header
data_list = [
('Name', 'Age', 'Weight'),
('Heidi Kalumpa', '36', '127'),
('Frank Maruco', '27', '234'),
('Larry Pestraus', '19', '315'),
('Serge Romanowski', '59', '147'),
('Carolus Arm', '94', '102'),
('Michel Sargnagel', '21', '175')
]

html_table = make_html_table(data_list)

#print(html_table)  # for test only

app =  QApplication([]) …
Ene Uran 638 Posting Virtuoso

Sometimes it's nice to have static variable in a function. A static variable remembers its last value. Here is one way to do it with Python:

# a class can give all global variables a save namespace
# also behaves like a static variable in a function

class Global(object):
    """
    declare all global variables here
    """
    x = 0
    z = False


# now all global variables can have the class instance
# as a namespace, use something simple like ww
ww = Global()

# testing ...
print( ww.x )  # 0
print( ww.z )  # False

def incr_wwx() :
    """
    ww.x does not need to be declared global
    and functions as a static variable here
    """
    ww.x += 1
    return ww.x

print( incr_wwx() )  # 1
print( incr_wwx() )  # 2
print( incr_wwx() )  # 3
print( ww.x )  # 3

print( '-'*10)

def toggle():
    """
    toggle between True and False on each call
    """
    ww.z = not ww.z
    return ww.z

print( toggle() )  # True
print( toggle() )  # False
print( toggle() )  # True
print( ww.z )  # True

For instance, if you put
ww.x += 1
into a function, ww.x keeps track of how many times the functions has been called.

Ene Uran 638 Posting Virtuoso

Have you ever wondered what 'self' is doing when you use Python classes? Here is the short and sweet of it:

# role of self in Python classes
# self can be named different, but 'self' is convention

class Snake(object):
    def __init__(self, name):
        # self keeps track of each instance
        # and also makes self.name global to class methods
        self.name = name
        # for test only
        print(self)

    def isnice(self):
        # a class method has self as the first argument
        return self.name + " is very nice"

# create 2 instances of class Snake
bob = Snake('Bob Python')
mary = Snake('Mary Rattle')

print('-'*40)

# now you can get the name that has been assigned to self.name
print(bob.name)
print(mary.name)

# access the class method
print(mary.isnice())

"""my result (Python 3.1.1) -->
# self for each instance has a different location in memory
<__main__.Snake object at 0x01E0B2B0>
<__main__.Snake object at 0x01E0B090>
----------------------------------------
Bob Python
Mary Rattle
Mary Rattle is very nice
"""
Ene Uran 638 Posting Virtuoso

Look over this code sample, it should be very explanatory:

# role of self in Python classes
# self can be named different, but 'self' is convention

class Snake:
    def __init__(self, name):
        # self keeps track of each instance
        # and also makes self.name global to class methods
        self.name = name
        # test
        print(self)

    def isnice(self):
        # a class method has self as the first argument
        return self.name + " is very nice"

# create 2 instances of class Snake
bob = Snake('Bob Python')
mary = Snake('Mary Rattle')

print('-'*40)

# now you can get the name that has been assigned to self.name
print(bob.name)
print(mary.name)

# access the class method
print(mary.isnice())

"""my result -->
# self for each instance has a different location in memory
<__main__.Snake object at 0x01E0B2B0>
<__main__.Snake object at 0x01E0B090>
----------------------------------------
Bob Python
Mary Rattle
Mary Rattle is very nice
"""
vegaseat commented: very nice +14
Ene Uran 638 Posting Virtuoso

Most commonly a dictionary of key:value pairs is searched by the unique key. Sometimes it becomes necessary to search for the key, or keys given a value. Special consideration has to be given to this case, because the value does not have to be unique and may return several keys (list of keys).

A class inheriting the dictionary base class is used to do both searches. I have also made up some simple, but nicely named functions to search the dictionary, in case you don't want to use a class.

Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso
Ene Uran 638 Posting Virtuoso

Very interesting! Thanks Jeff!

Ene Uran 638 Posting Virtuoso

Why are you using the C snippets for a C++ snippet? There is a difference between the two old languages.

Ene Uran 638 Posting Virtuoso

This simple Python code uses the Tkinter GUI toolkit and the Python Image Library (PIL) to create a program that allows you to grab an image of the display screen (or portion of it) and save it to an image file. Unfortunately, the ImageGrab.grab() method only works on a Windows computer. Sorry about that to all you good folks using PC Linux or Apple Unix. I guess we have to ask the PIL folks to get on the ball!

Ene Uran 638 Posting Virtuoso

How to you handle tabs?