Re: pinging from within python

2005-09-18 Thread Harlin Seritt
You can do the following:

import os

data = os.popen('ping machineName').read()
if 'request timed out' in data or 'unknown host' in data:
  Ping Failed Code
else:
  Ping Returned Something Good Code

This is the quickest and really most effective way to get it done IMO.

Harlin Seritt
Internet Villa: www.seritt.org

-- 
http://mail.python.org/mailman/listinfo/python-list


Putting a lock on file.

2005-09-18 Thread Harlin Seritt
I have a file that a few different running scripts will need to access.
Most likely this won't be a problem but if it is, what do I need to do
to make sure scripts don't crash because the input file is in use?
Would it be best to run a loop like the following:

flag = 0
while not flag:
try:
open(file, 'r').read()
flag = 1
except:
pass

This may seem nice on paper but I hate to run a while for an
indeterminate amount of time. Is there anything else that can be done
that would be better?

Thanks,

Harlin Seritt

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 alpha

2005-09-18 Thread Thomas Jollans
D.Hering wrote:
> under gentoo linux 2.6.

that does not exist. gentoo labels installers 2005.0 etc, but I have 
never heard of version numbers.
do you mean gentoo with linux 2.6 ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-18 Thread Michele Simionato
Pedro Werneck wrote:

>>> class M_A(type): pass
...


>>> class A: __metaclass__ = M_A
...
>>> class M_B(M_A): pass
...
>>> class B(A): __metaclass__ = M_B
...
>>> class C(B): __metaclass__ = M_A
...
>>> C.__class__




>>> C.__metaclass__





> Is this supposed to happen ?

Yes, or at least I feel this is a reasonable behavior. You get the
stricted metaclass(M_B) and not the more generic one
(M_A), so you don't lose anything. Remember that given a class C, its
metaclass is given by C.__class__, not by C.__metaclass__,
despite the name. I wrote some code to automatically solve metaclass
conflicts (see for instance my Oxford lectures
http://www.phyast.pitt.edu/~micheles/oxford-lectures.zip) and it works
in the same way, it uses the strictest metaclass.
You argue that in this case an error should be raised, since "errors
should never pass silently". May be. You are free to post
the bug report and look at the opinions of the developers. I am happy
enough with the current behavior and I would just
update the docs.

Michele Simionato


  Michele Simionato

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Putting a lock on file.

2005-09-18 Thread tiissa
Harlin Seritt wrote:
> I have a file that a few different running scripts will need to access.
[...]
> This may seem nice on paper but I hate to run a while for an
> indeterminate amount of time. Is there anything else that can be done
> that would be better?

On posix systems, there is a fcntl module [1] that can be useful.


[1] http://python.org/doc/2.4.1/lib/module-fcntl.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python game coding

2005-09-18 Thread Alessandro Bottoni
Lucas Raab wrote:

> Saw this on Slashdot
> (http://developers.slashdot.org/article.pl?sid=05/09/17/182207&from=rss)
> and thought some people might be interested in it. Direct link to the
> article is
>
http://harkal.sylphis3d.com/2005/08/10/multithreaded-game-scripting-with-stackless-python/
> 

Very interesting! 

BTW: I wonder if and when someone will use stackless python or pygame as a
basis for developing a _visual_ development environment for 2D
games/multimedia like Macromedia Director. It would be a killer app.

CU
---
Alessandro Bottoni
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python game coding

2005-09-18 Thread Diez B. Roggisch

> Very interesting! 
> 
> BTW: I wonder if and when someone will use stackless python or pygame as a
> basis for developing a _visual_ development environment for 2D
> games/multimedia like Macromedia Director. It would be a killer app.

Blender. It currently doesn't use stacklass AFAIK, but that shouldn't be 
too hard to fix.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python game coding

2005-09-18 Thread Diez B. Roggisch
Diez B. Roggisch wrote:
> 
>> Very interesting!
>> BTW: I wonder if and when someone will use stackless python or pygame 
>> as a
>> basis for developing a _visual_ development environment for 2D
>> games/multimedia like Macromedia Director. It would be a killer app.
> 
> 
> Blender. It currently doesn't use stacklass AFAIK, but that shouldn't be 
> too hard to fix.

Oop - I read 3d instead of 2d.. Hm, 3d _can_ do 2d, so just don't allow 
your cameras do fancy stuff like rotating :)

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brute force sudoku cracker

2005-09-18 Thread Diez B. Roggisch
As everyone posts his, I'll do the same :) It uses some constraint based 
solving techniques - but not too complicated ones. When stuck, it 
backtracks. So far it never failed me, but I haven't tested it too 
thouroughly.


Diez
import copy

def condense(vals):

if len(vals) == 0:
return ""
ranges = [0]
ranges += [i+1 for i, v in enumerate(vals[:-1]) if vals[i+1] - v > 1]
ranges.append(len(vals))
ranges = zip(ranges[:-1], ranges[1:])
def f(l):
if len(l) > 1:
return "%i-%i" % (l[0], l[-1])
return "%i" % l[0]
return ", ".join([f(vals[a:b]) for a,b in ranges])


riddle1 = """
1**83***2
57***1***
***5*9*64
7*4**859*
**3*1*4**
*514**3*6
36*7*4***
***6***79
8***52**3
"""
riddle2 = """
 **2*9*1*7 
 *386* 
 4 
 *5*** 
 **9*1*3** 
 ***4* 
 4 
 *792* 
 8*6*3*7** 
"""
class Constraint(object):
def __init__(self, fields):
self.__fields = fields

def apply(self, sudoko, all_nums = set(xrange(1,10))):
changed = False 
placed = set()
[placed.update(sudoko[x][y]) for x,y  in self.__fields if 
len(sudoko[x][y]) == 1]   
news = []
for x,y  in self.__fields:
old = sudoko[x][y]
if len(old) > 1:
new = old.intersection(all_nums.difference(placed))
if len(new) == 0:
raise ValueError()
if old != new:
changed = True
sudoko[x][y] = new
news.append(((x,y), new))
# naked pair elimination
if changed:
return True
pair_found = False
#print "-" * 30
#print sudoko
#print "-" * 30
for i in xrange(2, 5):
all = [list(n) for f,n in news if len(n) == i]
[l.sort() for l in all]
all = [tuple(l) for l in all]
all.sort()
#print "all ", all
for j, l in enumerate(all[:-1]):
if len(all[j:j+i]) == i and len(set(all[j:j+i])) == 1:
np = set(l)
#print "naked pair", np
for k, (f, n) in enumerate(news):
if n != np:
#print "Adjusted ", f, n
new = n.difference(np)
if len(new) == 0:
raise ValueError()

if new != n:
pair_found =True
news[k] = (f, new)
if pair_found:
for (x,y), n in news:
sudoko[x][y] = n
return pair_found

class Sudoku(object):
def __init__(self, parent=None):
if parent is None:
self.__field = [[set(xrange(1, 10)) for i in xrange(9)] for j in 
xrange(9)]
self.__constraints = []
# row constraints
for y in xrange(9):
self.__constraints.append(Constraint([(x,y) for x in 
xrange(9)]))
# column constraints
for x in xrange(9):
self.__constraints.append(Constraint([(x,y) for y in 
xrange(9)]))
# field constraints
for xx in xrange(0,9,3):
for yy in xrange(0,9,3):
self.__constraints.append(Constraint([(x+xx, y+yy) for x in 
xrange(3) for y in xrange(3)]))
else:
self.__field = copy.deepcopy(parent.__field)
self.__constraints = parent.__constraints
 

def __getitem__(self, index):
class Column(object):
def __init__(self, column, field):
self.__column = column
self.__field = field

def __setitem__(self, index, value):
self.__field[self.__column][index] = value

def __getitem__(self, index):
return self.__field[self.__column][index]

return Column(index, self.__field)

def __repr__(self):
res = [[None for i in xrange(9)] for j in xrange(9)]
col_widths = [0 for i in xrange(9)]
for x in xrange(9):
for y in xrange(9):
vals = list(self[x][y])
vals.sort()
r  = condense(vals)
res[x][y] = r
if col_widths[x] < len(r):
col_widths[x] = len(r)

rows = []
for y in xrange(9):
rows.append(" ".join(["%s%s" % (res[x][y], " " * (col_widths[x] - 
len(res[x][y]))) for x in xrange(9)]))

return "\n".join(rows)

def load(self, instance):
lines = [line for line in instance.split() if line]
for x in xrange(9):
for y in xrange(9):
v = lines[y][x]
if v != "*":
self[x][y] = set([int(v)])


def solve(self):
changed = set([True])
while True in chan

Re: [Python-Dev] python optimization

2005-09-18 Thread Diez B. Roggisch
Neal Becker wrote:
> One possible way to improve the situation is, that if we really believe
> python cannot easily support such optimizations because the code is too
> "dynamic", is to allow manual annotation of functions.  For example, gcc
> has allowed such annotations using __attribute__ for quite a while.  This
> would allow the programmer to specify that a variable is constant, or that
> a function is pure (having no side effects).

Use pyrex. It is basically an python-syntax-clone C-Generator, and 
allows for type-annotation. It's supported by distutils, so that you can 
develop using pure python, and then take your critical code and move it 
to pyrex, with not too much effort.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Doc Problem Example: os.path.split

2005-09-18 Thread Xah Lee
Python Doc Problem Example

Quote from:
http://docs.python.org/lib/module-os.path.html
--
split(  path)
Split the pathname path into a pair, (head, tail) where tail is the
last pathname component and head is everything leading up to that. The
tail part will never contain a slash; if path ends in a slash, tail
will be empty. If there is no slash in path, head will be empty. If
path is empty, both head and tail are empty. Trailing slashes are
stripped from head unless it is the root (one or more slashes only). In
nearly all cases, join(head, tail) equals path (the only exception
being when there were multiple slashes separating head from tail).
--

Can anyone tell me what this verbiage is trying to fucking say?

what the fuck is with the head and tail thing?

is the doc writer, trying to write the doc with some austereness, but
is confused about the behavior of split, or confused about expressing
it? Did his pretension fucked him up?

i was working on a program where i needed to split a path into dirname,
corename, and suffix. But this fucking python doc diverted my work and
wasted my time. It normally isn't a problem to find imperfections in
the world except the fucking OpenSourcers fuck with their fucking
moronicity and moronitude and propagate haughtily their fucking lies
and stupidity. Die.

Suggested rewrite:

split(path)
returns a pair (dirname,filename), where dirname is the part of path
up to the last slash, and filename is the rest of the string after the
last slash.

Exceptional cases are:
• if path is a single slash (or repeated), then path == dirname and
filename is empty.
• If the “last” slash is repeated, they are treated as one single
slash.


Fuck the motherfucking liers of OpenSourcing fuckheads.
(Note: my use of OpenSource here does not include people of GNU
community.)

For more about Python Doc problems, see
http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Doc Problem Example: os.path.split

2005-09-18 Thread Steven D'Aprano
On Sun, 18 Sep 2005 03:46:03 -0700, Xah Lee wibbled:

> Can anyone tell me what this verbiage is trying to fucking say?

Please don't feed the trolls.

In other words, if everybody ignores this loser, he might crawl back under
the rock he came from.

-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Doc Problem Example: os.path.split

2005-09-18 Thread Laszlo Zsolt Nagy

>is the doc writer, trying to write the doc with some austereness, but
>is confused about the behavior of split, or confused about expressing
>it? Did his pretension fucked him up?
>  
>
 Dear Xah Lee,

The Python community is very sorry because we have a very bad 
documentation. You are right. The documentation is bad, and the language 
is bad etc. The mailing list itself is not helpful and you cannot use it 
for anything. We will try to follow all of your glorious suggestions.  
But we have so many things to do, I'm affraid you need to wait until 
Python 5000 is released. Until that, I can recommend you the Visual 
Basic language. Its documentation is much more perfect. MSDN is really 
really well structured and easy to use! It is commercial, and - as you 
would expect - you will get immediate fixes after you make a kind 
suggestion like this. I think this is the best thing you can do.

For more information about this fabolous  ClosedSource commercial 
product, please visit this link:

http://msdn.microsoft.com/vbasic/

Good Luck!

   Les

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do Pythoneers reinvent the wheel?

2005-09-18 Thread Jorgen Grahn
On 14 Sep 2005 07:03:28 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Stefano Masini wrote:
>
>> There are a few ares where everybody seems to be implementing their
>> own stuff over and over: logging, file handling, ordered dictionaries,
>> data serialization, and maybe a few more.
>> I don't know what's the ultimate problem, but I think there are 3 main 
>> reasons:
>> 1) poor communication inside the community (mhm... arguable)
>> 2) lack of a rich standard library (I heard this more than once)
>> 3) python is such an easy language that the "I'll do it myself" evil
>> side lying hidden inside each one of us comes up a little too often,
>> and prevents from spending more time on research of what's available.
>
> I'd like to add one more that I haven't seen mentioned yet: ease of
> maintenance and distribution.
>
> Whenever I decide to use someone else's package for an important
> project, I need to make sure it is either maintained or looks clean
> enough that I can maintain it myself. For small packages, that alone is
> often more effort than writing my own.

If the licenses are compatible, you also have the option to simply steal the
code and merge it into yours -- possibly cutting away the stuff you don't
need.  Or if not, to read and learn from it.

That's another kind of reuse, which is sometimes overlooked.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brute force sudoku cracker

2005-09-18 Thread [EMAIL PROTECTED]
Had the same reaction as everyone when I saw theses puzzles a month or
so ago, so here is my solution...
the solve function is recursive, so it can also solve the 'deadlock
set' (example3). find_cell looks for an empty cell with the most filled
cells in it's row and column, so the search tree doesn't grow too
'wide'.

---

example1 = """8 9 - - - - 3 - 4
- - 5 - 3 - - - -
- 7 - - 8 1 5 - -
- 4 - - - 7 - - 3
- - - 5 4 3 - - -
2 - - 1 - - - 5 -
- - 7 9 1 - - 4 -
- - - - 7 - 2 - -
9 - 8 - - - - 7 5"""

example2 = """- 5 2 - - - - - -
9 - - 1 - - - 5 -
- - 4 8 3 - - - 2
- 3 - - 9 - 1 - 5
- - - - - - - - -
5 - 7 - 6 - - 4 -
1 - - - 7 3 6 - -
- 7 - - - 9 - - 3
- - - - - - 2 7 -"""

example3 = """- 3 - 5 - - 8 1 -
1 - - 7 6 - - 9 -
4 - - - - - - - -
8 4 3 9 7 5 1 2 6
- 1 - 6 - - - 7 8
6 - - 8 - 1 9 3 -
- - - 1 5 7 - - 9
- 9 - - 8 6 - - 1
- 6 1 - 9 2 - 8 -"""

class ImpossibleException(Exception): pass


def field_from_string(field_str):
def mapper(x):
if x == '-': return None
else: return int(x)
return [map(mapper, line.split()) for line in
field_str.split('\n')]


def field_from_file(filename):
f = open(filename)
field = field_from_string(f.read())
f.close()
return field


def print_field(field):
def mapper(x):
if x == None: return '  '
else: return str(x)+' '
str_rows = [map(mapper, x) for x in field]
str_rows = ['| ' + " ".join(str_row) + '|' for str_row in str_rows]
print 'x'+'-'*27+'x'
print "\n".join(x for x in str_rows)
print 'x'+'-'*27+'x'


def check_constraint(field, (x,y), num):
"""Checks if putting num at (x,y) is valid."""
#row constraint
occ = [elem for elem in field[x] if elem == num]
if occ:
return False
#column constraint
occ = [field[k][y] for k in range(9) if field[k][y] == num]
if occ:
return False
#subfield constraint
sub_x, sub_y = x//3, y//3
occ = [field[k+3*sub_x][l+3*sub_y] for k in range(3) for l in
range(3)
if field[k+3*sub_x][l+3*sub_y] == num]
if occ:
return False
return True


def find_cell(field):
"""Returns coords of an empty cell or None if all cells are filled.
Returns cells with most row and column 'neighbours' first."""
def count(row):
return len([x for x in row if x is not None])

#[(count, index), ... ]
x_counts = zip((count(row) for row in field), range(9))
sorted_x_counts = sorted(x_counts, reverse=True)
x_keys = [l for k,l in sorted_x_counts]

columns = [[field[k][y] for k in range(9)] for y in range(9)]
y_counts = zip((count(column) for column in columns), range(9))
sorted_y_counts = sorted(y_counts, reverse=True)
y_keys = [l for k,l in sorted_y_counts]

for x in x_keys:
for y in y_keys:
if field[x][y] == None:
return (x,y)
else:
return None


def set_value(field, (x,y), num):
"""Returns copy of field with cell (x,y) set to num."""
#new_field = copy.deepcopy(field)
new_field = [row[:] for row in field]
new_field[x][y] = num
return new_field


def solve(field):
xy = find_cell(field)
if not xy:
return field
poss = [e for e in range(1,10) if check_constraint(field, xy, e)]
for e in poss:
new_field = set_value(field, xy, e)
try:
return solve(new_field)
except ImpossibleException:
pass #try next possibility
raise ImpossibleException()


if __name__ == '__main__':
field = field_from_string(example3)
print 'initial field:'
print_field(field)
print 'solution:'
try:
print_field(solve(field))
except ImpossibleException:
print 'not solvable'

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Putting a lock on file.

2005-09-18 Thread Steven D'Aprano
On Sat, 17 Sep 2005 23:58:58 -0700, Harlin Seritt wrote:

> I have a file that a few different running scripts will need to access.
> Most likely this won't be a problem but if it is, what do I need to do
> to make sure scripts don't crash because the input file is in use?
> Would it be best to run a loop like the following:
> 
> flag = 0
> while not flag:
> try:
> open(file, 'r').read()
> flag = 1
> except:
> pass
> 
> This may seem nice on paper but I hate to run a while for an
> indeterminate amount of time. Is there anything else that can be done
> that would be better?

Instead of while flag, use a for loop. That way, when you have tried
unsuccessfully some known number of times, you can report back to the user
that you have tried and failed.

Also, in any serious program you should give better error reporting than
the above, especially for file-related errors. A bare "except:" that
catches all errors is generally bad practice. Eg, suppose you meant to
write "open(filename, 'r').read()" but accidentally mistyped ".raed()"
instead. Your except clause would catch the error, and you would spend
hours trying to work out why your file can't be opened.


Try something like this:


import errno

def get_file(fname, max_tries=10):
"""Returns the contents of fname, or None if there is an error."""
for i in range(max_tries):
try:
fp = open(fname, 'r')
text = fp.read()
fp.close()  # don't wait for Python to close it for you
return text
except IOError, (error, message):
if error == errno.ENOENT:
print "No such file. Did you look behind the couch?"
break
elif error == errno.EIO:
print "I/O error -- bad media, no biscuit!"
break
elif error in (errno.EPERM, errno.EACCES):
print "Permission denied. Go to your room!"
break
elif error == errno.EINTR:
print "Interupted call... trying again."
continue
elif error in (errno.EWOULDBLOCK, errno.EAGAIN):
print "Temporary error..." \
" please wait a few seconds and try again."
continue
else:
# Some other error, just print Python's message.
print message 
else:
# only called if you don't break
print "Sorry, the file is in use. Please try again later."
return None

You should look at the module errno, together with the function
os.strerror(), for more details. Of course, many people don't worry about
giving their own explanations for IOErrors, and simply return the same
error that Python does.


These two pages might be useful too:

http://www.gnu.org/software/libc/manual/html_node/Error-Codes.html
http://www.gnu.org/software/libc/manual/html_node/File-Locks.html



-- 
Steven.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brute force sudoku cracker

2005-09-18 Thread Anton Vredegoor
Diez B. Roggisch wrote:
> As everyone posts his, I'll do the same :) It uses some constraint based
> solving techniques - but not too complicated ones. When stuck, it
> backtracks. So far it never failed me, but I haven't tested it too
> thouroughly.

Thanks to all for sharing. I like to program sudoku and review such
code. So below here is my current file, I think it uses some techniques
not yet posted here. It also has a difficult 16x16 puzzle which I know
to be solvable (barring typing mistakes) but which my file can't solve
before I get tired of waiting, this might draw some heavyweights in the
ring :-)

I have also read the sudoku wiki page:

http://en.wikipedia.org/wiki/Sudoku

which was very helpfull and interesting (especially the link to Knuths
paper about dancing links was nice, even though I think (but maybe
wrongly so) that we don't need dancing links now that we've got sets,
but it's still a very very interesting paper)

I think the first important step is to realize that some variations
have fewer values so that it is possible to reduce the search space
early. Currently I'm exploring ideas about contigengies as explained in
the wiki above which seems promising, but I haven't found a nice way to
implement them yet. Maybe an easy optimization would be to find values
that don't come up often and choose variations containing those. And
maybe I should switch to an approach that has possibility values inside
the cells instead of computing them on the fly each time, that could
make contigency elimination easier.

Anton


from __future__ import generators
from sets import Set as set

problem1 = ['063000700','000690008','97002',
'002010080','050806090','090070200',
'60013','700045000','009000140']

problem2 = ['030009007','01008','000100090',
'004905006','02010','500607400',
'050001000','40020','700500030']

problem3 = ['030500810','000760090','4',
'043905006','01070','600801930',
'9','090086000','061002080']

problem4 = ['004530080','060009000','90005',
'000800350','0','027006000',
'80007','000300040','090072600']

X =[' 1  0  0  0  0 12  0 10 11  7  6  0  0  4  0  0',
' 0  7  0  0 15 13  0  0  0  0  2  0  0  8  0  0',
' 3  0  0  0  4  0  0  0  0  5  0 12  0 16  0  0',
' 0  0 14  2  0  9  0  0  0  0  1  0  0  0  0  0',
'10 15  0  1  0  0  0  2  0 16  0  0  3  0  0  0',
'12  0  0  3  0  0 15  0  0 13  0  4  0  1  9  5',
' 5  0 11  0  7  0  8  0  0  0  0  0  0 15  0  0',
' 7 13  0 16  0  0  0  6  0  0  0 14  0 10  0  0',
' 0  0 13  0 11  0  0  0 10  0  0  0  1  0 12  0',
' 0  0  7  0  0  0  0  0  0  3  0 16  0 14  0 13',
'16  8  0  0 14  0  5  0  0 15  0  0  4  0  0  6',
' 0  0  0  9  0  0  4  0  1  0  0  0  2  0  0  7',
' 0  0  0  0  0 16  0  0  0  0  8  0 10  5  0  0',
' 0  0  4  0 12  0  6  0  0  0 16  7  0  0  0 14',
' 0  0  6  0  0  1  0  0  0  0 12 13  0  0 11  0',
' 0  0 15  0  0  8 11  3  2  0  9  0  0  0  0  1']

problem5 = [row.split() for row in X]

class State:

def __init__(self,solved,unsolved):
self.solved = solved
self.unsolved = unsolved
self.size = int((len(solved)+len(unsolved))**.25)

def choiceset(self,x,y):
"the set of possible choices for an empty cell"
sz = self.size
res = set(range(1,sz*sz+1))
r,c = x/sz*sz,y/sz*sz
for (i,j),v in self.solved.iteritems():
if x == i or y == j or (r<=ihttp://mail.python.org/mailman/listinfo/python-list


C#3.0 and lambdas

2005-09-18 Thread bearophileHUGS
On Slashdot there is a discussion about the future C#3.0:
http://developers.slashdot.org/developers/05/09/18/0545217.shtml?tid=109&tid=8

http://msdn.microsoft.com/vcsharp/future/

There are many differences, but it looks a bit more like Python:
http://download.microsoft.com/download/9/5/0/9503e33e-fde6-4aed-b5d0-ffe749822f1b/csharp%203.0%20specification.doc

I like the lambda sintax enough. If there is a single parameter the
parentheses may be omitted. They are required if there aren't
parameters. The statement body allows the lambda to do anything.

x => x + 1 Expression body
x => { return x + 1; } Statement body
(x, y) => x * yMultiple parameters
() => Console.WriteLine()  No parameters

The syntax seems nice, but for python the "Statement body" syntax can
be a problem.

Bye,
bearophile

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FTP status problems. (Again)

2005-09-18 Thread Nainto
It works! Thanks so much for your help!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: complex data types?

2005-09-18 Thread richard
Gustavo Picon <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> On Sat, 2005-09-17 at 23:34 -0500, Gustavo Picon wrote:
>> Maybe something like this?
>> 
>> class music(object):
>> def __init__(self):
>> self.lst = {}
>> def __setattr__(self, name, value):
>> self.__dict__[name] = value
>> 
>> array = []
>> array.append(music())
>> array.append(music())
>> 
>> # begin quoting your code
>> array[0].artist = 'genesis'
>> array[0].album = 'foxtrot'
>> array[0].songs = ['watcher', 'time table', 'friday']
>> array[1].artist = 'beatles'
>> array[1].album = 'abbey road'
>> array[1].songs = ['come', 'something', 'maxwell']
>> # end quoting your code
>> 
>> print array[0].artist
>> print array[1].artist
>> print array[0].songs
>> print array[1].songs
>> 
> 
> Actually, forget about that music class, all you need in that example
> is:
> 
> class music:
> pass

I like that.  I ended up doing:

array = []

title = 't1'
name = 'n1'
songs = ['s1', 's2']
array.append([title,name,songs])
title = 't2'
name = 'n2'
songs = ['s3', 's4']
array.append([title,name,songs])

Thank you and the other posters for the help.

Must learn not to think in c/c++. Python is much easier - no malloc's 
and pointers to fuss with :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: complex data types?

2005-09-18 Thread richard
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> At the same time, if array[0].songs equals array[1] songs, you are
> probably initializing both array[0] and array[1] with the same object.
> Since array[0] and array[1] both refer to the same object, a change to
> one will be reflected in the other.
> 
> I hope this is what you're looking for.
> 
> Michael Loritsch

I believe that was one of the things I was doing.

thanks 

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 alpha

2005-09-18 Thread D.Hering
Hi Aahz,
Yes thank you. To clarify the cvs dist README listed Python version 2.5
alpha 0. I should have realized before posting that replacing was a bad
idea and another "slot-ed" version could be installed (package manager
already has 2.3.5 & 2.4.1). I just installed 2.5a0 in an alternative
directory (make altinstall) which build and tested out fine. I'm gonna
now attempt to compile the module packages mentioned above. I'll report
how it turns out for anyone interested. Thanks for your help!

Dieter

>Thomas Jollans wrote:
>>D.Hering wrote:
>> under gentoo linux 2.6.

>that does not exist. gentoo labels installers 2005.0 etc, but I have
>never heard of version numbers.
>do you mean gentoo with linux 2.6 ?

Hi Thomas,
Yes, ambiguity/abridgement usage is troublesome at times..lol. Yeah the
iso is 2005.0 and the linux kernal is gentoo sources version 2.6.12.

Dieter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading files with error

2005-09-18 Thread jepler
On Sun, Sep 18, 2005 at 02:15:00PM +1000, Maurice Ling wrote:
> Sorry but what are SEEK_END and SEEK_SET?

Oops, that's what I get for snipping a part of a larger program.

SEEK_SET = 0
SEEK_END = 2

Jeff


pgpC1OTox5VvO.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

How to obtain a 'interactive session' of a script?

2005-09-18 Thread Bo Peng
Dear list,

I have a long list of commands in the form of a script and would like to 
  obtain a log file as if I enter the commands one by one. (The output 
will be used in a tutorial.) What would be the best way to do it? Copy 
and paste is not acceptable since I make frequent changes tot he script.

Many thanks in advance.
Bo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to obtain a 'interactive session' of a script?

2005-09-18 Thread Fredrik Lundh
Bo Peng wrote:

> I have a long list of commands in the form of a script and would like to
>  obtain a log file as if I enter the commands one by one. (The output
> will be used in a tutorial.) What would be the best way to do it? Copy
> and paste is not acceptable since I make frequent changes tot he script.

the first example on this page

http://effbot.org/librarybook/code.htm

shows how to execute Python code line by line.

here's a variation that echoes the script fragments with the right prompts
in front of them:

import code

SCRIPT = [line.rstrip() for line in open("myscript.py")]

script = ""
prompt = ">>>"

for line in SCRIPT:
print prompt, line
script = script + line + "\n"
co = code.compile_command(script, "", "exec")
if co:
# got a complete statement.  execute it!
exec co
script = ""
prompt = ">>>"
else:
prompt = "..."

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to obtain a 'interactive session' of a script?

2005-09-18 Thread jepler
The 'code' module contains 'Utilities needed to emulate Python's interactive
interpreter.'.  By subclassing code.InteractiveConsole and replacing the
raw_input method with one which reads from a file, I think you can get what you
want.

The example below the classes uses StringIO so that it can be self-contained,
but you'll probably use a regular file instead.

import code, sys

class BoPeng(code.InteractiveConsole):
def __init__(self, locals=None, filename="", file = None):
self.file = file or open(filename)
code.InteractiveConsole.__init__(self, locals, filename)

def raw_input(self, prompt):
l = self.file.readline()
if l == '': raise EOFError
sys.stdout.write(prompt + l)
return l.strip("\n")

session = '''\
print 3+3
for i in range(10):
print i

print "Example of a traceback:"
1/0
'''

import StringIO
b = BoPeng(file = StringIO.StringIO(session))
b.interact(None)


pgpfYnuQODMMd.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Doc Problem Example: os.path.split

2005-09-18 Thread Matija Papec
X-Ftn-To: Xah Lee 

"Xah Lee" <[EMAIL PROTECTED]> wrote:
>Python Doc Problem Example

what makes you sure that this problem would be interesting for groups beside
c.l.python? are you begging to be converted to a true religion? :-)


-- 
Matija
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to obtain a 'interactive session' of a script?

2005-09-18 Thread Bo Peng

Thank you for the suggestions and code!

> import code
> 
> SCRIPT = [line.rstrip() for line in open("myscript.py")]
> 
> script = ""
> prompt = ">>>"
> 
> for line in SCRIPT:
> print prompt, line
> script = script + line + "\n"
> co = code.compile_command(script, "", "exec")
> if co:
> # got a complete statement.  execute it!
> exec co
> script = ""
> prompt = ">>>"
> else:
> prompt = "..."
> 

This one fails at function definition.

def fun():
   a=1
   b=2   <--- not included.

Still trying other methods.
Bo
-- 
http://mail.python.org/mailman/listinfo/python-list


How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Alex
Rossum's tutorial on Python states:
"open() returns a file object, and is most commonly used with two
arguments: 'open(filename, mode)'
mode 'r+' opens the file for both reading and writing."

Here's a little session in Python's interactive window

>>> f=open('mytext.txt','w+')
>>> f.write('My name is Bob')
>>> s=f.read()
>>> s.len()
>>> len(s)
4082
>>>f.close()

If I open the file mytext.txt in Notepad I see something that begins
with

"My name is Bob  VwMÚ¸x¶ Ð"

and goes on for approximately 4082 characters.

What's happening??

Alex

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-18 Thread Pedro Werneck
On 18 Sep 2005 00:39:31 -0700
"Michele Simionato" <[EMAIL PROTECTED]> wrote:

> Remember that given a class C, its metaclass is given by C.__class__,
> not by > C.__metaclass__, despite the name.

Of course. Seems you think I'm arguing that C.__class__ and
__metaclass__ should always be the same. The metaclass is given by
C.__class__ after class creation. At the end of the 'class' statement,
searching for the 'winner' metatype, dict["__metaclass__"] is supposed
to have priority over B.__class__, and this over global __metaclass__.
Not only this is the behavior documented on GvR essay but is on the
source code I mentioned too.

> You argue that in this case an error should be raised, since "errors
> should never pass silently". May be. 

Exactly... and the behaviour is inconsistent. I get an exception when
the metaclass is not related to the M_A-M_B hierarchy, like X below, and
the same error was supposed to be raised when using M_A or type, which
do not follow the same rule of being a "subclass of the metaclasses of
all its bases". In fact, I lost a lot of time trying to find an error
related to this in my code a few weeks ago.

>>> class X(type): pass
... 
>>> class C(B): __metaclass__ = X
... 
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a derived class must be a
(non-strict) subclass of the metaclasses of all its bases
>>> class C(B): __metaclass__ = M_A
... 
>>> C.__metaclass__

>>> C.__class__


> You are free to post the bug report and look at the opinions of the
> developers. 

I posted a few hours ago. 

Thank you.

-- 
Pedro Werneck
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python:C++ interfacing. Tool selection recommendations

2005-09-18 Thread Mike Meyer
> (I wonder, by the way, if it's a good idea to provide a very rich interface
> between an application and embedded Python. I have no experience in the
> area, but intuition tells me that simplicity and minimalism is important.
 
So long as you distinguish between minimalist and the bare minimum. My
experience with using and building systems with embedded interpreters
shows that you can never tell what a user will want to do. If you
provide some functionality that can't be invoked from the embedded
python, you can guarantee that some user somewhere will want that
functionality.

So your "minimal" interface should include the ability to do anything
that the application user can do from whatever interface you
provide. That may include functionality that the environment normally
provides for manipulating your application - unless the environment
provides tools for scripting that functionality.

> How well has this worked out in past projects?)

Applications that fail to provide complete functionality have worked
out poorly, usually leaving me frustrated. The most recent example is
Apple's Terminal application in OS X. I want to open a new window,
make it use a font other than the default font, resize the window,
then launch an application in that window passing it an argument from
the command line. This can't be automated because Apple left part of
the functionality out of their scripting interface. As a result, I'm
reduced to using xterm - which has problems of it's own.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to obtain a 'interactive session' of a script?

2005-09-18 Thread Bo Peng
[EMAIL PROTECTED] wrote:
> The 'code' module contains 'Utilities needed to emulate Python's interactive
> interpreter.'.  By subclassing code.InteractiveConsole and replacing the
> raw_input method with one which reads from a file, I think you can get what 
> you
> want.

This method works fine with only one minor problem. It would stop 
(waiting for user input) at help(str) command. I will have to find a way 
to feed the program with'q' etc.

Bo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Roguelike programmers needed

2005-09-18 Thread Thomas Jollans
what exactly is RPG/roguelike etc ? (what debian package provides an 
example?)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shed Skin under Windows and OSX

2005-09-18 Thread A.B., Khalid
Mark Dufour wrote:
> > By the way, I read in your blog that you would be releasing a windows
> > intaller soon.
> > Have you, or anyone else, managed to do it?
>
> I just finished making a 20 MB (!) package for Windows XP (I'm not
> sure which older versions of Windows it will run on.) It includes the
> Boehm garbage collector and a C++ compiler (MingW), which hopefully
> will make it  really easy to create executables. However, I'm not
> releasing it until somebody with XP can test it for me :-) If you'd
> like to try what I have so far,  please download
> http://kascade.org/shedskin-0.0.2.zip, unzip it and follow some simple
> steps in the README file. I would really like to know about anything
> that doesn't work, or is unclear!
>
> BTW, I also fixed all OSX problems, but I'm waiting for a friend to
> give it a final test.
>
> What kind of program would you like to compile?
>
>
> thanks!
> mark.


Here is the very end of a very long output of unit.py run in Python
2.4.1 on WinXP Pro SP2:

[generating c++ code..]
*** compiling & running..
rm test.o test.exe
g++ -O3 -IG:/Downloads/Temp/ss2/shedskin -c test.cpp
g++ -O3 -IG:/Downloads/Temp/ss2/shedskin test.o
G:/Downloads/Temp/ss2/shedskin/libss.a -lgc -o test
output:
[3, 3, 3, 1097, 70201]

*** success: small factorization program by Rohit Krishna Kumar 124
*** no failures, yay!


:)

Well done. So what was causing that crash in test '__class__ and
__name__ attributes' after all?

I'll also try to test it on Win98.

Regards,
Khalid

-- 
http://mail.python.org/mailman/listinfo/python-list


Concurrent access behind an asynchronous server

2005-09-18 Thread Pierre Quentel
Sorry if the question seems naive, but is there a risk of concurrent 
accesses to a database if it is accessed only by scripts called by 
requests to an asynchronous server ?

I have the same question for a server built on the non-threaded version 
of SocketServer.TCPServer

A+
Pierre
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do Pythoneers reinvent the wheel?

2005-09-18 Thread Mike Meyer
Jorgen Grahn <[EMAIL PROTECTED]> writes:
> On Sat, 10 Sep 2005 20:24:32 -0400, François Pinard <[EMAIL PROTECTED]> wrote:
> Yeah. I've often wished for some overview or guide that translates the
> current buzzwords to old concepts I'm familiar with. For example, I'm sure
> you can capture the core ideas of something like .NET in a couple of
> sentences.

Just taking a stab in the dark, since I'm only vaguely familiar with
.NET: P-code for multiple languages?

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Roguelike programmers needed

2005-09-18 Thread Robert Kern
Thomas Jollans wrote:
> what exactly is RPG/roguelike etc ? (what debian package provides an 
> example?)

Google is your friend.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Thomas Jollans
I have no idea what is happening, but to the subject line: I guess it's 
a plain wrapper around fopen fron 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to obtain a 'interactive session' of a script?

2005-09-18 Thread Fredrik Lundh
Bo Peng wrote:

>> import code
>>
>> SCRIPT = [line.rstrip() for line in open("myscript.py")]
>>
>> script = ""
>> prompt = ">>>"
>>
>> for line in SCRIPT:
>> print prompt, line
>> script = script + line + "\n"
>> co = code.compile_command(script, "", "exec")
>> if co:
>> # got a complete statement.  execute it!
>> exec co
>> script = ""
>> prompt = ">>>"
>> else:
>> prompt = "..."
>
> This one fails at function definition.
>
> def fun():
>   a=1
>   b=2   <--- not included.

hmm.  looks like a bug in compile_command.  stripping off the trailing
newline seems to fix it:

co = code.compile_command(script[:-1], "", "exec")

(to make things look right, you need to add an empty line after each
function definition in your code)

 



-- 
http://mail.python.org/mailman/listinfo/python-list


ordering results by column

2005-09-18 Thread leonardburton
Hi,

I posted this ticket https://trac.cakephp.org/ticket/212 and didn't get
a meaningful answer.

How can I order the data by a certain column in an index page?

Thanks,

Leonard

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ordering results by column

2005-09-18 Thread leonardburton
I guess google did something funny to me.  I was trying to post this to
Cake PHP group.  

Thanks,

Leonard

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Fredrik Lundh
"Alex" wrote:

> If I open the file mytext.txt in Notepad I see something that begins
> with
>
> "My name is Bob  VwMÚ¸x¶ Ð"
>
> and goes on for approximately 4082 characters.
>
> What's happening??

you're moving the file pointer around in a new file, and you're getting
junk (from the stdio file buffers, most likely) in the places where you
haven't written anything yourself.

 



-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Steven D'Aprano
On Sun, 18 Sep 2005 09:11:51 -0700, Alex wrote:

> Rossum's tutorial on Python states:
> "open() returns a file object, and is most commonly used with two
> arguments: 'open(filename, mode)'
> mode 'r+' opens the file for both reading and writing."
> 
> Here's a little session in Python's interactive window
> 
 f=open('mytext.txt','w+')
 f.write('My name is Bob')
 s=f.read()
 s.len()
 len(s)
> 4082
f.close()
> 
> If I open the file mytext.txt in Notepad I see something that begins
> with
> 
> "My name is Bob  VwMÚ¸x¶ Ð"
> 
> and goes on for approximately 4082 characters.
> 
> What's happening??

4082 is exactly 14 bytes less than four kilobytes. The string you wrote
to the file is... 14 bytes long. 

Seems to me the file system allocated a 4K block to your file. You wrote
14 bytes to it, which advances the file pointer to byte 14, and then
read to the end of the file, which was filled with whatever random bytes
just happened to be on the disk in that place.

I don't get this behaviour under Linux, so I assume this is
Windows-specific. Under Linux, the new file is created with length 0, and
read() returns the empty string.

Any file has a "physical length" (how many blocks allocated on disk) and a
"logical length" (how many bytes are actually used). You should expect
that any time you create a new file, the initial contents could be
anything until you over-write it. This is not a problem when you create a
new file in ordinary write mode, because you can't read those existing
bytes, and when you close the file, that specifies the end-of-file.

You might find the truncate() method useful:

f=open('mytext.txt','w+')
f.write('My name is Bob')
f.truncate()
s = f.read()
# s should be the empty string -- untested because I'm not running Windows
f.seek(0)
s = f.read()
# s should be "My name is Bob"
f.close()

Hope this helps.


-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 alpha

2005-09-18 Thread D.Hering
So far so good. Numeric-24.0b2, numarray-1.3.3, pytables-1.1.1 (gonna
wait alittle on the scipy install) all built. Tests passed except one
trivial test in numarray but does function:

1 items had failures:
   1 of 1205 in cache pass
***Test Failed*** 1 failures.
File "/usr/local/lib/python2.5/site-packages/numarray/numtest.py", line
3477, in cache pass
Failed example:
try:
   import Numeric
except ImportError:
   pass
else:
   a = arange(5)
   b = Numeric.arange(5)
   c = a + b
Exception raised:
Traceback (most recent call last):
  File "/usr/local/lib/python2.5/doctest.py", line 1243, in __run
compileflags, 1) in test.globs
  File "", line 2, in ?
  File "/usr/local/lib/python2.5/site-packages/Numeric/Numeric.py",
line 358, in ?
from dotblas import dot, innerproduct, vdot
  File
"/usr/local/lib/python2.5/site-packages/numarray/dotblas.py", line 5,
in ?
import generic as _gen
  File
"/usr/local/lib/python2.5/site-packages/numarray/generic.py", line 13,
in ?
import numerictypes as _nt
  File
"/usr/local/lib/python2.5/site-packages/numarray/numerictypes.py", line
168, in ?
Byte = _register("Byte",   Int8)
  File
"/usr/local/lib/python2.5/site-packages/numarray/numerictypes.py", line
68, in _register
raise ValueError("Type %s has already been registered" % name)
ValueError: Type Byte has already been registered

sh-3.00# python2.5
Python 2.5a0 (#1, Sep 18 2005, 10:20:55)
[GCC 3.4.4 (Gentoo 3.4.4, ssp-3.4.4-1.0, pie-8.7.8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numarray as na
>>> import Numeric as nu
>>> a = na.arange(5)
>>> b = nu.arange(5)
>>> c = a+b
>>> c
array([0, 2, 4, 6, 8])
>>>

Anyway, looking forward to now play with the generator functionality
and hoping the installs' continue to perform properly. :^) 

Dieter

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Ksenia Marasanova
18 Sep 2005 09:11:51 -0700, Alex <[EMAIL PROTECTED]>:
> Rossum's tutorial on Python states:

it's "Van Rossum's" :)
"van" in a part of the last name, you can't just cut it away in Dutch :)

-- 
Ksenia
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to obtain a 'interactive session' of a script?

2005-09-18 Thread Fredrik Lundh
Bo Peng wrote:

> This method works fine with only one minor problem. It would stop
> (waiting for user input) at help(str) command. I will have to find a way
> to feed the program with'q' etc.

replacing sys.stdin with something that isn't a TTY will fix this.

here's one way to do it:

class wrapper:
def __init__(self, file):
self.file = file
def isatty(self):
return 0
def __getattr__(self, key):
return getattr(self.file, key)

sys.stdin = wrapper(sys.stdin)

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Postgres PL/Python

2005-09-18 Thread Ksenia Marasanova
Thanks to all, especially to Stuart, for very informative answers.

It's clear to me now that  there is no need in my case to use
functions / stored procedures (yes, with typical MVC app I meant a
webapp on the same server with database, administered by the same
persons). However it can be a useful addition for more complex
situations that may come.

--
Ksenia
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 alpha

2005-09-18 Thread Fredrik Lundh
"D Hering" wrote:

> I just installed 2.5a0

what part of aahz's "There is no Python 2.5 alpha" did you not
understand?

> in an alternative directory (make altinstall) which
> build and tested out fine. I'm gonna now attempt to compile the module
> packages mentioned above. I'll report how it turns out for anyone
> interested.

what makes you think that anyone would be interested in whether
any piece of software works with an unreleased source snapshot?

all you're doing is wasting people's time (including your own).

 



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python game coding

2005-09-18 Thread Alessandro Bottoni
Diez B. Roggisch wrote:

> Diez B. Roggisch wrote:
>> 
>>> Very interesting!
>>> BTW: I wonder if and when someone will use stackless python or pygame
>>> as a
>>> basis for developing a _visual_ development environment for 2D
>>> games/multimedia like Macromedia Director. It would be a killer app.
>> 
>> 
>> Blender. It currently doesn't use stacklass AFAIK, but that shouldn't be
>> too hard to fix.
> 
> Oop - I read 3d instead of 2d.. Hm, 3d _can_ do 2d, so just don't allow
> your cameras do fancy stuff like rotating :)
> 
> Diez

Very interesting, anyway, both in 2D and in 3D. It looks like I have to
study Blender a little bit... :-)

Thanks
---
Alessandro Bottoni
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Alex
Yes the problem seems to be exactly that. I'm moving around the file
pointer. This piece of code works. Observe the only thing I've added is
f.seek(0)

>>> f=open('mytext.txt', 'w+')
>>> f.write('My name is Bob')
>>> f.seek(0)
>>> s=f.read()
>>> print s
My name is Bob
>>> f.close()

I've found this piece of clue at
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_fopen.2c_._wfopen.asp
"However, when you switch between reading and writing, there must be an
intervening fflush, fsetpos, fseek, or rewind operation. The current
position can be specified for the fsetpos or fseek operation, if
desired."

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-18 Thread Simon Percivall
If you have read the document I referred you to, did you also read the
example where classes M1, M2, M3 and M4 were defined?

A quote from the discussion of that example:
"For class D, the explicit metaclass M1 is not a subclass of the base
metaclasses (M2, M3), but choosing M3 satisfies the constraint, so
D.__class__ is M3."

Isn't that exactly what you are doing?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How does f=open('mytext.txt', 'w+') work?

2005-09-18 Thread Alex
Thanks Steven, very good explaination. f.seek(0) does the trick!
Alex

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Roguelike programmers needed

2005-09-18 Thread rpgnethack
Robert Kern wrote:
>
> Google is your friend.
>


True, that :-)

But what the heck. The average roguelike is a hack 'n' slash computer
game based on tabletop roleplaying games, most often Dungeons and
Dragons. The graphics in most roguelikes have stayed the same since the
70's (i.e. ASCII text) when the grand-daddy of all roguelikes, Rogue,
was born. Most roguelikes are completely open-source.

The most popular roguelikes are Angband (
http://thangorodrim.angband.org ) and Nethack ( http://www.nethack.org
). There are literally dozens of others--some variants, some
original--but listing them here would take too much time.

Don't be fooled by their apparent simplicity! What most roguelikes lack
in graphics they make up for in game play. These suckers are addictive.
You have been warned!

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to obtain a 'interactive session' of a script?

2005-09-18 Thread Bo Peng
Fredrik Lundh wrote:
> replacing sys.stdin with something that isn't a TTY will fix this.

This works like magic! Thank you!

Bo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-18 Thread Pedro Werneck
On 18 Sep 2005 10:33:11 -0700
"Simon Percivall" <[EMAIL PROTECTED]> wrote:

> Isn't that exactly what you are doing?

Yes, and that example has the same inconsistency. 

>>> class X(type): pass
... 
>>> class D2(C3, C2): __metaclass__ = X
... 
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: Error when calling the metaclass bases

For class D2, the explicit metaclass X is not a subclass of the base
metaclasses, just like M1 with D in the example, but with X you get a
metaclass conflict error, and with M1 doesn't. Choosing M3 satisfies the
constraint, but why it is choosen when you use M1 but not with X ?

That's exactly my point. If I wanted M3 or M2, I would be using an
explicit dict['__metaclass__'] = M3 or M2. Since I am trying to do it
with M1, which does not satisfy the constraint, it is an error, and
according to Python design concepts it was supposed to raise the same
exception. 

I don't know if it was a deliberate decision to go silently for the base
class metaclass if the explicit metaclass does not satisfy the
constraint but is a base class of any of the base classes metaclass, but
if it was, the same should happen when the explicit metaclass has no
relation to the base classes metaclass, which seems a very strange
design decision, and not only from Python "explicity and simplicity"
standpoint.

If this is really not an error, just a documentation issue like Mr.
Simionato argues, the first rule for determining M a few lines above
your quote is much more complex and should be changed from:

* if dict['__metaclass__'] exists, it is used.

to something more like:

* if dict['__metaclass__'] exists and is equal to, or a subclass of,
each of the metaclasses of the bases, it is used; if it exists and is a
base class of any of the metaclasses of the bases, the first base class
metaclass is used. If it exists and doesn't satisfies any of these
constraints, TypeError is raised.

If I am right and this is a bug, althought I am not very familiar with
Python internals my speculations on what may be wrong are on the bug
report I filled yesterday. If it's not a bug and this was the intended
behaviour, I think it's not consistent with Python design concepts,
especially "errors should never pass silently" and "explicit is better
than implicit". If it's just a documentation issue, the first rule in
search order is much more complex than documented. If I am completely
wrong in all of this, maybe it's better stop wasting our time. :)


Thank you

-- 
Pedro Werneck

http://sourceforge.net/tracker/index.php?func=detail&aid=1294232&group_id=5470&atid=105470
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Doc Problem Example: os.path.split

2005-09-18 Thread Bruno Desthuilliers
Laszlo Zsolt Nagy a écrit :
> 
>> is the doc writer, trying to write the doc with some austereness, but
>> is confused about the behavior of split, or confused about expressing
>> it? Did his pretension fucked him up?
>>  
>>
> Dear Xah Lee,
> 
> The Python community is very sorry because we have a very bad 
> documentation. You are right. The documentation is bad, and the language 
> is bad etc. The mailing list itself is not helpful and you cannot use it 
> for anything. We will try to follow all of your glorious suggestions.  
> But we have so many things to do, I'm affraid you need to wait until 
> Python 5000 is released. Until that, I can recommend you the Visual 
> Basic language. Its documentation is much more perfect. MSDN is really 
> really well structured and easy to use! It is commercial, and - as you 
> would expect - you will get immediate fixes after you make a kind 
> suggestion like this. I think this is the best thing you can do.
> 
> For more information about this fabolous  ClosedSource commercial 
> product, please visit this link:
> 
> http://msdn.microsoft.com/vbasic/
> 
> Good Luck!
> 
>   Les
> 
KEYBOARD !
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-18 Thread Simon Percivall
I definitely think that it's the intended behaviour: the example shows
how and why it works; and I definitely agree that it should be
documented better.

-- 
http://mail.python.org/mailman/listinfo/python-list


Creating a list of Mondays for a year

2005-09-18 Thread Chris
Is there a way to make python create a list of Mondays for a given year?

For example,

mondays = ['1/3/2005','1/10/2005','1/17/2005','1/24/2005',
'1/31/2005','2/7/2005',   ... ]

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Shed Skin under Windows and OSX

2005-09-18 Thread Mark Dufour
> *** success: small factorization program by Rohit Krishna Kumar 124
> *** no failures, yay!
> 
> 
> :)
>
> Well done. So what was causing that crash in test '__class__ and
> __name__ attributes' after all?

Well, I did something like this:

class_ c(..);
class_ *cp = &c;

class list {
list() {  
this->class = cp;
}
}

constant_list = new list(..);

Now, depending on the order of things, I think this->class became
somewhat undefined. In any case, putting all initializations in the
right order in an initialization function called from main() fixed the
problem.

The problem with test 85 was that it should not actually be passed to
g++, since it is indeed incorrect code :-) However, because of some
bug in unit.py, on sys.platform 'win32' g++ would always be called.

Thanks again for your help. Your Makefile made it very easy for me to
create a Windows package. I'm glad to learn about Mingw too.. very
nice.

> I'll also try to test it on Win98.

I think you said the GC wouldn't work in this case..? Anyway, I've had
my share of Windows for a while.. I would be really glad if somebody
else could look into this.. :)

Have you tried compiling any code of your own yet..?


thanks!
mark.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a list of Mondays for a year

2005-09-18 Thread skip

Chris> Is there a way to make python create a list of Mondays for a
Chris> given year?  For example,

Chris> mondays = ['1/3/2005','1/10/2005','1/17/2005','1/24/2005',
Chris> '1/31/2005','2/7/2005',   ... ]

How about:

import datetime

oneday = datetime.timedelta(days=1)
oneweek = datetime.timedelta(days=7)

year = 2005

start = datetime.date(year=year, month=1, day=1)
while start.weekday() != 0:
start += oneday

days = []
while start.year == year:
days.append(start)
start += oneweek

print days

Skip
-- 
http://mail.python.org/mailman/listinfo/python-list


Best Encryption for Python Client/Server

2005-09-18 Thread Ed Hotchkiss
Let us say that I am trying to create a very small and simple private network/connection between several scripts on different machines, to communicate instructions/data/files etc. to each other over the net. Is SSL the best method? Any recommendations of something to get started with? Thanks in advance.
-- Edward hotchkiss 
-- 
http://mail.python.org/mailman/listinfo/python-list

Best Encryption for Python Client/Server

2005-09-18 Thread Ed Hotchkiss
Let us say that I am trying to create a very small and simple private network/connection between several scripts on different machines, to communicate instructions/data/files etc. to each other over the net. Is SSL the best method? Any recommendations of something to get started with? Thanks in advance. 
-- edward hotchkiss 
-- 
http://mail.python.org/mailman/listinfo/python-list

[no subject]

2005-09-18 Thread Ed Hotchkiss
Let us say that I am trying to create a very small and simple private network/connection between several scripts on different machines, to communicate instructions/data/files etc. to each other over the net. Is SSL the best method? Any recommendations of something to get started with? Thanks in advance. 
-- edward hotchkiss 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Doc Problem Example: os.path.split

2005-09-18 Thread Julian Fondren
> Please don't feed the trolls.

> In other words, if everybody ignores this loser, he might crawl back under
> the rock he came from.

Well, comp.lang.python people would do better to accept the suggested
rewrite and ignore at the rest at their discretion.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a list of Mondays for a year

2005-09-18 Thread Peter Hansen
Chris wrote:
> Is there a way to make python create a list of Mondays for a given year?
> 
> For example,
> 
> mondays = ['1/3/2005','1/10/2005','1/17/2005','1/24/2005',
> '1/31/2005','2/7/2005',   ... ]

from datetime import date, timedelta

def mondays(year):
 '''generate all days that are Mondays in the given year'''
 jan1 = date(year, 1, 1)

 # find first Monday (which could be this day)
 monday = jan1 + timedelta(days=(7-jan1.weekday()) % 7)

 while 1:
 if monday.year != year:
 break
 yield monday
 monday += timedelta(days=7)

 >>> [str(x) for x in mondays(2005)]
['2004-01-05', '2004-01-12', ... '2004-12-27']

Extension to support any day of the week (including renaming the 
function!) is left as an exercise to the reader. ;-)

--
Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Roguelike programmers needed

2005-09-18 Thread en.karpachov
On Sun, 18 Sep 2005 17:28:30 +0100
Thomas Jollans wrote:

> what exactly is RPG/roguelike etc ? (what debian package provides an 
> example?)

apt-cache search roguelike

-- 
jk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Doc Problem Example: os.path.split

2005-09-18 Thread George Sakkis
Another epileptic seizure on the keyboard. Apart from clue deficit
disorder, this guy seems to suffer from some serious anger management
problems...*plonk*


"Xah Lee" <[EMAIL PROTECTED]> wrote:
> Python Doc Problem Example
>
> Quote from:
> http://docs.python.org/lib/module-os.path.html
> --
> split(  path)
> Split the pathname path into a pair, (head, tail) where tail is the
> last pathname component and head is everything leading up to that. The
> tail part will never contain a slash; if path ends in a slash, tail
> will be empty. If there is no slash in path, head will be empty. If
> path is empty, both head and tail are empty. Trailing slashes are
> stripped from head unless it is the root (one or more slashes only). In
> nearly all cases, join(head, tail) equals path (the only exception
> being when there were multiple slashes separating head from tail).
> --
>
> Can anyone tell me what this verbiage is trying to fucking say?
>
> what the fuck is with the head and tail thing?
>
> is the doc writer, trying to write the doc with some austereness, but
> is confused about the behavior of split, or confused about expressing
> it? Did his pretension fucked him up?
>
> i was working on a program where i needed to split a path into dirname,
> corename, and suffix. But this fucking python doc diverted my work and
> wasted my time. It normally isn't a problem to find imperfections in
> the world except the fucking OpenSourcers fuck with their fucking
> moronicity and moronitude and propagate haughtily their fucking lies
> and stupidity. Die.
>
> Suggested rewrite:
>
> split(path)
> returns a pair (dirname,filename), where dirname is the part of path
> up to the last slash, and filename is the rest of the string after the
> last slash.
>
> Exceptional cases are:
> · if path is a single slash (or repeated), then path == dirname and
> filename is empty.
> · If the "last" slash is repeated, they are treated as one single
> slash.
>
> 
> Fuck the motherfucking liers of OpenSourcing fuckheads.
> (Note: my use of OpenSource here does not include people of GNU
> community.)
>
> For more about Python Doc problems, see
> http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html
> 
>  Xah
>  [EMAIL PROTECTED]
> ? http://xahlee.org/
>

-- 
http://mail.python.org/mailman/listinfo/python-list


tuples and mysqldb tables

2005-09-18 Thread Ed Hotchkiss
I have used fetchall() to insert the values from a table into a tuple. anywhere from 0 - ? many rows could be in this tuple, so it is a row within a row. How do I use a loops to iterate through the nested tuple, and assign the tuples integers and strings to variables, ugh :P

 
The Tables data is like this: 
 
+-+
|    ID (INT)  |   Protocol (TEXT)  |  Name (LONGTEXT)  Description (LONGTEXT) |   
+-+
 
 

 
import MySQLdb
import sys
 
# find out what this ports function is 
def grabPortInfo(port):
try:
conn=MySQLdb.connect( host="www.freesql.org",
user="portnumbers",
port=3306,
passwd="*",
db="portnumbers")
except MySQLdb.Error, e: 
print "Error %d: %s" % (e.args[0], e.args[1]) 
print "\n\n WTF!? - portnumbers MySQL DB didn't open"
sys.exit (1)
# --
cursor = conn.cursor()
stmt = "SELECT * FROM portnumbers WHERE port=%i" %port
cursor.execute(stmt)
numrows = int(cursor.rowcount)
if numrows == 0:
print "port # not found in database"
elif numrows >= 1:
result = cursor.fetchall()
print len(result)
# break tuple into strings with output 
myPort = port
myProtocol = result[0|3]
myName = result[0|4]
myDescription = result[0|5]
print "PORT # | PROTOCOL | PORT NAME | PORT DESCRIPTION "
print myPort, myProtocol, myName, myDescription
cursor.close()
conn.close()
# end function -
 
grabPortInfo(22)
 
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Roguelike programmers needed

2005-09-18 Thread Michael Sparks
Robert Kern wrote:

> Thomas Jollans wrote:
>> what exactly is RPG/roguelike etc ? (what debian package provides an
>> example?)
> 
> Google is your friend.

Often a fair answer, but I'd suggest that the question was fair, especially
given the OP was seeking help :-)

After all, I read the subject line and simply assumed they were after
programmers with roguish qualities. Perhaps to work in the newly formed IT
division of the Crimson Permanent Assurance Company. After all, don't
forget - #It's Fun to Charter, and Accountant...#

;-)


Michael.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a list of Mondays for a year

2005-09-18 Thread George Sakkis
"Chris" <[EMAIL PROTECTED]> wrote:

> Is there a way to make python create a list of Mondays for a given year?
>
> For example,
>
> mondays = ['1/3/2005','1/10/2005','1/17/2005','1/24/2005',
> '1/31/2005','2/7/2005',   ... ]

Get the dateutil package (https://moin.conectiva.com.br/DateUtil):

import dateutil.rrule as rrule
from datetime import date

mondays2005 = tuple(rrule.rrule(rrule.WEEKLY,
dtstart=date(2005,1,1),
count=52,
byweekday=rrule.MO))

George

-- 
http://mail.python.org/mailman/listinfo/python-list


Synchronous/Asynchrnous Audio play with pymedia

2005-09-18 Thread Ron Provost
Hello,

I'm developing a piece of software to assist illiteraate adults to learn to 
read.  I'm trying to figure out how, if possible, to make audio playback 
asynchrnous but still controllable.  I'm using python 2.4 with pymedia on 
XP.  I started out with the example in the tutorials section of the pymedia 
website.  The pymedia docs imply to me that playback using Output's play() 
method should already be asynchronous and controllable.  I judge this 
because of the presence of the pause() and unpause() methods.  However, when 
I run the example I find that play() in fact is not returning until an 
entire frame has been played through the sound card.  This isn't entirely a 
problem since the frames are small, but I would prefer to give the entire 
sound file to the class and let it go on playing while I continue with other 
processing.  If, at some point during playback, I wish to pause, unpause or 
completely stop playback, I would like, again, to be able to make 
asynchronous calls to do so.  Doe anybody know if this is possible?  Am I 
using pymedia incorrectly?

I've attempted to construct a threaded class to handle my problem, but I'm a 
novice with threads and It's not working properly.  To use this class, first 
make an instance.  To assign an mp3 file for playback use myInst.select( 
myFileObj ).  To begin playback or to unpause use:  myInst.play( ).  to 
pause use:  myInst.pause( ).  to stop use:  myInst.stop( ).  Once stopped, 
myInst.play( ) should restart playback from the beginning.  The problem is 
that when I stop(), restarting with play() doesn't work.  Instead, the 
thread silently terminates.

Thanks for any help you can offer.  I've been trying to solve this on my own 
for days now and just know it shouldn't be this hard.




import time
import pymedia.audio.sound as sound
import pymedia.audio.acodec as acodec
import threading, Queue

class AudioPlayer( threading.Thread ):
   # States
   PLAY  =1
   PAUSE =2
   STOP  =3

   def __init__( self ):
  threading.Thread.__init__( self )

  self.setDaemon( 1 )
  self.requestQueue  = Queue.Queue( )
  self.start( )

   def select( self, filelikeObj ):
  self.requestQueue.put( filelikeObj )

   def play( self ):
  self.requestQueue.put( AudioPlayer.PLAY )

   def pause( self ):
  self.requestQueue.put( AudioPlayer.PAUSE )

   def stop( self ):
  self.requestQueue.put( AudioPlayer.STOP )

   def run( self ):
  state = AudioPlayer.STOP
  file  = None
  snd   = None

  while True:
 if (state == AudioPlayer.PLAY) and self.requestQueue.empty( ):
if not snd:
   cparams= { 'id': acodec.getCodecID( 'mp3' ) }
   codec = acodec.Decoder( cparams )
   file.seek( 0 )
   bytes = file.read( 8192 )
   frame = codec.decode( bytes )
   snd = sound.Output( frame.sample_rate, frame.channels, 
sound.AFMT_S16_LE )
else:
   bytes = file.read( 512 )
   if len(bytes) > 0:
  frame = codec.decode( bytes )

if frame:
   snd.play( frame.data )
else:
   if snd:
  snd.stop( )
   snd   = None
   state = AudioPlayer.STOP
 else:
msg = self.requestQueue.get( )

if msg in ( AudioPlayer.PAUSE, AudioPlayer.PLAY ):
   state = msg
else:
   if snd:
  snd.stop( )
   snd   = None
   state = AudioPlayer.STOP
   if msg != AudioPlayer.STOP:
  file = msg

# Test application
if __name__ == '__main__':
   import time
   player = AudioPlayer( )
   snd = open( 'music.mp3', 'rb' )
   player.select( snd )
   player.play( )
   time.sleep( 3 )

   player.pause( )
   time.sleep( 3 )
   player.play( )
   time.sleep( 10 )
   player.stop( )
   time.sleep( 3 )
   player.play( )
 


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a list of Mondays for a year

2005-09-18 Thread [EMAIL PROTECTED]
Consider also dateutil written by Gustavo Niemeyer
and found at:
https://moin.conectiva.com.br/DateUtil

>>> from dateutil.rrule import *
>>> list(rrule(WEEKLY, byweekday=MO, dtstart=date(2005,1,1), 
>>> until=date(2005,12,31)))

The library may be a little intimidating at first it is worth learning.

waldek

-- 
http://mail.python.org/mailman/listinfo/python-list


How am I doing?

2005-09-18 Thread Jason
Please don't laugh, this is my FIRST Python script where I haven't 
looked at the manual for help...

import string
import random

class hiScores:
 
hiScores=['1Alpha','07500Beta','05000Gamma','02500Delta','0Epsilon']

 def showScores(self):
 for entry in self.hiScores:
 print entry[0:5]," - ",entry[5:]

 def addScore(self,score,name):
 newScore=string.zfill(score,5)
 self.hiScores.append(newScore+name)
 self.hiScores.sort(reverse=True)

 if len(self.hiScores)==6:
 del self.hiScores[-1]

a=hiScores()
print "Original Scores\n---"
a.showScores()

while 1:
 newScore=random.randint(0,1)
 if string.zfill(newScore,5)>a.hiScores[4][0:5]:
 print "Congratulations, you scored %d " % newScore
 name=raw_input("Please enter your name :")
 a.addScore(newScore,name)
 a.showScores()
 continue

Anything I could have done differently or any "bad-habits" you think I 
have which could lead to ultimate doom I really appreciate to know.

TIA

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Roguelike programmers needed

2005-09-18 Thread Mike Meyer
[EMAIL PROTECTED] writes:
> Don't be fooled by their apparent simplicity! What most roguelikes lack
> in graphics they make up for in game play. These suckers are addictive.
> You have been warned!

And *portable*. I was delighted to discover a port of the original
rogue to the Palm. Then shocked to realize that my (old, obsolete)
Palm had four times as much RAM as the 11/70 I originally ran Rogue
on. And probably an equal overabundance of mips.

Which leads to the inevitable question: how many 370 acres can I fit
in my pocket?

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Announce: open 0.2 - a unix application launcherr

2005-09-18 Thread Mike Meyer
"open" is designed to provide Unix users with a single tool for
dealing with the multitude of applications that deal with data files.
Without open - or something like it - every time a user wants to look
at a file, they have to figure out what type the file is and which
application on their path can open that file, and then invoke that
application with the appropriate arguments. Likewise, every
application that uses external applications has it's own database of
file types and applications. Applications developers have to choose a
format for the database, write code to parse it, and provide a GUI for
editing it.  This not only represents a duplication of effort, but
requires the user to tell every application how to deal with each type
of file, meaning they have to learn multiple different tools for
dealing with this information.

"open" was designed to solve these problems. If the user wants to open
a file, they just invoke "open" on it. To edit it, they just invoke
"open -c edit" (or "edit" if they've installed it that way). Open will
figure out which application they want to use for this, and arrange
that it gets called appropriately. If open can't find an application,
it'll ask the user to choose one, and save that choice for future
reference.  For applications, open provides an API that takes care of
the entire problem. There's no need to parse a configuration file,
provide facilities for editing the configuration file, ensure the
consistency of the configuration file, or any such thing. The
application merely hands the file name to "open", and "open" does the
rest. Further, the API is one that any program that has to deal with
external applications already deals with - launching an external
application on a file. So users can start getting the benefit of using
"open" even if none of the applications they have installed know about
it - all they have to do is tell each application to use "open" for
everything. Hopefully, applications will start checking for and using
"open" as an external viewer by default, removing even that burden
from the user.

The benefits to the user are multifold. They only have to learn one
interface for configuring the invocation of external programs. If they
install a new foo viewer, and decide they want to use that for viewing
foos everywhere, they only have to change it in one place - the "open"
database. Users can quit worrying about "What application opens this
file" at the command line. Well, most of the time. Instead, they just
do "open ", and let open sort it out.

It's not got it's own web page yet - and little or no
documentation. Download the tarball from
http://www.mired.org/downloads/open-0.2.tar.gz >

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-18 Thread Pedro Werneck
On 18 Sep 2005 12:58:22 -0700
"Simon Percivall" <[EMAIL PROTECTED]> wrote:

> I definitely think that it's the intended behaviour: the example shows
> how and why it works; and I definitely agree that it should be
> documented better.

Yes. I finally understood the decision and now I agree it's not a bug,
it's the intended behaviour. If the explicit class is part of the
hierarchy but not a subclass of base classes metaclass, it will search
for the more specialized metaclass and use it, since it will have
anything the class need and conforms to the metaclass I set explicitly.

I will change the bug report and add some of the suggested
documentation.

Thanks
-- 
Pedro Werneck
-- 
http://mail.python.org/mailman/listinfo/python-list


Question About Logic In Python

2005-09-18 Thread James H.
Greetings!  I'm new to Python and am struggling a little with "and" and
"or" logic in Python.  Since Python always ends up returning a value
and this is a little different from C, the language I understand best
(i.e. C returns non-zero as true, and zero as false), is there anything
I should be aware of given Python's different approach?  Namely any
pitfalls or neat tricks that make the Python approach cool or save my
butt.

Thank you!

James

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a list of Mondays for a year

2005-09-18 Thread Peter Hansen
George Sakkis wrote:
> "Chris" <[EMAIL PROTECTED]> wrote:
>>Is there a way to make python create a list of Mondays for a given year?
> 
> Get the dateutil package (https://moin.conectiva.com.br/DateUtil):
> 
> import dateutil.rrule as rrule
> from datetime import date
> 
> mondays2005 = tuple(rrule.rrule(rrule.WEEKLY,
> dtstart=date(2005,1,1),
> count=52,
> byweekday=rrule.MO))

Count should probably be at least "53" to catch the years when there are 
that many Mondays such as 2001.  Unfortunately, I suspect that will 
screw it up for other years where there are only 52 (but I don't know 
this dateutil package so someone who does would have to say for sure).

-Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a list of Mondays for a year

2005-09-18 Thread Paul Rubin
Chris <[EMAIL PROTECTED]> writes:
> Is there a way to make python create a list of Mondays for a given year?
> mondays = ['1/3/2005','1/10/2005','1/17/2005','1/24/2005',
> '1/31/2005','2/7/2005',   ... ]

This is pretty inefficient but it's conceptually the simplest:

def mondays(year):
from calendar import weekday, monthrange
return [('%d/%d/%d'%(month,day,year))
 for month in xrange(1,13)
   for day in xrange(1,1+monthrange(year,month)[1])
 if weekday(year,month,day) == 0]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question About Logic In Python

2005-09-18 Thread Dan Bishop
James H. wrote:
> Greetings!  I'm new to Python and am struggling a little with "and" and
> "or" logic in Python.  Since Python always ends up returning a value
> and this is a little different from C, the language I understand best
> (i.e. C returns non-zero as true, and zero as false), is there anything
> I should be aware of given Python's different approach?  Namely any
> pitfalls or neat tricks that make the Python approach cool or save my
> butt.

The most common use of this feature is "x = x or default_val" as a
shorthand for "if not x: x = default_val".

Also, you can emulate C's ternary operator (cond ? t : f) with
(cond and [t] or [f])[0].

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How am I doing?

2005-09-18 Thread George Sakkis
"Jason" <[EMAIL PROTECTED]> wrote:

> Please don't laugh, this is my FIRST Python script where I haven't
> looked at the manual for help...

Sooner or later you should ;)

> import string

Don't need it it modern python; use string methods instead.

> import random
>
> class hiScores:

The common convention is to use Capitalized words for classes, e.g.
HiScores.

> hiScores=['1Alpha','07500Beta','05000Gamma','02500Delta','0Epsilon']

hiScores should better be given as parameter when an instance is made,
not hardcoded as a class instance. Also, it is better to separate the
score from the name. Then hiScores can be, say, a list of (score,name)
tuples, e.g. [('1', 'Alpha'), ('07500', 'Beta'), ..., ('0',
'Epsilon')]:

def __init__(self, hiScores):
self.hiScores = [(entry[:5], entry[5:]) for entry in hiScores]

>  def showScores(self):
>  for entry in self.hiScores:
>  print entry[0:5]," - ",entry[5:]

If you separate the score from the name in the constructor, you don't
have to split the entries every time showScores is called:
def showScores(self):
  for score,name in self.hiScores:
  print score, " - ", name

You can express the same more compactly using string interpolation:
def showScores(self):
  for entry in self.hiScores:
  print "%s - %s" % entry

>  def addScore(self,score,name):
>  newScore=string.zfill(score,5)
>  self.hiScores.append(newScore+name)
>  self.hiScores.sort(reverse=True)

If you add one entry at a time, it is more efficient to keep the list
sorted and use the bisect.insort function instead of sorting the whole
list:

bisect.insort(self.hiScores, (newScore,name))

>  if len(self.hiScores)==6:

With your given hiScores, this test is useless; you started with 5
entries and added one so you know there are 6 now. In the more general
case, sort the initial hiScores in the constructor and take the top 5
entries.

>  del self.hiScores[-1]

You can also remove the last element of a list by self.hiScores.pop()

> a=hiScores()
> print "Original Scores\n---"
> a.showScores()
>
> while 1:
>  newScore=random.randint(0,1)
>  if string.zfill(newScore,5)>a.hiScores[4][0:5]:

Two things:
- string.zfill(newScore,5) is better written as newScore.zfill(5)
- a.hiScores[4][0:5] is cryptic; it is better to write a method to give
you the last score so that you can spell it as a.lastScore():

def lastScore(self):
return a.hiScores[-1][0] # assuming (score,name) entries

>  print "Congratulations, you scored %d " % newScore
>  name=raw_input("Please enter your name :")
>  a.addScore(newScore,name)
>  a.showScores()
>  continue

"continue" doesn't do anything at the line you put it. When do you want
your program to exit ? As it is, it will loop forever.

> Anything I could have done differently or any "bad-habits" you think I
> have which could lead to ultimate doom I really appreciate to know.
> 
> TIA

HTH,
George

-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Roguelike programmers needed

2005-09-18 Thread Delaney, Timothy (Tim)
Mike Meyer wrote:

> And *portable*. I was delighted to discover a port of the original
> rogue to the Palm. Then shocked to realize that my (old, obsolete)
> Palm had four times as much RAM as the 11/70 I originally ran Rogue
> on. And probably an equal overabundance of mips.

I actually started on a port of Moria once, but never got around to
being really serious on it. And then of course my palm pilot shorted out
its capacitor and wouldn't hold enough charge to retain anything while
changing batteries, and ended up as a universal remote control for a
couple of years before finally being decommissioned ...

Tim Delaney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a list of Mondays for a year

2005-09-18 Thread George Sakkis
"Peter Hansen" <[EMAIL PROTECTED]> wrote:

> George Sakkis wrote:
> > "Chris" <[EMAIL PROTECTED]> wrote:
> >>Is there a way to make python create a list of Mondays for a given year?
> >
> > Get the dateutil package (https://moin.conectiva.com.br/DateUtil):
> >
> > import dateutil.rrule as rrule
> > from datetime import date
> >
> > mondays2005 = tuple(rrule.rrule(rrule.WEEKLY,
> > dtstart=date(2005,1,1),
> > count=52,
> > byweekday=rrule.MO))
>
> Count should probably be at least "53" to catch the years when there are
> that many Mondays such as 2001.  Unfortunately, I suspect that will
> screw it up for other years where there are only 52 (but I don't know
> this dateutil package so someone who does would have to say for sure).
>
> -Peter

Sorry, my bad; waldek in the post below got it right. Here's yet
another way that doesn't use the count or until keywords:

>>> from itertools import takewhile
>>> mondays2001 = tuple(takewhile(lambda d: d.year==2001,
  rrule.rrule(rrule.WEEKLY,
  dtstart=date(2001,1,1),
  byweekday=rrule.MO)))
>>> print len(mondays2001)
53

George

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How am I doing?

2005-09-18 Thread Jason
George Sakkis wrote:
> "Jason" <[EMAIL PROTECTED]> wrote:
> 
>> Please don't laugh, this is my FIRST Python script where I haven't
>> looked at the manual for help...
> 
> Sooner or later you should ;)
> 
>> import string
> 
> Don't need it it modern python; use string methods instead.
> 
>> import random
>>
>> class hiScores:
> 
> The common convention is to use Capitalized words for classes, e.g.
> HiScores.
> 
>> hiScores=['1Alpha','07500Beta','05000Gamma','02500Delta','0Epsilon']
> 
> hiScores should better be given as parameter when an instance is made,
> not hardcoded as a class instance. Also, it is better to separate the
> score from the name. Then hiScores can be, say, a list of (score,name)
> tuples, e.g. [('1', 'Alpha'), ('07500', 'Beta'), ..., ('0',
> 'Epsilon')]:
> 
> def __init__(self, hiScores):
> self.hiScores = [(entry[:5], entry[5:]) for entry in hiScores]
> 
>>  def showScores(self):
>>  for entry in self.hiScores:
>>  print entry[0:5]," - ",entry[5:]
> 
> If you separate the score from the name in the constructor, you don't
> have to split the entries every time showScores is called:
> def showScores(self):
>   for score,name in self.hiScores:
>   print score, " - ", name
> 
> You can express the same more compactly using string interpolation:
> def showScores(self):
>   for entry in self.hiScores:
>   print "%s - %s" % entry
> 
>>  def addScore(self,score,name):
>>  newScore=string.zfill(score,5)
>>  self.hiScores.append(newScore+name)
>>  self.hiScores.sort(reverse=True)
> 
> If you add one entry at a time, it is more efficient to keep the list
> sorted and use the bisect.insort function instead of sorting the whole
> list:
> 
> bisect.insort(self.hiScores, (newScore,name))
> 
>>  if len(self.hiScores)==6:
> 
> With your given hiScores, this test is useless; you started with 5
> entries and added one so you know there are 6 now. In the more general
> case, sort the initial hiScores in the constructor and take the top 5
> entries.
> 
>>  del self.hiScores[-1]
> 
> You can also remove the last element of a list by self.hiScores.pop()
> 
>> a=hiScores()
>> print "Original Scores\n---"
>> a.showScores()
>>
>> while 1:
>>  newScore=random.randint(0,1)
>>  if string.zfill(newScore,5)>a.hiScores[4][0:5]:
> 
> Two things:
> - string.zfill(newScore,5) is better written as newScore.zfill(5)
> - a.hiScores[4][0:5] is cryptic; it is better to write a method to give
> you the last score so that you can spell it as a.lastScore():
> 
> def lastScore(self):
> return a.hiScores[-1][0] # assuming (score,name) entries
> 
>>  print "Congratulations, you scored %d " % newScore
>>  name=raw_input("Please enter your name :")
>>  a.addScore(newScore,name)
>>  a.showScores()
>>  continue
> 
> "continue" doesn't do anything at the line you put it. When do you want
> your program to exit ? As it is, it will loop forever.
> 
>> Anything I could have done differently or any "bad-habits" you think I
>> have which could lead to ultimate doom I really appreciate to know.
>>
>> TIA
> 
> HTH,
> George
> 
LOL - O dear!!

Well I can certainly see a lot of better methods that you've pointed out 
George.  For one thing, I was 'wanting' to go down the tuples or 
dictionary mode but was under the impression you couldn't sort them 
directly.  From what I understand, you can't, but the example you have 
shown clearly makes sense and a hell-of-alot more practical.

Never knew about the Pop command!!

Thanks again for the help though, really appreciate it.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question About Logic In Python

2005-09-18 Thread [EMAIL PROTECTED]

James H. wrote:
> Greetings!  I'm new to Python and am struggling a little with "and" and
> "or" logic in Python.  Since Python always ends up returning a value
> and this is a little different from C, the language I understand best
> (i.e. C returns non-zero as true, and zero as false), is there anything
> I should be aware of given Python's different approach?  Namely any
> pitfalls or neat tricks that make the Python approach cool or save my
> butt.
>
> Thank you!
>
> James

Booleans are a subtype of plain integers, so if you use them
in arithmetic expressions, they evaluate to 0 and 1.

>>> def bool():
print "Boolean algebra"
print "%9s %9s | %9s %9s %9s" % ('A','B','A and B','A or B','A xor B')
print "-"*51
for a in [False,True]:
for b in [False,True]:
print "%9s %9s | %9s %9s %9s"  % (a,b,(a and b),(a or 
b),((a and not
b) or (not a and b)))
print
print
print "Arithmetic"
print "%9s %9s | %9s %9s %9s" % ('A','B','A + B','A * B','A - B')
print "-"*51
for a in [False,True]:
for b in [False,True]:
print "%9s %9s | %9s %9s %9s"  % (a,b,(a + b),(a * 
b),(a - b))


>>> bool()
Boolean algebra
A B |   A and BA or B   A xor B
---
False False | False False False
False  True | False  True  True
 True False | False  True  True
 True  True |  True  True False


Arithmetic
A B | A + B A * B A - B
---
False False | 0 0 0
False  True | 1 0-1
 True False | 1 0 1
 True  True | 2 1 0

-- 
http://mail.python.org/mailman/listinfo/python-list


Why is map() preferable in this case?

2005-09-18 Thread Ray
Hello,

I'm just reading the latest edition of Python Cookbook, where it says
in Recipe 4.2:

"when the op you wanna perform on each item is to call a function on
the item and use the function's result, use L1 = map(f, L), rather than
L1 = (f(x) for x in L)"

What is wrong with the generator expression (or maybe it is list
comprehension, I cannot remember now whether they used [] or () in the
book)? Is it for clarity? I'm a newbie, and to me, the
generator/comprehension looks _way_ more clearer than map(f, L).

Are there any performance/memory requirements I'm not aware of? Why
would one want to use map() when there's already an expression that is
so clear and easy to understand?

Thanks!
Ray

-- 
http://mail.python.org/mailman/listinfo/python-list


win32com.client.GetActiveObject()

2005-09-18 Thread David Nicolson
Hi,

I have been successfully using iTunes' COM interface with Python  
using either of the following lines successfully:

iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application")
iTunes = win32com.client.Dispatch("iTunes.Application")

The only problem is that it will launch iTunes if it is not running  
by instantiating the object here. There are some reasons why I have  
not attempted to use more COM to check if iTunes is an active  
process, I tried either of the following lines to only form a  
connection if iTunes is running.

iTunes = win32com.client.GetActiveObject("iTunes.Application")
iTunes = win32com.client.GetObject(Class = "iTunes.Application")

Both lines result in a pythoncom.com_error with 'Operation  
unavailable' in the second element of the tuple. Has anyone been able  
to successfully do this with iTunes' COM server? I have seen other  
'Operation unavailable' messages in a few other mailing lists but was  
unable to find any solutions to this problem.

Regards,
David

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is map() preferable in this case?

2005-09-18 Thread Devan L
Ray wrote:
> Hello,
>
> I'm just reading the latest edition of Python Cookbook, where it says
> in Recipe 4.2:
>
> "when the op you wanna perform on each item is to call a function on
> the item and use the function's result, use L1 = map(f, L), rather than
> L1 = (f(x) for x in L)"
>
> What is wrong with the generator expression (or maybe it is list
> comprehension, I cannot remember now whether they used [] or () in the
> book)? Is it for clarity? I'm a newbie, and to me, the
> generator/comprehension looks _way_ more clearer than map(f, L).
>
> Are there any performance/memory requirements I'm not aware of? Why
> would one want to use map() when there's already an expression that is
> so clear and easy to understand?
>
> Thanks!

Map is in C. It's faster, but not as clear. Some people do think map(f,
L) is nicer though. Google is your friend here, if you want to read the
old arguments.
> Ray

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Example of signaling and creating a python daemon

2005-09-18 Thread Jon Monteleone
What I dont understand about daemonizing a python script is whether or not it 
requires the
daemon creation, ie the signal handling and forking of the process, to be part 
of the
daemon code or is this code in a separate program that acts like a wrapper to 
turn a
python program into a daemon.  The latter is how linux documentation describes 
turning a
program into a daemon.

I guess I am wondering about the difference between using python to daemonize a 
program vs
using a bash script to daemonize a program.
Cheers -Jon
- Original Message - 
From: <[EMAIL PROTECTED]>
To: "David Pratt" <[EMAIL PROTECTED]>
Cc: 
Sent: Friday, September 16, 2005 3:31 AM
Subject: Re: Example of signaling and creating a python daemon


> -- 
> http://mail.python.org/mailman/listinfo/python-list

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32com.client.GetActiveObject()

2005-09-18 Thread Roger Upole
Basically, this means the application doesn't register itself
with the Running Object Table.  There's not much you can
do about it, except maybe petition whoever makes ITunes.

   Roger

"David Nicolson" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Hi,
>
> I have been successfully using iTunes' COM interface with Python  using 
> either of the following lines successfully:
>
> iTunes = win32com.client.gencache.EnsureDispatch("iTunes.Application")
> iTunes = win32com.client.Dispatch("iTunes.Application")
>
> The only problem is that it will launch iTunes if it is not running  by 
> instantiating the object here. There are some reasons 
> why I have  not attempted to use more COM to check if iTunes is an active  
> process, I tried either of the following lines to 
> only form a  connection if iTunes is running.
>
> iTunes = win32com.client.GetActiveObject("iTunes.Application")
> iTunes = win32com.client.GetObject(Class = "iTunes.Application")
>
> Both lines result in a pythoncom.com_error with 'Operation  unavailable' in 
> the second element of the tuple. Has anyone been 
> able  to successfully do this with iTunes' COM server? I have seen other  
> 'Operation unavailable' messages in a few other 
> mailing lists but was  unable to find any solutions to this problem.
>
> Regards,
> David
> 



== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


threads/sockets quick question.

2005-09-18 Thread ed
this script should create individual threads to scan a range of IP
addresses, but it doesnt, it simple ... does nothing. it doesnt hang
over anything, the thread is not being executed, any ideas anyone?
--

import socket
import threading
import traceback


MAX_THREADS = 50


class scanThread(threading.Thread):
def run(self):
try:
ss = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ss.connect((ip, port_counter))
print "%s | %d OPEN" % (ip, port_counter)
ss.close()
print "scanned: ",port_counter,"\n"
except:
traceback.print_exc()
# end class ---


def scan(ip, begin, end):
port_counter = 0
for port_counter in range(begin, end):
while threading < MAX_THREADS:
scanThread().start()
# end function ---
scan("localhost", 0, 1)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How am I doing?

2005-09-18 Thread Mike Meyer
Jason <[EMAIL PROTECTED]> writes:

> Please don't laugh, this is my FIRST Python script where I haven't
> looked at the manual for help...
>
> import string
> import random
>
> class hiScores:
>  hiScores=['1Alpha','07500Beta','05000Gamma','02500Delta','0Epsilon']
>
>  def showScores(self):
>  for entry in self.hiScores:
>  print entry[0:5]," - ",entry[5:]
>
>  def addScore(self,score,name):
>  newScore=string.zfill(score,5)
>  self.hiScores.append(newScore+name)
>  self.hiScores.sort(reverse=True)
>
>  if len(self.hiScores)==6:
>  del self.hiScores[-1]
>
> a=hiScores()
> print "Original Scores\n---"
> a.showScores()
>
> while 1:
>  newScore=random.randint(0,1)
>  if string.zfill(newScore,5)>a.hiScores[4][0:5]:
>  print "Congratulations, you scored %d " % newScore
>  name=raw_input("Please enter your name :")
>  a.addScore(newScore,name)
>  a.showScores()
>  continue
>
> Anything I could have done differently or any "bad-habits" you think I
> have which could lead to ultimate doom I really appreciate to know.

George already covered a lot of things. I wanted to make a general comment:

The standard idiom is to put all the executable code for a script in a
function, (say "main"), then invoke that function iff your code is run
as a script:

def main():
a = hiScores()
...

if __name__ == "__main__":
   main()

That way your program can be used as a module by other applications,
allowing your classes/functions/etc. to be reused by other
applications without having to copy them out of your program.

   http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Possible bug in "metaclass resolution order" ?

2005-09-18 Thread Bengt Richter
On Sat, 17 Sep 2005 12:41:09 -0300, Pedro Werneck <[EMAIL PROTECTED]> wrote:

>On 17 Sep 2005 02:04:39 -0700
>"Simon Percivall" <[EMAIL PROTECTED]> wrote:
>
>> Have you read the "Metaclasses" part of "Unifying types and classes in
>> Python 2.2"? (http://www.python.org/2.2.3/descrintro.html#metaclasses)
>
>Yes, I read. Have you read and understood my message ? :)
>
>A class B, subclass of class A, with a metaclass M_A should have M_A or
>a subclass of it as metaclass. If you try with anything else, you get a
>TypeError exception as expected. OK. But if you try with 'type', nothing
>happens. 
>
>Python 2.4.1 (#1, Sep 16 2005, 17:47:47) 
>[GCC 3.3.4] on linux2
>Type "help", "copyright", "credits" or "license" for more information.
 class M_A(type): pass
>... 
 class A: __metaclass__ = M_A
>... 
 class B(A): __metaclass__ = type
>... 
 B.__class__
>
 B.__metaclass__
>
>
FWIW, I think __metaclass__ can be any callable, but it seems to be the
first argument to type.__new__ that invokes the checking and
type(name, bases, cdict) seems to have the same effect as
type.__new__(type, name, bases, cdict). Maybe there has to be
a "real" class on the mro, and type isn't one, or it's a wild card ;-)

I haven't really grokked the error message's true meaning, not having
dealt with metaclass conflict before. Not ready today, sorry ;-)

 >>> class M_A(type): pass
 ...
 >>> class A: __metaclass__ = M_A
 ...
 >>> def foo(*args): print args; return 'silliness'
 ...
 >>> def foo(cname, cbases, cdict):
 ... print 'cname, cbases:', cname, cbases
 ... print 'cdict:', cdict
 ... mt = type('M_B',(type,),{})
 ... print 'mt:', mt
 ... print 'mt.mro(mt):', mt.mro(mt)
 ... print 'mt.__new__:', mt.__new__
 ... something = mt.__new__(mt, cname, cbases, cdict)
 ... print 'something:', something
 ... return something
 ...
 >>> class B(A): __metaclass__ = foo
 ...
 cname, cbases: B (,)
 cdict: {'__module__': '__main__', '__metaclass__': }
 mt: 
 mt.mro(mt): [, , ]
 mt.__new__: 
 Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 8, in foo
 TypeError: Error when calling the metaclass bases
 metaclass conflict: the metaclass of a derived class must be a 
(non-strict) subclass of the
 metaclasses of all its bases
 >>> def bar(cname, cbases, cdict):
 ... print 'cname, cbases:', cname, cbases
 ... print 'cdict:', cdict
 ... mt = type
 ... print 'mt:', mt
 ... print 'mt.mro(mt):', mt.mro(mt)
 ... print 'mt.__new__:', mt.__new__
 ... something = mt.__new__(mt, cname, cbases, cdict)
 ... print 'something:', something
 ... return something
 ...
 >>> class B(A): __metaclass__ = bar
 ...
 cname, cbases: B (,)
 cdict: {'__module__': '__main__', '__metaclass__': }
 mt: 
 mt.mro(mt): [, ]
 mt.__new__: 
 something: 
 >>>

And the something returned, whatever it is, if no checking is triggered by 
normal use,
gets bound to the class name, e.g.,

 >>> class C(A): __metaclass__ = lambda *a:('silly', 'result')
 ...
 >>> C
 ('silly', 'result')

Regards,
Bengt Richter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Brute force sudoku cracker

2005-09-18 Thread Gregory Bond


My current solver does 1 level of backtracking (i.e. constant space, and 
bounded time) only, and it has been able to solve every puzzle I've 
thrown at it.  It's based on the usual logic and book-keeping for the 
most part.  (It also explains how it comes up with each answer step as 
it goes, which is handy...)

Once it gets to the stage where it needs to guess, it arranges all the 
unknowns then tries them in some arbitary order.  It saves the state, 
applies the guess (square x,y is N) and then re-applies all the logic 
rules.  There are 3 possible outcomes from here:

  - We've solved it, which is good (this happens surprisingly often)

  - We can't solve it using this guess (so ignore this possibility, 
restore the state & try the next guess)

  - The Resulting puzzle is badly formed / inconsistant (represented by 
a python exception, naturally!) In this case, we know the guessed 
square/number is not valid, so we backtrack (restore the state before we 
made this guess), remove that possibility (x,y is N) and then apply all 
the logic rules again.  Often times, this is enough to solve, but it 
usually progreses things a little even if it doesn't solve it.

I've not yet found a (9x9) puzzle that this cannot solve.  The downside 
is that it cannot detect cases where there are multiple solutions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Help installing Python Constraints

2005-09-18 Thread Levi Self
Hi

Can someone help me figure out how to install Python Constraints on Windows? I have Python 2.4

Thanks
-- 
http://mail.python.org/mailman/listinfo/python-list