shadwickman 159 Posting Pro in Training

Um... what exactly are you trying to say with the above post? So you posted some code. Good work, but what is your question/motive?

shadwickman 159 Posting Pro in Training

Well here is the py2exe website:
http://www.py2exe.org/
And here is their tutorial that you should follow:
http://www.py2exe.org/index.cgi/Tutorial

This only makes executables which run on Windows. However, most Linux distributions already come with Python installed, so Python .py files should run fine from them as-is.

shadwickman 159 Posting Pro in Training

py2exe can make .exe files for Windows. These .exe files can run without Python installed. However, .exe files will not run on Linux.

shadwickman 159 Posting Pro in Training

Ohh ok, gotcha. You had me confused there for a moment :P

shadwickman 159 Posting Pro in Training

If you were to take the most updated code, you'd see that it works. This is what Lardmeister posted:

import wx

ID_FILE_QUIT = 101

class MainFrame(wx.Frame):
    def __init__(self, title):
        wx.Frame.__init__(self, None, wx.ID_ANY, title=title)
        self.menuBar = wx.MenuBar()
        self.fileMenu = wx.Menu()
        self.fileMenu.Append(ID_FILE_QUIT, '&Quit\tCtrl+Q')
        self.Bind(wx.EVT_MENU, self.quit, id=ID_FILE_QUIT)
        self.menuBar.Append(self.fileMenu, '&File')
        self.SetMenuBar(self.menuBar)
        self.Show()
        
    def quit(self, event):
        self.Close(True)


app = wx.App()
frame = MainFrame('Ya Mum')
app.MainLoop()

Which tom tetlaw acknowledged as he said "all I need to do is put the function name, not call the function". This is what we're doing by binding the function self.quit, rather than self.quit().

shadwickman 159 Posting Pro in Training

Yep, no errors whatsoever with my Python 2.5.4 installation either...

shadwickman 159 Posting Pro in Training

Better test it, that won't work!

Why not? It worked for me when I tested his code... and there's nothing wrong with his binding as I added another menu item with a separate function and ID and that still worked without conflict.

shadwickman 159 Posting Pro in Training

You will have to make separate executables for Windows and Linux too.

shadwickman 159 Posting Pro in Training

And make sure that your file isn't some huge size that you shouldn't be loading into memory all at once. You can just go through the lines with the xreadlines() iterator instead.

# this requires the output file to already exist and it should be
# blank, as opening it with mode "a" will just append lines to it.

fhi = open("input_file", "r")
fho = open("output_file", "a")
for line in fhi.xreadlines():
    if "rs" not in line:
        fho.write(line)
fhi.close()
fho.close()

But if you are loading it all into memory as a list like paulthom suggested, make sure to cycle the file in a way that deleting indices as you go won't mess up the loop, like paulthom's idea would. This below example shows the odd effects of deleting the indices during a for loop:

L = ['a', 'b', 'c', 'd']
for i, item in enumerate(L):
    del L[i]

"""resulting L:
['b', 'd']
"""

You could do it like this though:

fh = open("input_file", "r")
data = fh.readlines()
fh.close()

i = 0
while i < len(data):
    del data[i]
    i += 1
shadwickman 159 Posting Pro in Training

Ah thanks for catching that one line where I forgot to assign the list's value to "c". That's what I get for not testing code! :P

And I think that re.sub may be broken in Python 2.2... well, using a pattern like you did (the preceeding "r" in front of the string). If you give this mail a quick read, you'll see that Guido said it was broken with raw strings.

shadwickman 159 Posting Pro in Training

That error makes no sense. Is the section of code you posted oh here the entirety of it? Or is this a segment of something larger which might be causing the issue? As far as I know, re has sub available even in Python 2.2

Technically, the newest version of Python is 3.0, but I wouldn't go for that yet. It has large overhauls and is not backwards compatible. Plus third-party stuff isn't really updated to it yet. Most people (myself included) stick with 2.6 (or 2.5 too) as it's the best to date cause Python 3.0 is still too new. I'd really strongly recommend upgrading to 2.6 unless you're forced to stick with 2.2.

shadwickman 159 Posting Pro in Training

That makes no sense. Python 2.3 though is when the built-in enumerate function was introduced... your custom one should work fine though. It's outputting "HELLO_PYTHON_WORLD" two times?...

How about an (ugly) alternative method?

s1 = "HelloPythonWorld"
s2 = ""
index = 0
while index < len(s1):
    if c.isupper() and index > 0:
        s2 += '_' + c
    else:
        s2 += c
    index += 1

s2 = s2.upper()
print s2

This doesn't use that custom enumerate class you made. What output does this give you?

shadwickman 159 Posting Pro in Training

I'll formulate this below code based on the presumption that you're printing this and not storing it in a 2D array.

void displayBox ( int width, int height, char FillChar )
{
    for(int y = 0; y < height; y++) {
        for(int x = 0; x < width; x++) {
            // Top or bottom row.
            if(y == 0 || y == height - 1)
                cout << "_";

            // In between top and bottom
            else {
                // Side
                if(x == 0 || x == width - 1)
                    cout << "|";
                // Filler
                else
                    cout << FillChar;
            }
        }
        cout << endl;
    }
}

Cycle through the the y-direction (the height, therefore each row) and then loop across the x-direction of that row (the width) and decide what to output. If it is the first or last row it will display the underscore "_". If it isn't, but if it is the side, it will display the pipe "|", and if it isn't that either, then it must output the FillChar. At the end of each row's x-direction, output a newline.

This worked perfectly for me when I tested it even though I've barely touched C++ :P (Python is for me). I hope that explained it well enough though - tell me if you need me to clarify it more!

shadwickman 159 Posting Pro in Training

This still makes no sense. You can't "call" the other functions to get the variables they had. And besides, you already passed them on to that last function anyways. And what exactly do you mean by "to create a box". Can you give what sample output would look like?

shadwickman 159 Posting Pro in Training

By the way, please use code tags around your code instead of typing "Code" and "end of code".

Anyways, I don't see what your problem is exactly. Don't you just need to actually code in whatever you want performed into the final function and you're all set?

shadwickman 159 Posting Pro in Training

Hi again :D
I don't know why, but it wasn't accepting the negative values in the event handling. I just made the "down" values negative and multiplied positive values instead, like this:

import pygame
from pygame.locals import *

screen = pygame.display.set_mode((1024, 768))
background = pygame.image.load('marioscreendesign.bmp')
man = pygame.image.load('superdudepic.bmp')

screen.blit(background, (0,0))
screen.blit(man,(0,0))
pygame.display.flip()
for i in range(100):
   screen.fill((0,0,0))
   screen.blit(background, (0,0))
   screen.blit(man,(i,0))
   pygame.display.flip()
   pygame.time.delay(50)

while 1:
    # USER INPUT
    clock.tick(30)
    for event in pygame.event.get():
        if not hasattr(event, 'key'): continue
        down = event.type == KEYDOWN     # key down or up?
        # I just made the "down" value negative and it accepted that.
        if event.key == K_RIGHT: k_right = -down * 5
        elif event.key == K_LEFT: k_left = down * 5
        elif event.key == K_UP: k_up = down * 2
        elif event.key == K_DOWN: k_down = -down * 2
        # end
        elif event.key == K_ESCAPE: sys.exit(0)     # quit the game
    screen.fill(BLACK)

EDIT:
Change your conditional statements so that they're not 1-liners, which fixes it:

# ...
# excerpt from your code, making the IFs indented
while 1:
    # USER INPUT
    clock.tick(30)
    for event in pygame.event.get():
        if not hasattr(event, 'key'): continue
        down = event.type == KEYDOWN     # key down or up?
        if event.key == K_RIGHT:
            k_right = down * -5
        elif event.key == K_LEFT:
            k_left = down * 5
        elif event.key == K_UP:
            k_up = down * 2
        elif event.key == K_DOWN:
            k_down = down * -2
        elif event.key == K_ESCAPE:
            sys.exit(0)     # quit the game
    screen.fill(BLACK)
shadwickman 159 Posting Pro in Training

Very true. And seeing as he basically did that in Perl I'm sure he won't find the Python syntax too confusing.

shadwickman 159 Posting Pro in Training

You don't really need to be using regular expressions on something this simple though...

shadwickman 159 Posting Pro in Training

You can incorporate this easily into your script as a function, etc.

# split at the first bracket - the function, and the arguments
func, args = f.split("(")
# split the function into its type and name
func = func.split(" ")
# split the arguments at each comma
args = args.split(",")
# get rid of ending bracket and semicolon from last arg
args[-1] = args[-1][:2]
# put both lists together
result = func + args
#strip any leading or trailing whitespace from the items
result = [item.strip() for item in result]
# remove any list indices that are blank strings
result = filter(lambda x: x != "", result)

""" my result on the first line in your file:
['int', 'Function1', 'int arg1', '"0|1"', 'char * arg2']
"""

That's pretty well commented for you to understand. The last little strip() part is because when split at a comma, the following argument would start with a space. By calling strip() on all the resulting items, we ensure that none of them have excess leading or trailing whitespace. And when we split the func list at any spaces (to get the type and name), the space right after the name (before the bracket originally) made a blank index, so later on I added that filter call to weed out any blank-string indices. Tell me if you need any other clarification.
Hope that helps!

shadwickman 159 Posting Pro in Training

If by each "word", you mean strictly at every space, then you could read the file line by line, and perform this on every line:

fh = open('filename', 'r')
for line in fh.readlines():
    # use 'xreadlines()' if the file is large and you just want an iterator
    words = line.split(' ')
    # returns an array of every item between the spaces
    # do something else...
fh.close()

The 'words' list would look like this on the first line in that file:

['int', 'Function1', '(int', 'arg1,', '"0|1",', 'char', '*', 'arg2);']

Notice that some indices still have the commas, brackets, etc in them because they didn't have spaces in between. Is this ok or did you mean "words" as in a list of the function type, name, and the arguments not broken up like split(' ') did? Give an example of what you want the split-up line's list to look like.

shadwickman 159 Posting Pro in Training

Oh! That's a simple problem. Use the str object's strip() function. It removes all leading and trailing whitespace. Like this:

>>> a = " \t Hello World!\n "
>>> b = a.strip()
>>> b
'Hello World!'

As you can see, all spaces, tabs, newlines, etc. get removed. When you compare the indices in the list, strip each one first. Alternatively, you can strip each line with a list comprehension when you store the [icode]readlines()[/icode] lists like so:

line_list = [x.strip() for x in open("filename", "r").readlines()]

That way the lists get stored without any whitespace in their indices.

shadwickman 159 Posting Pro in Training

Well, seeing as you didn't read this simple post about using code tags, your Python has no indentation. Brilliant. I'm not going to try to fix your code's indentation so that I can begin to help with your problem. If you can post it with those helpful tags around it, I'll take a look.

shadwickman 159 Posting Pro in Training

What do you mean, a single "filter" result? Filter returns a list... oh wait. Are you using Python 2.x, or are you using Python 3.0? If you are then filter actually returns an iterator. Anyways, what did you mean by "single result"?

shadwickman 159 Posting Pro in Training

Oh damn! I made a mistake there. That line should read:

c = filter(lambda x: x in b, a)

That's embarrassing haha... I typed that in wrong. the statement x in b just returns a boolean of whether or not value "x" is an item in list "b", basically "is x in b?". The "if" shouldn't be there because that starts to define a conditional statement. Sorry about that!

Anyways, lambda functions are just a way of declaring simple functions on-the-go without assigning a name to them.

shadwickman 159 Posting Pro in Training

You can try the built-in filter function. Here's what I tried in the interpreter:

>>> a = [
	'filter',
	'lol',
	'filter',
	'lol',
	'lol',
	'filter',
	'lol'
        ]
>>> b = ['filter']
>>> c = filter(lambda x: if x in b, a)
>>> c
['filter', 'filter', 'filter']

As you can see, it takes each item in the list passed to filter (in this case, "a"), and returns a list of the values that returned True in the function passed to it.
In this case, the lambda function would return True if the current item (x) is in list "b". I hope that simplified your code a lot :P

Here's a Dive Into Python links concerning filter, and lambda.

Nyaato commented: Thanks for helping! +1
shadwickman 159 Posting Pro in Training

You can browse through that svn tree like folders, and save/view the files in each one. Look at their GoogleCode wiki for info about each of the topics (boot, boa, etc.).

shadwickman 159 Posting Pro in Training

Looks like you can connect anonymously via HTTP and browse the source.
http://cleese.googlecode.com/svn/trunk/

You'd need to build it yourself, and definitely have a look through their wiki to see if they have any in-depth instructions for that, along with dependencies, etc.

shadwickman 159 Posting Pro in Training

If you mean by "Python OS", an operating system that's built purely on Python, then no. As far as I know, that wouldn't work anyway because the interpreter to run Python needs an OS to run on in the first place (?). Correct me if I'm wrong though...

And I'm not sure about Python with Android, although I believe Jython may work and you can access the Java API that way.

shadwickman 159 Posting Pro in Training

Well, there is no return statement at all in that function... so it would return <i>None</i>.

shadwickman 159 Posting Pro in Training

I'm curious now how long it takes your computer to parse this "50 million line file" with Python, seeing how slow Python is compared to things like C... unless of course you were exaggerating the number of lines.
Anyways, if you open a file with fhandle = open('myfile', 'a') then when you call write("") on it, it'll just append it. Like The_Kernel said, just make sure you keep track of whether the file has been created yet, and if not, open it with the mode parameter as "w".

shadwickman 159 Posting Pro in Training

PLEASE! Use code tags! If you look at your post, you realize your Python code has no indentation anymore, and indentation is a crucial part of Python. I'm not going to bother looking through your code until you edit that post and put your code in those tags to preserve the spacing.

Salem commented: Well said! +36
shadwickman 159 Posting Pro in Training

In case you didn't notice, your linedata dictionary has no key "id". Hence you receiving the "KeyError" problem. You need the ID of the column you're inserting this into if I'm correct (I barely touched on MySQL about a year ago). Is the table you're inserting this into blank, and you're building it up? Or does it contain data and you're just overwriting/editing rows?
If you're building up a blank table, why not just track the number of rows you've added to the table so far and then you can use that as the id? Set "rowsadded" to zero at the beginning of your script and then increment it after each row input to the table. That way you can have your linedata dictionary as this:

linedata = {'id':rowsadded, 'time':data[1], 'date':data[9],'latitude':latitude,'longitude':longitude,'speed':data[7]}
sneekula commented: thanks for taking the tough ones +8
shadwickman 159 Posting Pro in Training

Because when you read lines from a file, a string is returned. Your data[3] is "0833.6323" (as a string). You can just convert it to a float first before the calculation like this: latitude=str(float(data[3])/100.0) EDIT:
I noticed you signed your post "sraven". You already have an account here (under that name) so why did you start this new one?

shadwickman 159 Posting Pro in Training

If you look at this forum, there is a permanent thread called "Projects for the Beginner". See here.
It has a huge amount of projects/ideas in it, so you can start looking through it for stuff to do.

shadwickman 159 Posting Pro in Training

Got it :D

data = [['4/18/94', '29.125', '442.46'],
    ['4/19/94', '29.336', '442.54'],
    ['1/20/04', '75.175', '1138.77'],
    ['1/21/04', '75.711', '1147.62'],
    ['1/22/04', '75.595', '1143.94']]
    
result = []

for item in data:
    # current middle index as a float
    n = float(item[1])
    
    # if there are no items in the result list yet
    if not result:
        result.append(item)
        
    # otherwise, if there are,
    else:
        # previous number (last one in result list) as a float
        prevnum = float(result[-1][1])
        
        if (prevnum < 30 and n > 75) or (prevnum > 75 and n < 30):
            result.append(item)

"""
My result:
[['4/18/94', '29.125', '442.46'], ['1/20/04', '75.175', '1138.77']]
"""
rasizzle commented: excellent advice +1
shadwickman 159 Posting Pro in Training

This post on stackoverflow seems to have the skeleton code for going about and making it a service.

And there's something about using srvany.exe here.

I've never actually done this myself so I can't offer much more insight...

shadwickman 159 Posting Pro in Training

This mail might help:
http://mail.python.org/pipermail/python-list/2002-August/161778.html

It looks like there are some good example's of it being used in the code, and about adjusting privileges.

EDIT:
It looks like the last argument you'd want to be 1 or True because that's the reboot option...

shadwickman 159 Posting Pro in Training

Can you post some of your code? I'm confused as to why you need to hold so many files open at one time... could you just cycle them one by one and not have them all open?

shadwickman 159 Posting Pro in Training

sraven, this only works when the command prompt window is in focus. If you're trying to capture all input for other applications too, then you'll need to use pyHook or be able to expand on sneekula's getch() example, but I'm not sure how to make that grab key presses with the command prompt not being in focus....

shadwickman 159 Posting Pro in Training

I think you can have it pass the command to the computer via the os module. Like for Debian-based GNU/Linux distros you could write:

import os
os.system("halt")

The only problem I can think of is that this would require super-user privileges to execute the shut down.

With Windows, if you have the win32api module, you can try this:

import win32api
win32api.InitiateSystemShutdown()

I haven't tried that before though, so you may want to look deeper into that. Hope I helped a bit!

shadwickman 159 Posting Pro in Training

Why did you post VB code? This is the Python forum. Regardless, please put it in code tags.

shadwickman 159 Posting Pro in Training

I'd say split the string into a list and use the filter method:

file_Name1 = 'abc123de'
# store that string as a list of characters
L1 = list(file_Name1)
# call filter on it using a lambda expression
L1 = filter(lambda x: x in '1234567890', L1)
# L1 now = ['1', '2', '3']
num_digits = len(L1)

EDIT:
If you need to know what filter does, lookie here:

filter(function, iterable)

    Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

    Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.

    See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.
shadwickman 159 Posting Pro in Training

Which Linux distro are you using? Regardless, if you want a visual editor for wxPython, I'd suggest wxGlade. It generates nice code but it may take a little getting used to using. I mostly just code all my GUIs by hand anyways.
As for good wxPython resources, here's some:

Style Guide - Not too comprehensive, but might offer some standardizing tips.
wxPython by Example - A short tutorial which has good examples for bare-bones apps.
wxPython Cookbook - Contains a lot of information on various aspects of wxPython. Lots of examples.
Widget Examples - Has a number of good application skeletons and examples about individual widgets and their uses.
Documentation - The regular documentation for wxPython.

VERY GOOD Tutorial - I'd recommend giving this a read through and looking at the example code as it's quite large and it covers a lot in an understandable way.

wxGlade Tutorial - If you decide to give wxGlade a go. Make sure to learn pure wxPython coding first so that you can do it by hand. Then use this for large GUIs just to speed things up if you want.

There was another very definitive page with all the widgets and examples and information about them, but I can't seem to find it at the moment. I'll post it later if I do find it. Hope these help for now! :)

shadwickman 159 Posting Pro in Training

As for a regular application, I'd go with wxPython for sure. Best GUI toolkit I've used for Python (I can't stand Tkinter at all).
If you want to make it more graphics-rich and not look like a regular program, you can try pygame, but that might be a bit difficult to jump into right away.

shadwickman 159 Posting Pro in Training

Expanding even further:

import random

mini = 1  # min. number of tuple indices
maxi = 5  # max. number of tuple indices
low = 1  # low-end of range of number
high = 9  # high-end of range of number

result = []
for j in range(10):
    current = []
    # add a random number of indices to the tuple
    for k in range(random.randint(mini, maxi)):
        # add another number to the current list
        current.append(random.randint(low, high))
    # convert current list into a tuple and add to resulting list
    result.append(tuple(current))
"""
my result:
[(2, 1), (5, 9, 6, 1), (3,), (7, 1, 3), (5, 2, 5, 6, 1), (3,), (1, 1, 9, 8, 7), (2,), (9, 5, 3), (6,)]
"""

Just allows for a random number of indices in each tuple.

shadwickman 159 Posting Pro in Training

Doesn't the windows installer come with it?

EDIT:
for Ubuntu, it should be sudo apt-get install idle-python3.0

shadwickman 159 Posting Pro in Training

Your "items" dictionary doesn't have a key named "o" which apparently you are trying to locate. The line if p.weapon == items[sitem[1]] is basically equating to if p.weapon == items["o"] . That seems to not be in the chunk of "relevant code" that you posted, but even so, the code you posted throws an error on its own.

Regarding the code, you shouldn't cycle the dictionary "items" like you are currently doing. Cycle the list of the values in the dictionary, and unpack them to variable names like this:

items = {'sword':['sword', 3, 15],
    'axe':['axe', 5, 25],
    'bow and arrow':['bow and arrow', 4, 20]}
for item, price, damage in items.values():
    print item
    print "\tprice", price
    print "\tdamage", damage

Your items dictionary is a little repetitive though, by putting the item name as both the key and the first index in the value of it. This is much better:

items = {'sword':[3, 15],
    'axe':[5, 25],
    'bow and arrow':[4, 20]}
# cycle through the (key, value) list of the dict
for item, stats in items.items():
    print item
    print "\tprice", stats[0]
    print "\tdamage", stats[1]

Hope that helped!

Ene Uran commented: very nice example +7
shadwickman 159 Posting Pro in Training

Well, if you ran what you posted, nothing will happen. You defined these functions and classes but you haven't actually done anything with them. None of these get called during the execution of the script.

shadwickman 159 Posting Pro in Training

Well, there's probably a much easier way of writing the data to the screen in a nice table, as all the conditionals you have in the header_content function don't look too pleasant, even though they get the stuff done.
I wrote a quick table function that accepts a list containing other lists as the indices, and prints the list out into the headings it receives, and makes sure the spacing is kept nice. You could fix it up to fit your script better, or just use it as a template to see how I went about doing it. Maybe if you want, make it spread the data over a fixed-width of 80 characters or something. Anyways, here's the function:

import sys

'''
Display a list of data, where list[0] is a list of headers, and each index after that contains a row of data, corresponding to the order of the headers.
'''
def display_table(matrix, colspace=4, sepchar='-', capheaders=True):

    # set-up variables
    headers = matrix[0]
    data = matrix[1:]
    spacer = ' ' * colspace
    if sepchar:  # if there is a separator
        if len(sepchar) > 1:  # if more than one character
            sepchar = sepchar[0]  # only keep first one
    colwidths = [ 0 for i in range(len(headers)) ]  # init all max lengths to 0
    
    # read lines and store longest values for each column
    for row in matrix:
        for index, item in enumerate(row):
            length = len(str(item))
            if colwidths[index] < length:
                colwidths[index] = length
        
    # write headers
    for index, …
shadwickman 159 Posting Pro in Training

I don't have time to fully check through all the above code right now, but if you're interested in the guidelines for standardizing Python code, you can have a read through PEP 8.

And as just a speculation, if you're importing this module to use in another program, but don't want certain global variables (as you have opted to use here) accessible by the module it is imported to, then name them with one underscore preceeding their name. Like _array_studentDetails .