Ene Uran 638 Posting Virtuoso

Duck Typing comes to mind.

Ene Uran 638 Posting Virtuoso

Very nice idea.

Ene Uran 638 Posting Virtuoso

Please read the note on homework help. We only help those who show at least some coding effort.

Ene Uran 638 Posting Virtuoso

The module psyco compiles to 386 machine code rather than byte code. It speeds things up a little for the Python interpreter.

To my knowledge two complete OS have been written using mostly Python, both of them are less than ideal and are used for research purposes only. Python is a high level language and has not been designed for such a low level task!

Ene Uran 638 Posting Virtuoso

Directed at ktsangop,

Are you writing your program with an editor, save it as a .py file and then run it, or are you simply running it directly from the Python interpretive shell?

If you run it from the shell, we can argue till the cows lay eggs.

Ene Uran 638 Posting Virtuoso

Usually homework like that asks for change with the least amount of coins.

Ene Uran 638 Posting Virtuoso

Really not very complicated, just follow this sequence of actions:

"""
assumes that you are using Python31 installed on the c drive
create a directory c:/Python31/MyModules
then save this file in that directory as __init__.py
basically an code-empty file with an optional explanation
it will make MyModules a package
"""

Now directory MyModules is a package and you can put your custom modules in it, for instance this test module:

"""
now create this simple test module
and save in c:/Python31/MyModules as module1.py
"""
text = "text from module1"

Next write some code to test module1, this file can be saved anywhere and when you run Python (in this case Python 3.1.1) it will find package directory since it is in the Python search path:

"""
assumes that you are using Python31 installed on the c drive
1) create a directory c:/Python31/MyModules
2) write an empty file __init__.py to that directory
   ( this makes MyModules a package)
3) write a test module module1.py to that directory
   ( has one code line --> text = "text from module1" )
4) test module module1.py in c:/Python31/MyModules
   with the code below, this file can be saved anywhere

since package directory MyModules is in the Python search path
it will be found, remember package names are case sensitive
as are module names
"""

import MyModules.module1 as mm_module1

print(mm_module1.text)
Ene Uran 638 Posting Virtuoso

Shorten the list and add a temporary print for testing. See what that will do for you:

# shorten list for test
a = range(1, 10)
b = []
d = 0
for n in a:
    while n != 1:
        if n % 2 == 0:
            b.append(n)
            n = n/2
        elif n % 2 != 0:
            b.append(n)
            n = n*3 + 1
        else: b.append(n)
    print b, d, len(b)  # test
    if len(b) > d:
        d = len(b)
        b = []
Ene Uran 638 Posting Virtuoso

Almost two more years to wait until this spectacular event will happen. Makes the rest of the wait boring.:)

Ene Uran 638 Posting Virtuoso

Almost invisible nano robots attacking human tissue, ouch! Lots of money to be made there!

Would make a good movie, but then who wants to see a monster movie where you can't see the monsters.

Ene Uran 638 Posting Virtuoso

I have only python 2.5 installed and i can find PIL in the Pythons installation directory. I use a IDE called PyScripter. When i run the program from the IDE it works fine. But it throws error when i run it from the command line.

What do you mean with run it from the command line? What is your command?

Ene Uran 638 Posting Virtuoso

Calm down, nobody has called you anything!

The thread caters to project ideas that are for the beginner. However beginners are at all sorts of levels in their learning progress. Any project takes some research, otherwise it isn't a project!

I have enjoyed the sticky's project ideas very much. Please put your clever Raffle project back into the thread. Avoid the unsubstantiated extra comments about other projects. If you manage to freeze up Python on a program you wrote, go to the regular forum and ask questions. This way you won't ask other folks to clutter up this nice thread/sticky with answers. That is what the rules imply.

It looks like the word Beginner should have been replaced by Python Enthusiast or something.

Ene Uran 638 Posting Virtuoso

Simply loop your code a million times and time the whole thing. There is also module timeit.

Ene Uran 638 Posting Virtuoso

A nano robot made to seek and destroy human sight and hearing sounds just a little too scary! Something the sickos in defense might just drool over.

Ene Uran 638 Posting Virtuoso

This should tell DOS what kind of decoding you want to use:

# -*- coding: latin-1 -*-

print ord('é'.decode("latin-1"))     # 233
Ene Uran 638 Posting Virtuoso

This is the problem:

So what is your code?

Ene Uran 638 Posting Virtuoso

When you use Tm = [[0]*8]*24 you are creating 24 alias copies of an eight zero list. That means all 24 sublists have the same memory address.

To create the proper list of lists use this approach:

# create a 24 by 8 list of lists initialized with zero
zerolist24x8 = []
for x in range(24):
    # create a fresh list of 8 zeros 24 times
    zerolist8 = []
    for y in range(8):
        zerolist8.append(0)
    zerolist24x8.append(zerolist8)

Now you can use module copy to make your copy of zerolist24x8, for instance:

import copy
Tm = copy.deepcopy(zerolist24x8)
Tr = copy.deepcopy(zerolist24x8)
Ene Uran 638 Posting Virtuoso

The folks at the NSA will pick your super secret password in less than a second. So, pick something simple you can easily type and remember in the hope that it is safe from the boss or your underage sister.

Ene Uran 638 Posting Virtuoso

You are getting into trouble with escaped characters caused by \ since '\r' is read as CR (carriage return).
Try to use:

bright = wx.Image(r'C:\Users\Alexander\Desktop\New Folder\right.jpg', wx.BITMAP_TYPE_ANY)

or:

bright = wx.Image('C:\\Users\\Alexander\\Desktop\\New Folder\\right.jpg', wx.BITMAP_TYPE_ANY)

or:

bright = wx.Image('C:/Users/Alexander/Desktop/New Folder/right.jpg', wx.BITMAP_TYPE_ANY)

for all your Window paths.

Ene Uran 638 Posting Virtuoso

Thanks nezachem!
Looks like my .png image file only has RGB and not RGBA. You could use this modified code:

# convert a .png image file to a .bmp image file using PIL

from PIL import Image

file_in = "test.png"
img = Image.open(file_in)

file_out = "test2.bmp"
print len(img.split())  # test
if len(img.split()) == 4:
    # prevent IOError: cannot write mode RGBA as BMP
    r, g, b, a = img.split()
    img = Image.merge("RGB", (r, g, b))
    img.save(file_out)
else:
    img.save(file_out)

Not sure what is going on, but I get these double posts with DaniWeb.

Ene Uran 638 Posting Virtuoso

Thanks nezachem!
Looks like my .png image file only has RGB and not RGBA. You could use this modified code:

# convert a .png image file to a .bmp image file using PIL

from PIL import Image

file_in = "test.png"
img = Image.open(file_in)

file_out = "test2.bmp"
print len(img.split())  # test
if len(img.split()) == 4:
    # prevent IOError: cannot write mode RGBA as BMP
    r, g, b, a = img.split()
    img = Image.merge("RGB", (r, g, b))
    img.save(file_out)
else:
    img.save(file_out)
Ene Uran 638 Posting Virtuoso

Strange, my test1.png image file is full color and I have no problems.

Ene Uran 638 Posting Virtuoso

It's as simple as this:

# convert a .png image file to a .bmp image file using PIL

from PIL import Image

file_in = "test1.png"
img = Image.open(file_in)

file_out = "test1.bmp"
img.save(file_out)
rasizzle commented: Great help. +1
maxvanden commented: very helpful +0
Ene Uran 638 Posting Virtuoso

Thanks for letting us know. I would have done it the same way too, since Frame has the convenient borderwidth arg.

Ene Uran 638 Posting Virtuoso

Hint, generally you iterate over the string like this:

mystring = "abcdefghijklmnop"

# newstring starts as an empty string (no char in it)
newstring = ""
count = 0
for c in mystring:
    # every third character is added to newstring
    if count % 3 == 0:
        #print( c )  # test
        # build up newstring
        newstring += c
    # increment count by 1
    count += 1

print( newstring )  # adgjmp
Ene Uran 638 Posting Virtuoso

Give your thread a meaningful title and more people will help.

Ene Uran 638 Posting Virtuoso

Maybe you should give your thread a more meaningful title.

Ene Uran 638 Posting Virtuoso

---
Though, I am assigned to write this function just using the String library to write my own parser.
---

You need to tell us this sort of thing right away!

You could use find() assuming each line has one opening and one closing tag. Here is an example of string function find():

line = '<h1>hi my name is Fred</h1>'

# find index of first '<'
ix1 = line.find('<')

# find index of first '>'
ix2 = line.find('>')

# find index of first '</'
ix3 = line.find('</')

# find index of second '>' (past ix2)
ix4 = line.find('>', ix2+1)

# test
print( ix1, ix2, ix3, ix4 )

# now get tags using string slicing and the indexes found
tag1 = line[ix1:ix2+1]
tag2 = line[ix3:ix4+1]

print( tag1 )  # <h1>
print( tag2 )  # </h1>
Ene Uran 638 Posting Virtuoso

This will give your program a certain eloquence:

# convert temperatures using Python2 or Python3

def f2c( fahrenheit ):
    """convert Fahrenheit to Celsius"""
    return ( fahrenheit - 32 ) * 5.0 / 9.0

def c2f( celsius ):
    """convert Celsius to Fahrenheit"""
    return 9.0 / 5.0 * celsius + 32

def main(info):
    print( info )
    while True:
        t = str(input( "Enter the temperature: " )).lower()
        if 'q' in t:
            break
        if 'f' in t:
            # remove last char, convert to number
            num = float(t[:-1])
            celsius = f2c(num)
            print( "%0.1f F = %0.1f C" % (num, celsius) )
        elif 'c' in t:
            # remove last char, convert to number
            num = float(t[:-1])
            fahrenheit = c2f(num)
            print( "%0.1f C = %0.1f F" % (num, fahrenheit) )


info = """\
Enter the temperature with the unit of measurement,
for instance ...
100F will give the temperature in Celsius
100C will give the temperature in Fahrenheit
(enter just q to quit the program)
"""

# program starts here
main(info)

Not totally fool proof, but what is?

Ene Uran 638 Posting Virtuoso

We just discussed that in detail, all you have to do is to slightly modify the solution:

# extract tag names in html code

try:
    # Python2
    import HTMLParser as hp
except ImportError:
    # Python3
    import html.parser as hp

class MyHTMLParser(hp.HTMLParser):
    def __init__(self):
        hp.HTMLParser.__init__(self)
        self.tag_list = list()

    def handle_starttag(self, tag, attrs):
        self.tag_list.append("<%s>" % tag)

    def handle_endtag(self, tag):
        self.tag_list.append("</%s>" % tag)


parser = MyHTMLParser()
html_str = """<h1>hi my name is</h1>"""
parser.feed(html_str)
parser.close()
for tag in parser.tag_list:
    print(tag)

"""my result -->
<h1>
</h1>
"""
Ene Uran 638 Posting Virtuoso

sorry i forgot to mention.. its graphics.py

Sorry, I am using Python 3.1.1 and graphics.py does not work with Python3.

Ene Uran 638 Posting Virtuoso

... and what kind of GUI toolkit is this?

Ene Uran 638 Posting Virtuoso

Good show! So the question is, can you use your program to compute all the trig functions you wanted (sin, cos, tan, arcsin, etc.).

Ene Uran 638 Posting Virtuoso

I tried Netbeans and found it very awkward, especially for Python code. I have Windows and mostly use PyScripter. I can run code initially from memory and don't have to make a project out of it.

Ene Uran 638 Posting Virtuoso

Just a general example of functions and their parameters/arguments:

# example of passing parameters/arguments to and from functions

def get_data():
    """get the data from the user, from a file, or hard coded"""
    mydata = [1, 2, 3, 4]
    # return requested data to caller
    return mydata

def process_data(data=None):
    """this is also the main function of the program"""
    # if no data is passed, get it with this function call
    if not data:
        data = get_data()
    minimum_data = min(data)
    maximum_data = max(data)
    # pass the 2 needed data paramters/arguments to this function
    show_result(minimum_data, maximum_data)

def show_result(min_data, max_data):
    """display the result, needs 2 data paramters/arguments"""
    print( "result: min=%s  max=%s" % (min_data, max_data) )

# call the main function to start
# use default data via function get_data()
process_data()

# you can also supply the needed data to the main function
data = list("abcd")
process_data(data)

"""overall result -->
result: min=1  max=4
result: min=a  max=d
"""

Study it carefully! If you have questions, ask. Avoid global variables, as your program gets larger, they can easily create hard to find bugs.

Note: this code will work with Python2 or Python3

Ene Uran 638 Posting Virtuoso

The only one that comes to mind is the Wing IDE from:
http://wingide.com/wingide

There might be a trial version you can test drive.

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

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

Try
ascii += cs_string

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)