Re: string.atoi and string.atol broken?

2005-01-26 Thread Peter Otten
Dan Bishop wrote:

>> def itoa(n, base):
>>assert 2 <= base <= 16
> 
> Why have the restriction base <= 16?  int() allows up to 36.  All you
> need to do is
> 
> BASE36_DIGITS = string.digits + string.lowercase

For no other reason than carelessness. I have not yet seen anything beyond
base-16 in the wild.

By the way, does anyone know the Greek name for 36?

Peter


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


Re: python without OO

2005-01-26 Thread Alex Martelli
Davor <[EMAIL PROTECTED]> wrote:

> no one ever had to document structured patterns - which definitely
> exist - but seem to be obvious enough that there is no need to write a
> book about them...

You _gotta_ be kidding -- what do you think, e.g., Wirth's "Algorithms
plus Data Structures Equals Programs" *IS* all about?


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


Re: script to search ebay?

2005-01-26 Thread Lance Hoffmeyer
Thanks for the script.  I haven't been on ebay for a while.
Wasn't aware of the Favorite searches.  Favorite Search is
probably the way to go.  Thanks for the info.

Lance


On Tue, 25 Jan 2005 22:57:54 -0800, Kamilche wrote:

> This script works. But why not make a 'Favorite Search' in ebay, and
> have it send you daily email for a year?
> 
> --Kamilche
> 
> |import urllib
> |import smtplib
> |
> |def main():
> |# Perform the search
> |results = SearchEbay(['So long and thanks for all the fish',
> | 'NOMATCHFOUND',
> | 'Python Programming'])
> |
> |# Email the results
> |Email('[EMAIL PROTECTED]',
> |  '[EMAIL PROTECTED]',
> |  'eBay Search Results',
> |  results)
> |
> |def SearchEbay(searchstrings):
> |' Search eBay for the desired items'
> |searchURL = "http://search.ebay.com/%s";
> |results = ""
> |s = "eBay Search Results:\n"
> |print s,
> |results += s
> |for i in range(len(searchstrings)):
> |
> |# Build the search URL
> |search = searchstrings[i].replace(' ', '-')
> |s = searchURL % search + " : "
> |print s,
> |results += s
> |
> |# Download the URL
> |url = urllib.urlopen(searchURL % search)
> |data = url.read()
> |url.close()
> |
> |# Write the URL to a file for debugging
> |fd = open('ebay %d.html' % i, 'w')
> |fd.write(data)
> |fd.close()
> |
> |# Search for the number of items found
> |c = data.find('items found for')
> |if c >= 0:
> |start = data.rfind('', 0, c) + 3
> |stop  = data.find('', start + 1)
> |cnt   = data[start:stop]
> |else:
> |cnt = '0'
> |s = "%s items found.\n" % cnt
> |print s,
> |results += s
> |
> |return results
> |
> |def Email(fromaddr, toaddr, subject, msg):
> |' Send email'
> |msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" % \
> |   (fromaddr, toaddr, subject, msg))
> |server = smtplib.SMTP('your.smtp.server.here')
> |server.set_debuglevel(1)
> |server.sendmail(fromaddr, toaddr, msg)
> |server.quit()
> |
> |main()

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


Re: is there better 32 clock() timing?

2005-01-26 Thread Bengt Richter
On Tue, 25 Jan 2005 15:46:30 +, Stephen Kellett <[EMAIL PROTECTED]> wrote:

>In message <[EMAIL PROTECTED]>, Bengt Richter 
><[EMAIL PROTECTED]> writes
>>I believe that is quite wrong as a general statement.
>
>Actually my initial statement should have been written
>"accessing a resource, the accuracy of which is no better than 10ms.". I 
>was thinking of the 1ms multimedia timer but wrote about clock() 
>instead.
>
>10ms, coincidentally is the approx minimum scheduling granularity for 
>threads unless you are in a multimedia thread (or real time thread - not 
>sure about real time threads in NT).
>
>>If the "resource" only had ~1ms granularity,
>>the minimum would be zero, as it is if you call time.time() in a tight loop,
>
>Correct. Write your app in C and call clock(). Thats what you get. You 
>can call clock 2 times and still get a delta of zero. The next delta 
>(on my system) is 10ms at about 22000 calls.
>
>>>There are various timers available, documented and undocumented, all of
>>>which end up at 1ms or 1.1ms, give or take. For anything shorter you
>
>Whoops here we go, same typo - should have been 10ms or 11ms. There is a 
>1ms timer in the multimedia timing group.
>
>>>need QueryPerformanceCounter() (but that *is* a slow call), or use the
>>Have you timed it, to make that claim?
>
>Yes.
>
>>What do you mean by "slow"?
>
>Slower than any other Win32, CRT or Undocumented NT function you can use 
>to get timer information. Yes, I have timed them all, a few years ago.
>
>QueryPerformanceCounter is 47 times slower to call than clock() on my 
>1Ghz Athlon.
That really makes me wonder. Perhaps the Athlon handles RDTSC by way of
an illegal instruction trap and faking the pentium instruction? That might
explain the terrible timing. Try it on a pentium that supports RDTSC.
The clock() usually gets high resolution bits from a low order 16 bits
of the timer chip that drives the old 55ms clock that came from IBM
using cheap TV crystal based oscillators instead of defining an
OS-implementer-friendly time base, I think. The frequency was nominally
1193182 hz I believe. Obviously the OS didn't get interrupted that often,
but if you divide by 2**16, you get the traditional OS tick of ~55ms:

 >>> 1193182./2**16
 18.206512451171875
 >>> (1193182./2**16)**-1
 0.054925401154224583

So that's a clue. By grabbing tick count and bits read from the fast-counting
harware clock register, you can compute time fairly accurately for the moment
you are sampling that register. IIRC, you couldn't get the whole 16 bits because
it was a toggling trigger or some such.

>
>QueryPerformanceCounter may have finer granularity, but called in a 
>tight loop it'll crush your program.
Maybe on your Athlon, but my experience is different ;-)

>
>>>RDTSC instruction which is fast but gives a count of instruction cycles
>>>executed and is thus not totally accurate (multiple execution pipelines,
>>>plus multithreading considerations).
>>Accurate for what.
>
>See below - you haven't taken things into account, despite my comment in 
>brackets above which gives a big hint.
I've absorbed a lot of hints since around '59 when I began to work with
computers and timing issues ;-)

>
>>A single clock AFAIK drives RDTSC
>
>Correct.
>
>>The main problem with a CPU clock based reading is that it's very stable 
>>unless
>>there's variable clock rate due to power management.
>
>Try running multiple apps at the same time you are doing your 
>measurement, each of which has a variable loading. Each of these apps is 
>contributing to the count returned by RDTSC. That is what I was 
>referring to.

Ok, but that's another issue, which I also attempted to draw attention to ;-)

Quoting myself:
"""
>
>Even with the attribute lookup overhead, it's not several hundred microseconds
>as a *minimum*. But on e.g. win32 you can get preempted for a number of 
>milliseconds.
>E.g., turn that to a max instead of a min:
>
>I see a couple 20-30 ms ones ;-/
>
> >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5))
> 0.0085142082264155761
> >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5))
> 0.0088125700856949152
> >>> max(abs(time.clock()-time.clock()) for i in xrange(10**5))
> 0.0022125710913769581
> >>> max(abs(clock()-clock()) for i in xrange(10**5))
> 0.023374472628631793
> >>> max(abs(clock()-clock()) for i in xrange(10**5))
> 0.030183995400534513
> >>> max(abs(clock()-clock()) for i in xrange(10**5))
> 0.0017130664056139722
> >>> max(abs(clock()-clock()) for i in xrange(10**5))
> 0.0070844179680875641
>
"""

Depending on what your timing requirements are, you may be able to run
a zillion trials and throw out the bad data (or plot it and figure out
some interesting things about timing behavior of your system due to various
effects). E.g., timeit presumably tries to get a minimum and eliminate as
many glitches as possible.

But as mentioned, the big picture of requirements was not clear. Certainly
you can't expect to control ignition of a rac

Re: string.atoi and string.atol broken?

2005-01-26 Thread Peter Otten
Nick Coghlan wrote:

> Huh - you remind me that I forgot to put the "show_base" Bengt and I came
> up with into the ASPN cookbook. . .
> 
> Py> def show_base(val, base, min_digits=1, complement=False,
> ...   digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
> ...   if base > len(digits): raise ValueError("Not enough digits for
> base") ...   negative = val < 0
> ...   val = abs(val)
> ...   if complement:
> ... sign = ""
> ... max = base**min_digits
> ... if (val >= max) or (not negative and val == max):
> ...   raise ValueError("Value out of range for complemented format")
> ... if negative:
> ...   val = (max - val)
> ...   else:
> ... sign = "-" * negative
> ...   val_digits = []
> ...   while val:
> ... val, digit = divmod(val, base)
> ... val_digits.append(digits[digit])
> ...   result = "".join(reversed(val_digits))
> ...   return sign + ("0" * (min_digits - len(result))) + result
> ...
> 

Yes, that is a bit more general. For the cookbook you might consider
factoring out the "".join() operation, thus entirely removing the upper
limit for the base (the output of the first step would be a tuple of
integers).

Peter

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


Re: snakespell and myspell

2005-01-26 Thread Fuzzyman

Jarek Zgoda wrote:
> Fuzzyman wrote:
>
> > I'm looking to implement a plugin spell checker.
> >
> > I'm probably going to go with PyEnchant, as it looks to be the most
> > promising currently maintained spell checker.
> >
> > I just wondered if anyone knew what happened to snakespell and
myspell.
> > Both seem to have dissapeared from the net. People have reported
good
> > results from both - and it seems a shame to lose them.
>
> Well, myspell-python is no longer maintained, original author
resigned
> some time ago and I didn't found anybody who would like to take
> responsibility on this package. I provide myspell-1.0 download from
my
> project page at BerliOS (http://developer.berlios.de/projects/jpa/),
but
> I do not maintain this package.
>
> If you look for spell-checking library, I'd consider using python
> binding for aspell, available at
> http://www.republika.pl/wmula/proj/aspell-python/ (currently I'm
> rewriting my program to use python-aspell). This library is actively
> maintained and Wojtek Mula is active member of Polish Python
community.
>

The problem with aspell is (as far as I can see anyway) that the
library you mention is aimed at aspell 0.50.5 or the up to date 0.60
series. aspell for windows is currently only at 0.50.3.

Hmmm I think I'll explore PyEnchant for the moment. I need to see
how easy it is to add words to a user dictionary.

Regards,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> --
> Jarek Zgoda
> http://jpa.berlios.de/ | http://www.zgodowie.org/

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


Re: py2exe problem

2005-01-26 Thread Harald Massa
Grant Edwards 

> LookupError: no codec search functions registered: can't find encoding
> Googling for the error message will find you the answer.  

http://starship.python.net/crew/theller/moin.cgi/Py2Exe

carries within "encodings" and "encodings again" receipes to get it 
working.

A software development system which REALLY solves the encodings problem 
WITHOUT creating a swarm of new ones could would challange even my 
devotedness to Python :

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


Re: Maximum Number of Class Attributes

2005-01-26 Thread Sylvain Thenault
On Wed, 26 Jan 2005 02:03:12 +, Bob Parnes wrote:

> In its default configuration, my version of pylint (0.5.0) sets the
> maximum number of class attributes at 7. This seems low to me, but I can
> see how an excessive number might make maintenance more difficult. Is this
> indeed the best value for a maximum under ordinary conditions? If not, can
> anyone suggest a more  reasonable value?

well, this value is very subjective, and may change from one context to
another... For instance at some point I hope that pylint will detect "GUI"
classes and allow more attributes (and methods?) to those. 
Anyway that's just an indicator, not a rule of thumb (and pylint itself
has some class with more than 7 attributes...). 

And FYI, this value has been taken from a post to the
testdrivendevelopment at yahoogroups (as most others default values in the
"design analysis" checker). Hum, well... After checking it seems that the
post said 20 attributes. I don't remember why did i get this number down
to 7. If this discussion leads to an agreement for a better number, I
can change the default value.

-- 
Sylvain Thénault   LOGILAB, Paris (France).

http://www.logilab.com   http://www.logilab.fr  http://www.logilab.org


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


Re: need help on generator... (re)

2005-01-26 Thread Peter Otten
Joh wrote:

>> def gen(iterable, start, end):
>>it = iter(iterable)
>>while True:
>>it, a = tee(it)
>>a = tuple(islice(a, end-1))
>>for sz in xrange(start, len(a)+1):
>>yield a[:sz]
>>it.next()
>>
>> if __name__ == "__main__":
>>print list(gen(range(1, 5), 2, 4))
> 
> please, this one looks interesting, could you explain a bit how it
> works and why it "remain memory-efficient" ?

If you have a generator of the form

def gen1(iterable):
for i in iterable:
yield f(i)
for i in iterable:
yield g(i)

and then use it

for item in gen1(range(huge_number)):
do_something_useful_with(item)

it will only work when you feed it with something you can iterate over
multiple times, e. g. a list, not a generator that reads data on every call
of the next() method. That means you must store the data for (to keep it
simple) the lifetime of gen1(). If you can modify the generator to

def gen2(iterable):
for i in iterable:
yield f(i)
yield g(i)

for item in gen2(xrange(huge_number)): # switched from range() to xrange()
do_something_useful_with(item)

there is no such restriction to the iterable. All data can be read,
processed and garbage-collected immediately.

The gen() generator is a bit more complex in that it has to store a few
adjacent items instead of only one and allows for an arbitrary number of
functions (inlined as yield of an n-tuple) instead of always two functions,
but the idea is the same.

Peter




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


Re: MySQLdb

2005-01-26 Thread Daniel Bowett
Dennis Lee Bieber wrote:
On Tue, 25 Jan 2005 20:43:54 +, Daniel Bowett
<[EMAIL PROTECTED]> declaimed the following in
comp.lang.python:

As a test I have written a script that executes 3000 insert statements 
on a table. The table contains 10 fields with a mix of text and numbers 
- its a product table for a website eg UPC, ProductName, Price etc.

	How many indices?
 

The problem I have is that it takes just over two minuted to execute the 
3000 insert statements which seems really slow! I am running it on a 

I recall reading that, for some RDBMs, when doing such batch
inserts, they recommend turning off the indices at the start, do the
inserts, then reactivate the indices -- apparently it is faster to
rebuild an index after the data has been inserted, then to continually
update the index.
UPC is my only index - its a varchar with 20 characters. I am only 
opening the connection once, then doing 3000 execute statements in a for 
loop.

I do have two "TEXT" fields in the table which contain the long and 
short description. The average length of the long description is about 
167 characters, the longest is 1800 characters. Is this whats making it 
slow?

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


Re: Help! Host is reluctant to install Python

2005-01-26 Thread Premshree Pillai
There are quite a few hosts who offer Python support, no? Maybe you
could change hosts. Pair offers Python, AFAIK.


On Tue, 25 Jan 2005 13:15:45 -0500, Daniel Bickett <[EMAIL PROTECTED]> wrote:
> I've been trying to convince my host to install python/mod_python on
> his server for a while now, however there are a number of reasons he
> is reluctant to do so, which I will outline here:
> 
> 1. His major reason is optimization. He uses Zend's optimization of
> PHP as an example, and he has stated that python is rather resource
> consuming.
> 2. Another one of his points is that he is unexperienced in installing
> python, and he would not know how to do it securely. By 'securely',
> I'm assuming he means disallowing a malicious (or ignorant) user from
> harming the server
> 
> And, in light of point #1, I suggested that if there wasn't any
> optimization immediately available, he could just enable it for my
> account (thus lessening potential resource consumption at any given
> time), to which he retorted "Do /you/ know how to do that?", and I
> must say, he has me cornered ;-)
> 
> I have no experience with this sort of thing, so I'm asking a little
> assistance in the direction of any documents or websites (or what have
> you) I could show him in order to answer some of these questions, or
> perhaps even some unspoken ones -- anything worth noting. (all I'm
> really going to do is link him to this thread once it has accumulated
> any answers)
> 
> Thank you all for your help :)
> 
> Wishing-to-be-liberated-from-the-clutches-of-PHP-ly y'rs,
> Daniel Bickett
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


-- 
Premshree Pillai
http://www.livejournal.com/~premshree
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to ncurses on win32 platform

2005-01-26 Thread Josef Meile
Hi Brane,
I was wondering about the same thing some days
ago. I found the following alternatives:
* Curses for Windows for Python (It was previously
mentioned on a follow-up. there are some missing
features):
http://flangy.com/dev/python/curses/
* PDCurses (It looks promissing):
http://pdcurses.sourceforge.net/
* The Console Module:
http://www.effbot.org/zone/console-handbook.htm
* Windows CONsole I/O for Python:
http://newcenturycomputers.net/projects/wconio.html
Please note that I haven't tested any of the mentioned
packages, so, I don't know if they are really a good
replacement for ncurses, so, it's up-to-you to test
them.
Regards,
Josef
--
http://mail.python.org/mailman/listinfo/python-list


Re: python without OO

2005-01-26 Thread Claudio Grondi
I can't resist to point here to the
  Re: How to input one char at a time from stdin?
posting in this newsgroup to demonstrate, what
this thread is about.

Claudio

> >On Tue, 25 Jan 2005 12:38:13 -0700, Brent W. Hughes
> ><[EMAIL PROTECTED]> wrote:
> >> I'd like to get a character from stdin, perform some action, get
another
> >> character, etc.  If I just use stdin.read(1), it waits until I finish
typing
> >> a whole line before I can get the first character.  How do I deal with
this?
> >
> >This is exactly what you need:
> >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/134892
> >Title: "getch()-like unbuffered character reading from stdin on both
> >Windows and Unix"
>
> Nice to know how, but all those double underscores made my eyes bleed.
> Three classes? What's wrong with something simple like the following
> (not tested on Unix)?
>
>
> import sys
> bims = sys.builtin_module_names
> if 'msvcrt' in bims:
> # Windows
> from msvcrt import getch
> elif 'termios' in bims:
> # Unix
> import tty, termios
> def getch():
> fd = sys.stdin.fileno()
> old_settings = termios.tcgetattr(fd)
> try:
> tty.setraw(sys.stdin.fileno())
> ch = sys.stdin.read(1)
> finally:
> termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
> return ch
> else:
> raise NotImplementedError, '... fill in Mac Carbon code here'

"Davor" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> Is it possible to write purely procedural code in Python, or the OO
> constructs in both language and supporting libraries have got so
> embedded that it's impossible to avoid them? Also, is anyone aware of
> any scripting language that could be considered as "Python minus OO
> stuff"? (As you can see I'm completely new to Python and initially
> believed it's a nice&simple scripting language before seeing all this
> OO stuff that was added in over time)
> Thanks,
> Davor

Here the OO "solution" (activestate recipe 134892):

class _Getch:
"""Gets a single character from standard input.  Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()

def __call__(self): return self.impl()


class _GetchUnix:
def __init__(self):
import tty, sys

def __call__(self):
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch


class _GetchWindows:
def __init__(self):
import msvcrt

def __call__(self):
import msvcrt
return msvcrt.getch()


getch = _Getch()


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


Re: how to write a tutorial

2005-01-26 Thread Keith Thompson
"Xah Lee" <[EMAIL PROTECTED]> writes:
[snip]
> Following is a tutorial on Python's classes.
[snip]

Please stop posting this to comp.lang.c.  I'm sure the folks in most
of the other newsgroup aren't interested either -- or if they are,
they can find it in comp.lang.python.

Followups redirected.

-- 
Keith Thompson (The_Other_Keith) [EMAIL PROTECTED]  
San Diego Supercomputer Center <*>  
We must do something.  This is something.  Therefore, we must do this.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to write a tutorial

2005-01-26 Thread Charlton Wilbur
> "XL" == Xah Lee <[EMAIL PROTECTED]> writes:

XL> I've used the Python tutorial's chapter on class as
XL> an example. I've indicated that proper tutorial should be
XL> simple, covering just common cases, be self-contained, and be
XL> example based. 

"Correct" is not in your list of criteria.  Big surprise, that.

Followups set appropriately.

Charlton


-- 
cwilbur at chromatico dot net
cwilbur at mac dot com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple slices

2005-01-26 Thread jfj
Jeff Shannon wrote:

So, what problem is it, exactly, that you think you'd solve by making 
tuple slices a view rather than a copy?

I think views are good for
 1) saving memory
 2) saving time (as you don't have to copy the elements into the new tuple)
And they are worth it. However, (as in other cases with slicing), it is 
very easy and fast to create a view for a slice with the default step 
'1', while it's a PITA and totally not worth it to create a view for a 
slice with non default step. I think it would be good to:

 if slice_step == 1
   create_view
 else
   create_new_tuple
Actually, i think that slices with step, is a bad feature in general
and i think I will write a PEP to suggest their removal in python3k.
Gerald
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python with no significant whitespace

2005-01-26 Thread Jeremy Sanders
On Wed, 26 Jan 2005 11:31:18 +0800, mep wrote:

> Hi,all
> Is there anybody trying to release a modification version to current
> python source code with no significant whitespace, say replacing whitespace
> by {}
> like C or java. I do *NOT* mean whitespace is good or bad, just
> want to know.

It probably would be easy to convert source in the form using brackets to
indented form on the fly, and use exec to interpret the converted form.

You need to do something like convert  { to

:
 foo

Of course this isn't a good idea.

Jeremy


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


RELEASED Python 2.3.5, release candidate 1

2005-01-26 Thread Anthony Baxter

On behalf of the Python development team and the Python community, I'm
happy to announce the release of Python 2.3.5 (release candidate 1).

Python 2.3.5 is a bug-fix release. See the release notes at the website
(also available as Misc/NEWS in the source distribution) for details of
the bugs squished in this release.

Assuming no major problems crop up, a final release of Python 2.3.5 will
follow in about a week's time. 

Python 2.3.5 is the last release in the Python 2.3 series, and is being
released for those people who still need to use Python 2.3. Python 2.4
is a newer release, and should be preferred if possible. From here,
bugfix releases are switching to the Python 2.4 branch - a 2.4.1 will
follow 2.3.5 final.

For more information on Python 2.3.5, including download links for
various platforms, release notes, and known issues, please see:

http://www.python.org/2.3.5

Highlights of this new release include:

  - Bug fixes. According to the release notes, more than 50 bugs 
have been fixed, including a couple of bugs that could cause 
Python to crash. 

Highlights of the previous major Python release (2.3) are available 
from the Python 2.3 page, at

http://www.python.org/2.3/highlights.html

Enjoy the new release,
Anthony

Anthony Baxter
[EMAIL PROTECTED]
Python Release Manager
(on behalf of the entire python-dev team)


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

Re: python without OO

2005-01-26 Thread Fuzzyman
It's perfectly possible to write good python code without using
classes. (and using functions/normal control flow).

You will have a problem with terrminology though - in python everything
is an object (more or less). Common operations use attributes and
methods of standard objects.

For example :

> somestring = 'fish'
> if somestring.startswith('f'):
> print 'It does'

The above example uses the 'startswith' method of all string objects.

Creating your own 'classes' of objects, with methods and attributes, is
just as useful.

You can certainly use/learn python without having to understand object
oreinted programming straight away. On the other hand, Python's object
model is so simple/useful that you *will* want to use it.
Regards,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

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


Re: Tuple slices

2005-01-26 Thread Bengt Richter
On Tue, 25 Jan 2005 19:25:55 -0500, "George Sakkis" <[EMAIL PROTECTED]> wrote:

>"Jeff Shannon" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
>> George Sakkis wrote:
>>
>> > An iterator is perfectly ok if all you want is to iterate over the
>> > elements of a view, but as you noted, iterators are less flexible than
>> > the underlying sequence. The view should be (or at least appear)
>> > identical in functionality (i.e. public methods) with its underlying
>> > sequence.
>>
>> So, what problem is it, exactly, that you think you'd solve by making
>> tuple slices a view rather than a copy?
>>
>> As I see it, you get the *possibility* of saving a few bytes (which
>
>It all comes down on what you mean by "a few bytes". Since many (most?) slices 
>are linear wrt to the
>original sequence's length, it is not hard to think of algorithms that involve 
>the creation of
>*many* slices (e.g. most recursive divide-and-conquer algorithms). 
>Implementing these using slices
>simply does not scale as the input sequence gets larger. Of course, you can 
>always use the standard
>C/C++ approach and pass the original sequence along with the (start,stop,step) 
>indices of the slice,
>as Terry Reedy mentioned, but then you lose in expressiveness.
I didn't see the leadup to this, but what is the problem with just subclassing 
tuple to
give you the views you want?


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


Re: MySQLdb

2005-01-26 Thread nobody
> How many indices?

Just the primary key (id).



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


Re: py2exe problem

2005-01-26 Thread Thomas Heller
Harald Massa <[EMAIL PROTECTED]> writes:

> Grant Edwards 
>
>> LookupError: no codec search functions registered: can't find encoding
>> Googling for the error message will find you the answer.  
>
> http://starship.python.net/crew/theller/moin.cgi/Py2Exe
>
> carries within "encodings" and "encodings again" receipes to get it 
> working.
>
> A software development system which REALLY solves the encodings problem 
> WITHOUT creating a swarm of new ones could would challange even my 
> devotedness to Python :

AFAIK, McMillan Installer solves this by including all the encodings
stuff by default, and it has a --ascii flag to override this behaviour.
Would that be a solution?

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


"pickle" vs. f.write()

2005-01-26 Thread Johan Kohler
Hi,
I have a class with attributes that are string, integer and list.  eg.
class person:
name =""
age = 0
friends=[]
comment=""
me = person()
I want to save a whole bunch of instances to a file, a classic "records"  
file I/O.

To write the file, I can do f.write(str([me.name, me.age, me.friends,  
me.comment]) + "\n"

This works nicely for writing, but when reading, I cannot convert the  
string easily to a list:
list(f.readline()) is not the same as [me.name, me.age, me.friends,  
me.comment]

I was wondering whether pickle might make this easier - an example would  
be much appreciated.

Otherwise, what is the best "Python" way to write and read this data  
structure?

Thanks in advance...
Johan
__
Yes, I do feel stupid asking this, but time's-a-runnin' out..
--
Using Opera's revolutionary e-mail client: http://www.opera.com/m2/

Please find our disclaimer at http://www.ukzn.ac.za/disclaimer

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


Re: python without OO

2005-01-26 Thread Premshree Pillai
On 25 Jan 2005 13:49:48 -0800, Davor <[EMAIL PROTECTED]> wrote:
> Is it possible to write purely procedural code in Python, or the OO
> constructs in both language and supporting libraries have got so
> embedded that it's impossible to avoid them? Also, is anyone aware of
> any scripting language that could be considered as "Python minus OO
> stuff"? (As you can see I'm completely new to Python and initially
> believed it's a nice&simple scripting language before seeing all this
> OO stuff that was added in over time)
> Thanks,
> Davor

Umm,  just curious -- why would you want to not use the OO stuff?
Python is like pseudocode (the basic OO, which is mostly common to
most OO languages, isn't really complicated).

Moreover, using Python without OO would be like, um, eating mango seed
without the pulp. :)

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


-- 
Premshree Pillai
http://www.livejournal.com/~premshree
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb

2005-01-26 Thread Daniel Bowett
Daniel Bowett wrote:
I have just started playing around with MySQLdb for a project I am 
planning.

As a test I have written a script that executes 3000 insert statements 
on a table. The table contains 10 fields with a mix of text and numbers 
- its a product table for a website eg UPC, ProductName, Price etc.

The problem I have is that it takes just over two minuted to execute the 
3000 insert statements which seems really slow! I am running it on a 
machine with a 1.5 Ghz Pentium M Processor and Gig Of Ram. I dont think 
the machine is to blame for the speed because during execution the 
processor sits at about 10% and there is loads of free RAM.

Does anyone know if this sort of speed sounds right?
Cheers,
Dan.

UPDATE
--
I have found the "executemany" function! It now takes around a second to 
complete the 3000 inserts.

Lesson learnt - I should have posted my code...
Thanks for your help everyone.
--
http://mail.python.org/mailman/listinfo/python-list


Re: building Python: up arrow broken on SuSE Linux 8.2

2005-01-26 Thread Peter Maas
Erik Johnson schrieb:
I am trying to upgrade my Python installation. After downloading
sources and building Python 2.3.4, I am unable to use the command
history editing feature in the interactive interpreter (where the
up-arrow would previously give you the last command line to edit,
it now just prints "^[[A".)
Do you have the GNU readline library installed and within Python's
reach (lib in LD_LIBRARY_PATH or in /etc/ld.so.conf with subsequent
call of ldconfig)?
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: python without OO

2005-01-26 Thread Miki Tebeka
Hello Davor,

> Also, is anyone aware of any scripting language that could be considered
> as "Python minus OO stuff"? 
Maybe Lisp (http://clisp.cons.org/, http://www.paulgraham.com/onlisp.html)
or Scheme (http://www.plt-scheme.org/software/mzscheme/,
http://mitpress.mit.edu/sicp/full-text/book/book.html)
will be better for you mind :-)

HTH.
--

Miki Tebeka <[EMAIL PROTECTED]>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple slices

2005-01-26 Thread Bengt Richter
On Wed, 26 Jan 2005 11:55:59 -0800, jfj <[EMAIL PROTECTED]> wrote:

>Jeff Shannon wrote:
>
>> 
>> 
>> So, what problem is it, exactly, that you think you'd solve by making 
>> tuple slices a view rather than a copy?
>> 
>
>I think views are good for
>  1) saving memory
>  2) saving time (as you don't have to copy the elements into the new tuple)
>
>And they are worth it. However, (as in other cases with slicing), it is 
>very easy and fast to create a view for a slice with the default step 
>'1', while it's a PITA and totally not worth it to create a view for a 
>slice with non default step. I think it would be good to:
>
>  if slice_step == 1
>create_view
>  else
>create_new_tuple
>
>Actually, i think that slices with step, is a bad feature in general
>and i think I will write a PEP to suggest their removal in python3k.
>
What's the big deal with other than 1 steps? It is just adjusting a few numbers
so that you can either index the new virtual slice with an integer and return 
the
element, in which case the index into the original tuple will be
someoffset+i*somefactor once you get past the limit checks for the virtual
slice. By the same token, transforming a few numbers of one virtual slice
into similar numbers for a a new virtual slice of that shouldn't be rocket 
science.
And it wouldn't have to be done more than once.  Don't have time to do it now,
but there are plenty around here that could, I'm sure.

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


Re: re Insanity

2005-01-26 Thread Tim Daneliuk
Aahz wrote:
In article <[EMAIL PROTECTED]>,
Tim Daneliuk  <[EMAIL PROTECTED]> wrote:
Given an arbitrary string, I want to find each individual instance of
text in the form:  "[PROMPT:optional text]"
I tried this:
   y=re.compile(r'\[PROMPT:.*\]')
Which works fine when the text is exactly "[PROMPT:whatever]" but
does not match on:
  "something [PROMPT:foo] something [PROMPT:bar] something ..."
The overall goal is to identify the beginning and end of each [PROMPT...]
string in the line.
Ideas anyone?

Yeah, read the Friedl book.  (Okay, so that's not gonna help right now,
but trust me, if you're going to write lots of regexes, READ THAT BOOK.)
I've read significant parts of it.  The problem is that I don't write
re often enough to recall all the subtle details ... plus I am getting
old and feeble... ;)
--

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list


Re: string.atoi and string.atol broken?

2005-01-26 Thread TZOTZIOY
On Wed, 26 Jan 2005 08:58:45 +0100, rumours say that Peter Otten
<[EMAIL PROTECTED]> might have written:

>By the way, does anyone know the Greek name for 36?

triakontahexadecimal would be a nice compromise of greek and the
"hexadecimal" convention of having six before ten -- "ÎÎÎ" ("hexi") is
six, "" ("deka") is ten, "ÏÏÎÏÎ" ("triakonta") is thirty.  
I
think in ancient Greek sometimes units came before tens, just like in
German (another similarity is the verb in the end of the sentence, as
Mark Twain also noted sometime in a humourous article AFAIR.)

In current Greek hexadecimal is "ÎÎÏÎ" ("dekaexadikon").
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python without OO

2005-01-26 Thread Neil Benn
Davor wrote:
Is it possible to write purely procedural code in Python, or the OO
constructs in both language and supporting libraries have got so
embedded that it's impossible to avoid them? Also, is anyone aware of
any scripting language that could be considered as "Python minus OO
stuff"? (As you can see I'm completely new to Python and initially
believed it's a nice&simple scripting language before seeing all this
OO stuff that was added in over time)
Thanks,
Davor
 

Hello,
 Yes you can, that is a benefit and flaw of python in that you 
can mix up procedural and OO code, it allows for simple solutions - 
however it also allows for you to create all kinds of havoc.  IMHO, 
there would have to be a very very small task to require procedural 
code.  Especially if the code is gonna be open sourced (and presumably 
built upon) you will benefit from a proper design so that it can be 
developed and moved on in the future.

One other thing, if your developers are proposing deep inheritance 
trees in _any_ language then they are designing incorrectly.  In none of 
the languages I code in would I design a deep inheritance tree, the deep 
inheritance tree is a fault of the designer not the language (for 
example Java does not force you to design deep inheritance trees!) - 90% 
of the time.  I say this because you do need to be aware of the 
'mythical python wand' which will turn you from a bad programmer into a 
good programmer simply by typing 'class Klass(object):'.

   Rather than reading a GOF book, I'd pick up an introduction to OO 
programming book to take a refresher course - you thank yourself!!

Language without OO at all - what about Logo - drive that little 
tortoise around!!

Cheers,
Neil
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tuple slices

2005-01-26 Thread Nick Coghlan
jfj wrote:
Jeff Shannon wrote:

So, what problem is it, exactly, that you think you'd solve by making 
tuple slices a view rather than a copy?

I think views are good for
 1) saving memory
 2) saving time (as you don't have to copy the elements into the new tuple)
1. Applies only if you are making large slices, or a lot of slices with each 
containing at least 3 elements.
  A view can also *cost* memory, when it looks at a small piece of a large 
item. The view will keep the entire item alive, even though it needs only a 
small piece.

2. Hell no. The *elements* aren't copied, pointers to the elements are. If you 
*don't* copy the pointers, then every item access through the view involves an 
indirection as the index into the original sequence gets calculated.

So views *may* save memory in some applications, but are unlikely to save time 
in any application (except any saving resulting from the memory saving).

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: string.atoi and string.atol broken?

2005-01-26 Thread TZOTZIOY
On Wed, 26 Jan 2005 02:10:44 +0100, rumours say that "Fredrik Lundh"
<[EMAIL PROTECTED]> might have written:

>Mike Moum wrote:

>> s.atoi('4',3) should result in 11
>>
>> s.atoi('13',4) should result in 31
>>
>> s.atoi('12',4) should result in 30
>>
>> s.atoi('8',4) is legitimate, but it generates an error.
>>
>> Is this a bug, or am I missing something obvious?

>the function's named "atoi", not "atoitoa".



s.itoa(4,3) should result in '11'
s.itoa(13,4) should result in '31'
s.itoa(12,4) should result in '30'
s.itoa(8,4) should result in '20'

s.atoi('4', 3) should fail
s.atoi('13', 4) should result in 7
s.atoi('12', 4) should result in 6
s.atoi('8', 4) should fail

 :)
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string.atoi and string.atol broken?

2005-01-26 Thread Peter Otten
Peter Otten wrote:

> def itoa(n, base):
>  assert 2 <= base <= 16
>  if n < 0:
>  digits = ["-"]
>  n = -n
>  else:
>  digits = []
>  while n:
>  n, m = divmod(n, base)
>  digits.append(string.hexdigits[m])
>  digits.reverse()
>  return "".join(digits)

This is junk, sorry. Doesn't handle n<=0 correctly (at least).

Peter

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


Re: string.atoi and string.atol broken?

2005-01-26 Thread Peter Otten
Christos TZOTZIOY Georgiou wrote:

> On Wed, 26 Jan 2005 08:58:45 +0100, rumours say that Peter Otten
> <[EMAIL PROTECTED]> might have written:
> 
>>By the way, does anyone know the Greek name for 36?
> 
> triakontahexadecimal would be a nice compromise of greek and the
> "hexadecimal" convention of having six before ten -- "???" ("hexi") is
> six, "" ("deka") is ten, "?" ("triakonta") is thirty.  I
> think in ancient Greek sometimes units came before tens, just like in
> German (another similarity is the verb in the end of the sentence, as
> Mark Twain also noted sometime in a humourous article AFAIR.)
> 
> In current Greek hexadecimal is "" ("dekaexadikon").

The Latin part escaped me. Now we need unicode names in Python, and the fun
can really begin.

I had you in mind with my question, thank you. 

Peter

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


Re: Tuple slices

2005-01-26 Thread Nick Coghlan
jfj wrote:
Actually, i think that slices with step, is a bad feature in general
and i think I will write a PEP to suggest their removal in python3k.
I wouldn't bother. Extended slicing was added to support those doing serious 
numerical work in Python, and it won't get removed for all the reasons it was 
added in the first place.

Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


wx.Image: Couldn't add an image to the image list.

2005-01-26 Thread Laszlo Zsolt Nagy
I would like to load image from a directory right into an image list.
I wrote a simple library that loads the images in the directory and
resizes them as needed before adding to the wx.ImageList.
This is not the same code but some snippets.
I resize the image this way (using Python Imaging Library):
def resizeimage(image,newsize):
  oldsize = (image.GetWidth(),image.GetHeight())
  if oldsize != newsize:
  return piltoimage(resizepil(imagetopil(image),newsize))
  else:
  return image
This is how I convert images to a bitmaps:
bmp = wx.BitmapFromImage(image,depth=depth)
I have a directory with 16x16 bmp images in it. Everything works fine 
for sizes
16x16 and below. When I try to use a bigger size (say, 32x32) I get the 
following
message:

Couldn't add an image to the image list.
It is repeated for every image. (I used wx.PySimpleApp.) There is the 
same problem
when I try to force 8bit color depth.  Where is the problem? Is this 
related to my
Windows XP platform?

Best,
 Laci  2.0
p.s.: I wonder why it is not named wx.BitmapList since one can only 
store wx.Bitmap instances in it. Late sorrow. :-)

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


Re: threading.py Condition wait overflow error

2005-01-26 Thread Mark English
> Date: Wed, 26 Jan 2005 00:10:31 -0500
> From: Tim Peters <[EMAIL PROTECTED]>
> The most common cause for "impossible exceptions"
> is flawed C code in an extension that fails to 
> check a Python C API call for an error return.
Yes, I use a lot of C modules which I wrote. It could certainly be one
of them (although which one could be an interesting challenge to find
out). It may even have something to do with moving to the VC7.1
compiler.

Thank you very much for your suggestion. Without it I would never have
thought to look at that code.

Mark


---
The information contained in this e-mail is confidential and solely 
for the intended addressee(s). Unauthorised reproduction, disclosure, 
modification, and/or distribution of this email may be unlawful. If you 
have received this email in error, please notify the sender immediately 
and delete it from your system. The views expressed in this message 
do not necessarily reflect those of LIFFE Holdings Plc or any of its subsidiary 
companies.
---

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


Re: Question: "load"ing a shared object in python

2005-01-26 Thread Simon Brunning
On Tue, 25 Jan 2005 23:19:01 +0200, Pro Grammer <[EMAIL PROTECTED]> wrote:
> Hello, all,
> I am not sure if this is the right place to ask, but could you kindly
> tell me how to "load" a shared object (like libx.so) into python, so
> that the methods in the .so can be used? That too, given that the shared
> object was written in c++, compiled with g++ ?

Will ctypes do the trick?

http://starship.python.net/crew/theller/ctypes/

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "pickle" vs. f.write()

2005-01-26 Thread Peter Maas
Johan Kohler schrieb:
class person:
name =""
age = 0
friends=[]
comment=""
me = person()
Otherwise, what is the best "Python" way to write and read this data  
structure?
import pickle
class person:
name =""
age = 0
friends=[]
comment=""
me = person()
# store
pf = file('/tmp/pickletest', 'w')
pickle.dump(me, pf)
pf.close()
# load
pf = file('/tmp/pickletest', 'r')
me2 = pickle.load(pf)
pf.close()
This is sequential access. If you want to have random access, look
for shelve.
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: add indexes on the fly to lists

2005-01-26 Thread Diez B. Roggisch
> If you want only "search and found" element, look dictionnary ; if you
> want also to have the order, see the module set.

Erg - no. Sets are mathematically defined as having no order. 

-- 
Regards,

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


Re: string.atoi and string.atol broken?

2005-01-26 Thread Fredrik Lundh
Christos TZOTZIOY Georgiou wrote:

>>the function's named "atoi", not "atoitoa".
>
> 

cool.  can I have a copy of your script?

reminds me that I have a few patches in the inqueue.  I wonder
what this one does? ;-)

hmm ;-)  guess I can tune that later ;-)  and what about that other
patch? ;-) let's see ;-)  patch, checkout, reload File "effbot.py", line 29238
<<< .mine
 ^
IndentationError: expected an indented block 



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


Re: OT

2005-01-26 Thread Diez B. Roggisch
> However, i know for a fact that phr is _not_ a user at
> sextans.lowell.edu.
> 
> Is this a problem with my dns?

Most probably - he shows up as [EMAIL PROTECTED] for me.
-- 
Regards,

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


Re: OT

2005-01-26 Thread phr
"Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
> > Is this a problem with my dns?
> 
> Most probably - he shows up as [EMAIL PROTECTED] for me.

It's my news client configuration.  Normally I post from a different
machine but that one is temporarily down.  I haven't bothered to
configure this one properly because I didn't expect to have to be
using it this long.  I don't want to keep posting from this machine
for long, so if the other machine is going to stay down, I'll figure
out some other alternative.  Sorry for this weirdness.

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


FTP Server

2005-01-26 Thread michele . simionato
What's the simplest way to write an FTP Server in Python?
A short research on the newsgroup and on the Cookbook did not
bring out anything relevant (but I hear a little voice in the
back of my head saying Twisted, Twisted! ...)
Michele Simionato

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


Re: execute python code from db

2005-01-26 Thread Laszlo Zsolt Nagy
robert wrote:
Hello,
Anybody knows if it's possible to execute python code from an db.
db=MySQLdb.connect(host="localhost",user="r",passwd="j",db="v")
c=db.cursor()
c.execute("""SELECT * FROM table
   WHERE id = %s""", (id,))
for python_code in c.fetchall():
   execute (python_code)
Maybe feed python with stdin??.
 

http://docs.python.org/lib/built-in-funcs.html
Look for these:
   compile
   exec
   eval
   execfile
Also the statement exec:
http://docs.python.org/ref/exec.html#l2h-562
I also recommend to look at the documentation of  "global","globals" 
before you try to use them.

Best,
  Laci 2.0
--
http://mail.python.org/mailman/listinfo/python-list


Re: execute python code from db

2005-01-26 Thread Damjan
> for python_code in c.fetchall():
> execute (python_code)
> 
> Maybe feed python with stdin??.

eval

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


Re: python without OO

2005-01-26 Thread Peter Maas
Davor schrieb:
so initially I was hoping this is all what Python is about, but when I 
started looking into it it has a huge amount of additional (mainly OO) 
stuff which makes it in my view quite bloated now.
So you think f.write('Hello world') is bloated and file_write(f,'Hello 
world')
is not? This is the minimum amount of OO you will see when using Python. But
I guess you will use OO in the long run to *avoid* bloated code:
--snip---
print  "*** Davor's evolution towards an OO programmer ***"
print '\n*** Step 1: OO is evil, have to use atomic variables:'
name1 = 'Smith'
age1 = 35
sex1 = 'male'
name2 = 'Miller'
age2 = 33
sex2 = 'female'
print name1, age1, sex1, name2, age2, sex2
print '\n*** Step 2: This is messy, put stuff in lists:'
p1 = ['Smith', 35, 'male']
p2 = ['Miller', 33, 'female']
for e in p1:
print e
for e in p2:
print e
print '\n*** Step 3: Wait ..., p[2] is age, or was it sex? Better take a dict:'
p1 = dict(name = 'Smith', age = 35, sex = 'male')
p2 = dict(name = 'Miller', age = 33, sex = 'female')
for e in p1.keys():
print '%s: %s' % (e, p1[e])
for e in p2.keys():
print '%s: %s' % (e, p2[e])
print '\n*** Step 4: Have to create person dicts, invoice dicts, ...better use 
dict templates:'
class printable:
def __str__(self):
'''magic method called by print, str() ..'''
ps = ''
for e in self.__dict__.keys():
ps += '%s: %s\n' % (e, str(self.__dict__[e]))
return ps
class person(printable):
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
class invoice(printable):
def __init__(self, name, product, price):
self.name = name
self.product = product
self.price = price
per = person(name = 'Smith', age = 35, sex = 'male')
inv = invoice(name = 'Smith', product = 'bike', price = 300.0)
print per
print inv
--snip---
Either your program is small. Then you can do it alone. Or you will
reach step 4.
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: FTP Server

2005-01-26 Thread John Abel
[EMAIL PROTECTED] wrote:
If you're after a simple FTP server, have a look at medusa.
   

Uhm ... Medusa does not seem actively maintained nowadays.
 M.S.
 

AFAIK, it's maintained to the extent, that if you find bugs/enhance it 
and let the medusa-dev list know, it more than likely will get fixed/added.

For what it's worth, I have a medusa-based FTP server running on Linux 
(daemon) and Win32 (service), without any problems at all.

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


Re: HAVE YOU HEARD THE GOOD NEWS!

2005-01-26 Thread StvB
I felt very evil after trying to figure out why my py program wouldn't work 
when I began a year ago:
I do Delphi at work, and at home I was missing the () after the functions. 
I was ready to sell my sou.. well nevermind.. it's all good now.

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Good News!
>
>
> Do you know how simple it is to go to Heaven after this life has ended?
>
>
> Some people believe that belonging to a local church, temple, mosque or
> synagogue will get them to Heaven.
>
>
> Others believe that water baptism, obeying the ten commandments or just
> being a good person will get them to Heaven.
>
>
> There are many other beliefs as well, but the good news about God's way
> to Heaven is found in the Holy Bible.
>
>
> The good news is that God came from Heaven to earth in the person of
> Jesus Christ over 2000 years ago and died for our sins(misdeeds). He
> was born in the land of Israel supernaturally to a virgin Jewish woman
> named Mary. He lived a sinless life for thirty-three years and then
> sacrificed His sinless blood and died on a cross to pay the death
> penalty for our sins. After Jesus was placed in a tomb He rose from the
> dead three days later as He said He would. The Holy Bible also tells us
> that Jesus Christ ascended into Heaven and that all who accept Him as
> their Lord and Saviour will live forever with Him in Heaven where there
> is no more death, sorrow, sickness and pain.
>
>
> The Bible says, "For the wages of sin is death, but the gift of God is
> eternal life through Christ Jesus our Lord." (Romans 6:23)
>
>
> This verse in the Bible says, "For ALL HAVE SINNED, and come short of
> the glory of God." (Romans 3:23)
>
>
> This verse says, "But God demonstrates his own love for us in this:
> While we were still sinners, Christ died for us." (Romans 5:8)
>
>
> In this passage the Bible clearly explains how simple it is to be saved
> and on your way to Heaven, "For if you confess with your mouth, "Jesus
> is Lord," and believe in your heart that God raised him from the dead,
> you WILL BE SAVED." (Romans 10:9)
>
>
> You can be saved right now and on your way to Heaven if you will open
> your heart to Jesus and pray the following prayer:
>
> Dear Jesus Christ, I want to be saved so that I can have a home in
> Heaven when I die. I agree with You that I am a sinner.
> I believe You love me and want to save me. I believe that You bled and
> died on the cross to pay the penalty for my sins. I believe that You
> rose from the dead. Please forgive my sins and come into my heart and
> be my Lord and Saviour. Thank You Lord Jesus Christ for forgiving me
> and saving me through Your merciful grace. Amen.
>
>
> You are now a Christian if you said the prayer and allowed God to save
> you. Welcome to the family of God.
>
>
> Salvation is not a reward but a gift. The Bible says it this way, "For
> it is by GRACE you have been SAVED, through FAITH and this not from
> yourselves, it is the GIFT of God." (Ephesians 2:8)
>
>
> Nothing in the world is more important than your eternal destiny.
>
>
> The Bible says, "In Him(Jesus) we have redemption through His blood,
> the forgiveness of sins..." (Ephesians 1:7)
>
>
> If you have not yet made a decision to be saved, please do so now
> before it is too late. The reason why it is so important to be saved
> now is because you do not know exactly when you will die. You may die
> prematurely in a traffic accident, terrorist attack or some other way
> before you get another chance to be saved.
>
>
> The Bible tells us that we will spend eternity in Heaven or a place of
> eternal torment called Hell. It would be terrible to die and go to Hell
> when all you have to do is accept Jesus Christ as your personal Lord
> and Saviour.
>
>
> Some people that have already made Jesus Christ their Lord and Saviour
> worry about losing their salvation. The Bible teaches Christians that
> we can never lose our salvation no matter what happens.
>
>
> The Bible says it this way, "My dear children, I write this to you so
> that you will not sin. But if anybody does sin, we have one who speaks
> to the Father in our defense Jesus Christ, the Righteous One."
>
>
> Yes my friend, Jesus Christ is able to save you and keep you saved.
>
>
> Please tell your family and friends, thanks!
>
>
> Have a great day!
> Internet Evangelist R.L. Grossi
>
>
>
>
>
> 1. http://www.biblegateway.com << Free Online Bible
> 2. http://www.free-hoster.com/goodnews << Passion of the Christ
> 3. http://www.carm.org/cults/cultlist.htm << Beware Of Cults
> 4. http://www.equip.org/free/DH198.htm << About Hell
> 5. http://www.powertochange.com/questions/qna2.html << Is Jesus God?
> 


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


Re: is there better 32 clock() timing?

2005-01-26 Thread Stephen Kellett
In message <[EMAIL PROTECTED]>, Bengt Richter
<[EMAIL PROTECTED]> writes
>>QueryPerformanceCounter is 47 times slower to call than clock() on my
>>1Ghz Athlon.
>That really makes me wonder. Perhaps the Athlon handles RDTSC by way of
>an illegal instruction trap and faking the pentium instruction?

No. Athlon implements it correctly- if it didn't you'd end up in the
debugger with an illegal instruction trap - you don't. Also my stats
below show that Athlon's RDTSC is faster than Pentium's which I doubt
you'd get if you were faking things. Taking it further - the test to see
if a processor supports RDTSC is to wrap it in an exception handler and
execute the instruction - if it doesn't you end up in the __except part
of the SEH handler.

QueryPerformanceCounter and RDTSC are not the same thing.
QueryPerformanceCounter talks to hardware to get its results. I imagine
that differences in performance for QueryPerformanceCounter are down to
how the HAL talks to the hardware and can't be blamed on the processor
or manufacturer.

clock() gets its info from the OS at (I imagine) the same granularity as
the NT scheduler. Some systems schedule at 10ms/11ms others at about 6ms
or 7ms. I think this is to do with single/dual processors - unsure as I
don't have a dual processor box. If you call GetThreadTimes() you will
find values returned that match the approx clock() values - which is why
I think they are related.

I've just run some tests using the same old program. QPC is
QueryPerformanceCounter. QPF is QueryPerformanceFrequency. I've included
the QPC/QPF column to show the timings in seconds.

1Ghz Athlon, Windows XP, SP2 1,000,000 iterations
QPC QPC/QPF (seconds)
QueryPerformanceCounter 7156984 5.998233
GetThreadTimes5032770.421794
RDTSC 1034300.086684
clock()   1489090.124800

QPC QPC/QPF (seconds)
850Mhz Pentium III, W2K. 1,000,000 iterations
QueryPerformanceCounter 5652161 1.579017
GetThreadTimes  3608976 1.008222
RDTSC 8429500.235491
clock()   6998400.195511

The results surprise me - Pentium III clock() takes less time to execute
than Pentium III RDTSC!

It surprises me that the 850Mhz Pentium III QPC is faster than the 1Ghz
Athlon QPC, but whichever way you slice it, QPC is massively slower than
RDTSC or clock(). Also surprising is the W2K GetThreadTimes is so slow
compared to the Athlon GetThreadTimes().

>of the timer chip that drives the old 55ms clock that came from IBM
>using cheap TV crystal based oscillators instead of defining an
>OS-implementer-friendly time base, I think. The frequency was nominally
>1193182 hz I believe. Obviously the OS didn't get interrupted that often,
>but if you divide by 2**16, you get the traditional OS tick of ~55ms:

I though that was the Windows 9x way of doing things. You get the 49 day
wrap around with this one I think.

>you can't expect to control ignition of a racing engine reliably with
>an ordinary windows based program ;-)

...and Schumacher is in the lead, oh look! The Ferrari has blue
screened. The new regulations to reduce speeds in F1 are working, that
has really slowed him down...

Stephen
-- 
Stephen Kellett
Object Media Limitedhttp://www.objmedia.demon.co.uk
RSI Information:http://www.objmedia.demon.co.uk/rsi.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: FTP Server

2005-01-26 Thread John Abel
If you're after a simple FTP server, have a look at medusa.
Regards
John
[EMAIL PROTECTED] wrote:
What's the simplest way to write an FTP Server in Python?
A short research on the newsgroup and on the Cookbook did not
bring out anything relevant (but I hear a little voice in the
back of my head saying Twisted, Twisted! ...)
Michele Simionato
 

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


execute python code from db

2005-01-26 Thread robert
Hello,

Anybody knows if it's possible to execute python code from an db.

db=MySQLdb.connect(host="localhost",user="r",passwd="j",db="v")

c=db.cursor()
c.execute("""SELECT * FROM table
WHERE id = %s""", (id,))

for python_code in c.fetchall():
execute (python_code)

Maybe feed python with stdin??.


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


4suite XSLT thread safe ?

2005-01-26 Thread Ola Natvig
Anybody out there who knows if the 4suite implementation of XSLT are a 
threadsafe one?

--
--
 Ola Natvig <[EMAIL PROTECTED]>
 infoSense AS / development
--
http://mail.python.org/mailman/listinfo/python-list


Re: FTP Server

2005-01-26 Thread michele . simionato

Do you have a code snippet/pointer so I have an idea of how to use it?
M.S.

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


Re: FTP Server

2005-01-26 Thread michele . simionato
> If you're after a simple FTP server, have a look at medusa.
Uhm ... Medusa does not seem actively maintained nowadays.

  M.S.

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


Re: execute python code from db

2005-01-26 Thread Nick Coghlan
robert wrote:
Hello,
Anybody knows if it's possible to execute python code from an db.
db=MySQLdb.connect(host="localhost",user="r",passwd="j",db="v")
c=db.cursor()
c.execute("""SELECT * FROM table
WHERE id = %s""", (id,))
for python_code in c.fetchall():
execute (python_code)
Maybe feed python with stdin??.
What's wrong with the exec statement?
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: "pickle" vs. f.write()

2005-01-26 Thread Johan Kohler
Thanks... works like a charm :-)
On Wed, 26 Jan 2005 12:55:38 +0100, Peter Maas <[EMAIL PROTECTED]> wrote:
Johan Kohler schrieb:
class person:
name =""
age = 0
friends=[]
comment=""
 me = person()
 Otherwise, what is the best "Python" way to write and read this data   
structure?
import pickle
class person:
 name =""
 age = 0
 friends=[]
 comment=""
me = person()
# store
pf = file('/tmp/pickletest', 'w')
pickle.dump(me, pf)
pf.close()
# load
pf = file('/tmp/pickletest', 'r')
me2 = pickle.load(pf)
pf.close()
This is sequential access. If you want to have random access, look
for shelve.

--
Using Opera's revolutionary e-mail client: http://www.opera.com/m2/

Please find our disclaimer at http://www.ukzn.ac.za/disclaimer

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


PyCon: Early Bird Deadline two days away [really]!

2005-01-26 Thread Steve Holden
Pythonistas:
If you have been putting off your registration, stop putting it off!
Last year the early bird deadline was extended because we were a little 
late getting the program together. This year the program was published 
two weeks in advance of the deadline for early bird registrations, which 
is JANUARY 28 (and it's already January 26).

So, don't delay: save yourself $75 and register by midnight Friday. 
Which time zone, you ask. Why wait and find out - it only takes a couple 
of minutes to register.

http://www.python.org/pycon/2005/register.html
regards
Steve Holden
Chairman, PyCON DC 2005
--
PyCon DC 2005: The third Python Community Conference
http://www.pycon.org/   http://www.python.org/pycon/
The scoop on Python implementations and applications
--
http://mail.python.org/mailman/listinfo/python-list


Freeze with wxpython on python 2.3 or python 2.4 on Win32 with Thread

2005-01-26 Thread Tsubasa[Hokage]
first problem:

With Idle environnement under Win32, all freeze after with bunch of
code:

#!/usr/bin/python
import threading,time

class T (threading.Thread) :
def __init__(self,_a,_b) :
threading.Thread.__init__(self)
self.a = _a
self.b = _b
def run(self) :
print "T(%d,%d)"%(self.a,self.b)
time.sleep(3)
print "T(%d,%d)=>%d"%(self.a,self.b,self.a+self.b)
return self.a+self.b

t = T(3,5)
t.start()


All freeze when sleep command are execute.
Second part of this problem, I have a GUI in wxpython, when I create
new thread i can't write new data in widget like a multibox when i am
in a thread :( but i can retrieve data ( GetValue works but SetValue
freeze ).

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


Re: 4suite XSLT thread safe ?

2005-01-26 Thread Diez B. Roggisch
Ola Natvig wrote:

> Anybody out there who knows if the 4suite implementation of XSLT are a
> threadsafe one?

What do you mean by that? You can of course transform xml using xslt in as
many threads as you like - but what do you want with two or more threads in
_one_ transformation? You start it, and some time later the result is
there.

-- 
Regards,

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


fast list lookup

2005-01-26 Thread Klaus Neuner
Hello,

what is the fastest way to determine whether list l (with
len(l)>3) contains a certain element?


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


Re: fast list lookup

2005-01-26 Thread Simon Brunning
On Wed, 26 Jan 2005 06:45:29 -0800 (PST), Klaus Neuner
<[EMAIL PROTECTED]> wrote:
> what is the fastest way to determine whether list l (with
> len(l)>3) contains a certain element?

If the list isn't sorted, I doubt you'll do better than

if an_element in my_list:
# do whatever

If the list is sorted, have a look at the bisect module.

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 4suite XSLT thread safe ?

2005-01-26 Thread Istvan Albert
Diez B. Roggisch wrote:
What do you mean by that? You can of course transform xml using xslt in as
many threads as you like 
It is not unthinkable that some parts of the library would not be
threadsafe. They could have some internal shared global variable
that keeps track of an intermediate state.
Some C string processing functions are not thread safe either.
Istvan.
--
http://mail.python.org/mailman/listinfo/python-list


Re: 4suite XSLT thread safe ?

2005-01-26 Thread Ola Natvig
Diez B. Roggisch wrote:
Ola Natvig wrote:

Anybody out there who knows if the 4suite implementation of XSLT are a
threadsafe one?

What do you mean by that? You can of course transform xml using xslt in as
many threads as you like - but what do you want with two or more threads in
_one_ transformation? You start it, and some time later the result is
there.
If a thread that are using a XSLT processor looses the GIL within the 
transformation process and another one starts processing on the same 
processor will this work?

Will the half-way finished thread be in the way of the one starting the 
processing before the stoped thread are done.

I think that's what I ment. Can a XSLT processor object be shared 
between multiple threads?

--
--
 Ola Natvig <[EMAIL PROTECTED]>
 infoSense AS / development
--
http://mail.python.org/mailman/listinfo/python-list


Re: fast list lookup

2005-01-26 Thread Alex Martelli
Klaus Neuner <[EMAIL PROTECTED]> wrote:

> what is the fastest way to determine whether list l (with
> len(l)>3) contains a certain element?

"if thecertainelement in l:"

is the fastest way unless there are properties of l which you're not
telling us about, or unless what you need is not just to determine
whether l contains a certain element but rather something different
(such as doing the same determination for several elements on an
unchanging l).


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


Re: 4suite XSLT thread safe ?

2005-01-26 Thread Ola Natvig
Istvan Albert wrote:
Diez B. Roggisch wrote:
What do you mean by that? You can of course transform xml using xslt 
in as
many threads as you like 

It is not unthinkable that some parts of the library would not be
threadsafe. They could have some internal shared global variable
that keeps track of an intermediate state.
Some C string processing functions are not thread safe either.
Istvan.
It looks like there are some problems with multiple threads accessing 
the the processor 'at once', think I'll write som kind of syncronizing 
wrapper or supply multiple processors to the threads.

--
--
 Ola Natvig <[EMAIL PROTECTED]>
 infoSense AS / development
--
http://mail.python.org/mailman/listinfo/python-list


Re: 4suite XSLT thread safe ?

2005-01-26 Thread Diez B. Roggisch
> It is not unthinkable that some parts of the library would not be
> threadsafe. They could have some internal shared global variable
> that keeps track of an intermediate state.
> Some C string processing functions are not thread safe either.

While the only one how can answer this is Uche himself, I'm confident that
this is not the case - modern OO-style apis associate state usually on a
per-object base. And 4suite is heavily OO-styled.

-- 
Regards,

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


Re: fast list lookup

2005-01-26 Thread Marco Aschwanden
what is the fastest way to determine whether list l (with
len(l)>3) contains a certain element?
Either a sorted list (in conjunction with the bisect-module) or a  
dictionary is your friend...

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


Re: fast list lookup

2005-01-26 Thread Kent Johnson
Klaus Neuner wrote:
Hello,
what is the fastest way to determine whether list l (with
len(l)>3) contains a certain element?
If you can use a set or dict instead of a list this test will be much 
faster.
Kent
--
http://mail.python.org/mailman/listinfo/python-list


Re: 4suite XSLT thread safe ?

2005-01-26 Thread Diez B. Roggisch
> If a thread that are using a XSLT processor looses the GIL within the
> transformation process and another one starts processing on the same
> processor will this work?
> 
> Will the half-way finished thread be in the way of the one starting the
> processing before the stoped thread are done.
> 
> I think that's what I ment. Can a XSLT processor object be shared
> between multiple threads?

No  - as a simple test reveals:

#The identity transform: duplicates the input to output
TRANSFORM = """http://www.w3.org/1999/XSL/Transform"; version="1.0">


  

  



"""

#And I don't even like Monty Python, folks
SOURCE1 = """What do you mean "bleah
SOURCE2 = """I don't like spam"""

import threading
from Ft.Xml.Xslt import Processor
processor = Processor.Processor()
import time, sys
from Ft.Xml import InputSource

transform = InputSource.DefaultFactory.fromString(TRANSFORM,
"http://spam.com/identity.xslt";)

processor.appendStylesheet(transform)

#Now the processor is prepped with a transform and ccan be used
#over and over for the same transform
results = []
source = InputSource.DefaultFactory.fromString(SOURCE1,
"http://spam.com/doc1.xml";)
source2 = InputSource.DefaultFactory.fromString(SOURCE2,
"http://spam.com/doc2.xml";)
threading.Thread(target=lambda:
results.append(processor.run(source))).start()
# comment the following line to make things crash.
time.sleep(5)
threading.Thread(target=lambda:
results.append(processor.run(source2))).start()

time.sleep(5)
print results


-- 
Regards,

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


Sorry for the multiple posts !!

2005-01-26 Thread Jose Rivera
My broswser stoped working when I posted, and I tought it didn't work,
so I tried a more times until did not report an error.

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


Re: 4suite XSLT thread safe ?

2005-01-26 Thread Diez B. Roggisch
> While the only one how can answer this is Uche himself, I'm confident that
> this is not the case - modern OO-style apis associate state usually on a
> per-object base. And 4suite is heavily OO-styled.

I should have added that this means that using a api like 4suite where you
can get a processor for one transformation, it should be safe to get
another one in another thread for another transformation, as this is the
preceived use case.

-- 
Regards,

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


Re: is there better 32 clock() timing?

2005-01-26 Thread Peter Hansen
Stephen Kellett wrote:
that time.clock() is inaccurate.  The problem is that the "time.clock()"
statement takes several hundred microseconds to execute.
The statement is incorrect. clock() itself isn't slow, but it is 
accessing a resource, the accuracy of which is no better than 1ms.

There are various timers available, documented and undocumented, all of 
which end up at 1ms or 1.1ms, give or take. For anything shorter you 
need QueryPerformanceCounter() (but that *is* a slow call), or use the 
RDTSC instruction which is fast but gives a count of instruction cycles 
executed and is thus not totally accurate (multiple execution pipelines, 
plus multithreading considerations).
(I've read the five or so following messages you and Bengt
have posted, but not in detail so I'm not sure where you're
going with all this, but... )
According to the docs for time.clock(), "On Windows, this function returns
wall-clock seconds elapsed since the first call to this function, as a floating
 point number, based on the Win32 function QueryPerformanceCounter(). The
resolution is typically better than one microsecond."
Depending on whether you really meant "accuracy" above, and
on other things, this is either irrelevant, or contradicts
your first statement...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


detect tk mainloop

2005-01-26 Thread John Hunter

In matplotlib using the tkagg backend, the tk mainloop is started at
the end of a python script by issuing a call to a "show" function,
which realizes all the created figure windows and the calls
Tkinter.mainloop().  This can cause problems if the mainloop was
started by another module (eg idle).

Is there a way to query tkinter to detect whether the mainloop has
already been called?

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


cookielib and urllib2: thread-safe?

2005-01-26 Thread Alex Hunsley
I'm writing a test script in python for pulling web pages from a web 
server using urllib2 and cookielib. Since the main thing I am testing is 
what happens when concurrent requests are made to the web server, I need 
to make several requests concurrently, which I'll do from different 
threads in my python script. So the important question is: are cookielib 
and urllib2 thread safe? Are there any precautions that apply to using 
these libs in a multi-threaded context?

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


Re: smtplib bug with Windows XP

2005-01-26 Thread Peter Hansen
Steve Christensen wrote:
In article <[EMAIL PROTECTED]>, [EMAIL PROTECTED] wrote:
thank Peter, elbert, for the suggestions.  I hadn't thought of using
telnet to try to connect to the SMTP server.  and when I do try, telnet
can't connect either, at least on port 25.  On port 110, it has no
problem.  So, perhaps the IT people have made some configuration
changes; I'll have a chat with them.  I'm relieved that it's not a
Python problem, though.
We had similar issues when our systems were upgraded to McAfee VirusScan
8.0. If you're running that locally (on the system trying to connect to
the SMTP server), try disabling the rule in the Access Control dialog
that's labeled 'Prevent mass mailing worms from sending email'
How do such tools still allow the sending of valid emails?
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: python without OO

2005-01-26 Thread Thomas Bartkus

"Davor" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> > On the other hand, this does beggar for a reason to bother with Python
at
> > all.  It seems you could be happy doing BASH scripts for Linux or DOS
batch
> > files for Windows.  Both are "nice&simple" scripting languages free of
> > object oriented contamination.
>
> not really, what I need that Python has and bash&dos don't is:
>
> 1. portability (interpreter runs quite a bit architectures)
> 2. good basic library (already there)
> 3. modules for structuring the application (objects unnecessary)
> 4. high-level data structures (dictionaries & lists)
> 5. no strong static type checking
> 6. very nice syntax
>
> so initially I was hoping this is all what Python is about, ...

The irony here is that the OO approach woven into the warp and woof of
Python is what make 1-6 possible.

> but when I
> started looking into it it has a huge amount of additional (mainly OO)
> stuff which makes it in my view quite bloated now...

Again, there is nothing "additional" about the OO in Python.  It is the very
foundation upon which it is built.

> ... anyhow, I guess
> I'll have to constrain what can be included in the code through
> different policies rather than language limitations...
It would be reasonable to decide that Python is not what you are looking
for.
I'm not sure that castrating it in this manner would be quite so reasonable.

Thomas Bartkus


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


Re: Tuple slices

2005-01-26 Thread George Sakkis
"Bengt Richter" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> On Wed, 26 Jan 2005 11:55:59 -0800, jfj <[EMAIL PROTECTED]> wrote:
>
> >Jeff Shannon wrote:
> >
> >>
> >>
> >> So, what problem is it, exactly, that you think you'd solve by making
> >> tuple slices a view rather than a copy?
> >>
> >
> >I think views are good for
> >  1) saving memory
> >  2) saving time (as you don't have to copy the elements into the new tuple)
> >
> >And they are worth it. However, (as in other cases with slicing), it is
> >very easy and fast to create a view for a slice with the default step
> >'1', while it's a PITA and totally not worth it to create a view for a
> >slice with non default step. I think it would be good to:
> >
> >  if slice_step == 1
> >create_view
> >  else
> >create_new_tuple
> >
> >Actually, i think that slices with step, is a bad feature in general
> >and i think I will write a PEP to suggest their removal in python3k.
> >
> What's the big deal with other than 1 steps? It is just adjusting a few 
> numbers
> so that you can either index the new virtual slice with an integer and return 
> the
> element, in which case the index into the original tuple will be
> someoffset+i*somefactor once you get past the limit checks for the virtual
> slice. By the same token, transforming a few numbers of one virtual slice
> into similar numbers for a a new virtual slice of that shouldn't be rocket 
> science.
> And it wouldn't have to be done more than once.  Don't have time to do it now,
> but there are plenty around here that could, I'm sure.
>
> Regards,
> Bengt Richter

Here's my (undocumented) version of it: 
http://rafb.net/paste/results/HkxmHp37.html
and its unit test: http://rafb.net/paste/results/2LIInT68.html

And some useless timing comparisons (I know it's a stupid example, don't flame 
me for this):

$ python /usr/lib/python2.3/timeit.py \
-s "x=tuple(xrange(1))" \
"[x[1:-1] for n in xrange(100)]"
10 loops, best of 3: 3.84e+04 usec per loop

$ python /usr/lib/python2.3/timeit.py \
-s "from immutableseq import ImmutableSequence" \
-s "x=ImmutableSequence(xrange(1))" \
"[x[1:-1] for n in xrange(100)]"
100 loops, best of 3: 5.85e+03 usec per loop

Feel free to comment or suggest improvements.

George



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


Re: FTP Server

2005-01-26 Thread Kartic
Michele -

Listen to your inner voice :-)

If simple is all you want, try twisted. You can use mktap to create a
simple ftp server and be ready to serve in a few minutes. And if you
are upto it, get buried in the documents and you can customize your ftp
server.

If you are looking for something simpler but not asynchronous, I found
this at the Vault called pyFTPDrop, which is aimed at *NIX.

http://www.mythi.cx/python/pyFTPdrop.py

/
Thank you,
--Kartic
PS: I am sure Medusa is fairly straightforward too, but I have no
experience with it.

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


access private field in python 2.4

2005-01-26 Thread [EMAIL PROTECTED]
Hello,
I'm new to python,
How can I access private field in python.

thanks

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


re.search - just skip it

2005-01-26 Thread rasdj
Input is this:

SET1_S_W CHAR(1) NOT NULL,
SET2_S_W CHAR(1) NOT NULL,
SET3_S_W CHAR(1) NOT NULL,
SET4_S_W CHAR(1) NOT NULL,
;

.py says:

import re, string, sys
s_ora = re.compile('.*S_W.*')
lines = open("y.sql").readlines()
for i in range(len(lines)):
try:
if s_ora.search(lines[i]): del lines[i]
except IndexError:
open("z.sql","w").writelines(lines)

but output is:

SET2_S_W CHAR(1) NOT NULL,
SET4_S_W CHAR(1) NOT NULL,
;

It should delete every, not every other!

thx,

RasDJ

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


Help With Python

2005-01-26 Thread Judi Keplar

I am currently taking a course to learn Python and was looking for
some help.  I need to write a Python statement to print a comma-
separated repetition of the word, "Spam", written 511 times ("Spam,
Spam, … Spam").

Can anybody help me get started?  I am completely new to programming!

Thanks in advance!



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


Wow!

2005-01-26 Thread Bernie


That is clever, gives a lot of insight into how the __dict__ == the
object.


This is somewhat like the solution I am using from the Cookbook, an
Empty object copy.   This is cleaner and very much more concise.
Thank you!

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


Re: access private field in python 2.4

2005-01-26 Thread Ola Natvig
[EMAIL PROTECTED] wrote:
Hello,
I'm new to python,
How can I access private field in python.
thanks
In python there realy are not private fields. There are those fields 
that you start with a double underline (__) theese are translated to

 ___
Withouth the < and > markers, but there are not good practice to access 
theese through that name.

--
--
 Ola Natvig <[EMAIL PROTECTED]>
 infoSense AS / development
--
http://mail.python.org/mailman/listinfo/python-list


Re: re.search - just skip it

2005-01-26 Thread Duncan Booth
 wrote:

> Input is this:
> 
> SET1_S_W CHAR(1) NOT NULL,
> SET2_S_W CHAR(1) NOT NULL,
> SET3_S_W CHAR(1) NOT NULL,
> SET4_S_W CHAR(1) NOT NULL,
> ;
> 
> .py says:
> 
> import re, string, sys
> s_ora = re.compile('.*S_W.*')
> lines = open("y.sql").readlines()
> for i in range(len(lines)):
> try:
> if s_ora.search(lines[i]): del lines[i]
> except IndexError:
> open("z.sql","w").writelines(lines)
> 
> but output is:
> 
> SET2_S_W CHAR(1) NOT NULL,
> SET4_S_W CHAR(1) NOT NULL,
> ;
> 
> It should delete every, not every other!

No, it should delete every other line since that is what happens if you use 
an index to iterate over a list while deleting items from the same list. 
Whenever you delete an item the following items shuffle down and then you 
increment the loop counter which skips over the next item.

The fact that you got an IndexError should have been some sort of clue that 
your code was going to go wrong.

Try one of these:
  iterate backwards
  iterate over a copy of the list but delete from the original
  build a new list containing only those lines you want to keep

also, the regex isn't needed here, and you should always close files when 
finished with them.

Something like this should work (untested):

s_ora = 'S_W'
input = open("y.sql")
try:
lines = [ line for line in input if s_ora in line ]
finally:
input.close()

output = open("z.sql","w")
try:
output.write(str.join('', lines))
finally:
output.close()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help With Python

2005-01-26 Thread Thomas Guettler
Am Wed, 26 Jan 2005 15:55:28 + schrieb Judi Keplar:

> 
> I am currently taking a course to learn Python and was looking for 
> some help.  I need to write a Python statement to print a comma-
> separated repetition of the word, "Spam", written 511 times ("Spam, 
> Spam, … Spam").
> 
> Can anybody help me get started?  I am completely new to programming!

Hi,

# This way, there is a comma after the last:
import sys
for i in range(511):
sys.stdout.write("Spam, ")

# No comma at the end:
mylist=[]
for i in range(511):
mylist.append("Spam")
print ", ".join(mylist)

 Thomas

-- 
Thomas Güttler, http://www.thomas-guettler.de/


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


Re: Help With Python

2005-01-26 Thread Peter Maas
Judi Keplar schrieb:
I am currently taking a course to learn Python and was looking for 
some help.  I need to write a Python statement to print a comma-
separated repetition of the word, "Spam", written 511 times ("Spam, 
Spam, … Spam").

Can anybody help me get started?  I am completely new to programming!
Online:
- http://www.python.org/moin/BeginnersGuide (Beginner, Advanced)
- http://www.freenetpages.co.uk/hp/alan.gauld/ (Beginner)
- http://docs.python.org/tut/tut.html (Beginner)
- http://diveintopython.org/ (Advanced)
Books (Look for most recent editions):
- Mark Lutz, Learning Python (Beginner)
- Alex Martelli, Python in a Nutshell (Beginner, Advanced)
- Frederik Lundh, Python Standard Library (Beginner, Advanced)
- Alex Martelli, Python Cookbook (Beginner, Advanced)
- Mark Pilgrim Dive Into Python (Advanced)
--
---
Peter Maas,  M+R Infosysteme,  D-52070 Aachen,  Tel +49-241-93878-0
E-mail 'cGV0ZXIubWFhc0BtcGx1c3IuZGU=\n'.decode('base64')
---
--
http://mail.python.org/mailman/listinfo/python-list


Re: re.search - just skip it

2005-01-26 Thread Fredrik Lundh
<[EMAIL PROTECTED]> wrote:

> but output is:
>
> SET2_S_W CHAR(1) NOT NULL,
> SET4_S_W CHAR(1) NOT NULL,
>
> It should delete every, not every other!

for i in range(len(lines)):
try:
if s_ora.search(lines[i]): del lines[i]
except IndexError:
...

when you loop over a range, the loop counter is incremented also if you delete
items.  but when you delete items, the item numbering changes, so you end up
skipping over an item every time the RE matches.

to get rid of all lines for which s_ora.search matches, try this

lines = [line for line in lines if not s_ora.search(line)]

for better performance, get rid of the leading and trailing ".*" parts of your
pattern, btw.  not that it matters much in this case (unless the SQL state-
ment is really huge).

 



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


Re: import hook, overwrite import?

2005-01-26 Thread Kartic
Hi Torsten,

If you want to use other methods to import (other than good ole file
system), yes, you can create an importer class and register it as an
importer module, that import will use to search and import.

For example, it is possible to use zip imports (this functionality is
already builtin) to import from a zip archive.
py>>> import zlib # required
py>>> import sys
py>>> sys.path.append('/location/to/zippedmodules.zip')
py>>> import testzip
py>>> testzip.__file__
'/location/to/zippedmodules.zip/testzip,py'

To generally do it, you have to:
1. Create a class that provides a load_module method that returns a
module type.
2.  Install your class as a hook using
sys.path_hooks.append(your_importer_class)

Please take a look at the imp module :
http://docs.python.org/lib/module-imp.html for a complete description
on accessing the import internals. There is also a simple example in
this section.

Is this is what you are looking for?

Thanks,
--Kartic
PS: This about how much I know...the more I find out, I will share :-)

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


Re: limited python virtual machine (WAS: Another scripting language implemented into Python itself?)

2005-01-26 Thread Alexander Schremmer
On Tue, 25 Jan 2005 22:08:01 +0100, I wrote:

 sys.safecall(func, maxcycles=1000)
> could enter the safe mode and call the func.

This might be even enhanced like this:

>>> import sys
>>> sys.safecall(func, maxcycles=1000,
 allowed_domains=['file-IO', 'net-IO', 'devices', 'gui'],
 allowed_modules=['_sre'])

Every access to objects that are not in the specified domains are
restricted by the interpreter. Additionally, external modules (which are
expected to be not "decorated" by those security checks) have to be in the
modules whitelist to work flawlessy (i.e. not generate exceptions).

Any comments about this from someone who already hacked CPython?

Kind regards,
Alexander
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help With Python

2005-01-26 Thread Simon Brunning
On Wed, 26 Jan 2005 15:55:28 -, Judi Keplar
<[EMAIL PROTECTED]> wrote:
> I am currently taking a course to learn Python and was looking for
> some help.  I need to write a Python statement to print a comma-
> separated repetition of the word, "Spam", written 511 times ("Spam,
> Spam, â Spam").
> 
> Can anybody help me get started?  I am completely new to programming!

Well, I don't want to give it to you on a plate, since it's homework,
but you might find this page useful:
.

I'd also suggest that you have a run through the tutorial -
. It's time well spent! If you don't get
on with that, there's another couple of tutorials available aimed
directly at those new to programming -
 and
.

Lastly, although neophytes are more than welcome here, you might find
the tutor mailing list a good place to ask questions in the early days
of your Python experience. You'll find it here -
.

Good luck, and welcome to Python!

-- 
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
--
http://mail.python.org/mailman/listinfo/python-list


Re: re.search - just skip it

2005-01-26 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
Input is this:
SET1_S_W CHAR(1) NOT NULL,
SET2_S_W CHAR(1) NOT NULL,
SET3_S_W CHAR(1) NOT NULL,
SET4_S_W CHAR(1) NOT NULL,
;
.py says:
import re, string, sys
s_ora = re.compile('.*S_W.*')
lines = open("y.sql").readlines()
for i in range(len(lines)):
try:
if s_ora.search(lines[i]): del lines[i]
When you delete for example lines[0], the indices of the following lines change. So the former 
lines[1] is now lines[0] and will not be checked.

The simplest way to do this is with a list comprehension:
lines = [ line for line in lines if not s_ora.search(line) ]
Even better, there is no need to make the intermediate list of all lines, you 
can say
lines = [ line for line in open("y.sql") if not s_ora.search(line) ]
In Python 2.4 you don't have to make a list at all, you can just say
open("z.sql","w").writelines(line for line in open("y.sql") if not 
s_ora.search(line))
;)
Kent
except IndexError:
open("z.sql","w").writelines(lines)
but output is:
SET2_S_W CHAR(1) NOT NULL,
SET4_S_W CHAR(1) NOT NULL,
;
It should delete every, not every other!
thx,
RasDJ
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help With Python

2005-01-26 Thread Will McGugan
Judi Keplar wrote:
I am currently taking a course to learn Python and was looking for 
some help.  I need to write a Python statement to print a comma-
separated repetition of the word, "Spam", written 511 times ("Spam, 
Spam, … Spam").

Can anybody help me get started?  I am completely new to programming!
Thanks in advance!
>>> print "Spam, " * 510 + "Spam"
Will McGugan
--
http://mail.python.org/mailman/listinfo/python-list


Re: module for 'po' files

2005-01-26 Thread David Fraser
Sara Fwd wrote:
 Hi all
Is there a module for processing & handling  '.po'
files in python?
If you want to do anything beyond standard gettext (which is handled by 
the gettext module) there's lots of code at translate.sourceforge.net ...

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


unknown protocol error when connecting to an server via ssl

2005-01-26 Thread christian_stengel

Hi *,

I have just started to learn python and I am having a problem with 
an python client connecting to a perl server using ssl (I tried this 
with pyOpenSSL and with the build in SSL Module).

I don't want to check a cerificate, so i simply tried a

from OpenSSL import SSL

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("127.0.0.1", 2000)

s.sendall("100 Hello\n")

ctx = SSL.Context(SSL.SSLv23_METHOD)
ctx.set_verify(SSL_VERIFY_NONE,self.verify_cb)
ss = SSL.Connection(ctx,s)
ss.set_connect_state()

ss.sendall("101 User\n")

when writeing the 101 I'll get an SSL23_GET_SERVER_HELLO 
unknown protocol error. If I don't do the ssl stuff, everything 
works.

I also tried this with the socket.ssl(s,None, None) to get a secure 
socket - but I got the same error.

The server is not written by me - so I can't change that to python.  
The problem is, that there is first an unencrypted socket, that is 
converted to a secure socket.

the perl (server) code is something like this:

# creating a socket
$socket = IO::Socket::INET->new(Listen => 5,
  LocalPort => 2000,
  Timeout => 15,
  Resue => 1,
  Proto => 'tcp');

# some more code

# accepting a remote connection
$session = $socket->accept;

# some more code

# convert the Socket to an ssl socket
$sslsocket = IO::Socket::SSL::socket_to_SSL($session,
  SSL_verify_mode => 0x00)

# some more code

 Does anybody know, where the UNKNOWN PROTOCOL error 
comes from? I have changed the connection Mode to 
SSLv2_METHOD but this gave me an GET_SERVER_HELLO 
read wrong packet type error.

I have done this with python 2.3.4 under linux - and the perl stuff 
is done via the IO-Socket-SSL package.

Thx,

Chris



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


Re: Help With Python

2005-01-26 Thread Will McGugan

 >>> print "Spam, " * 510 + "Spam"
Or if you have 2.4..
>>> print ", ".join( "Spam" for _ in xrange( 511 ) )
Although, the replys with links will ultimately be more helpful!
Will McGugan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help With Python

2005-01-26 Thread Kartic
Py>>> print "Spam, " * 115
Spam, Spam, Spam, Spam, Spam, . Spam,

Multiplies (repeats) the string 115 times.

To eliminate the last ", " (that is, a comma followed by space), you
can do it using the slice notation and say:
Py>>> print ("Spam, " * 115) [:-2]
Spam, Spam, Spam, Spam, Spam, ., Spam

The [:-2] means that you asking Python to print everything from the
beginning to the last but two characters of the string. You can also
write this as [0:-2]

[or [0:length_of_spam - 2] where length_of_spam = len("Spam, " * 115)]

Since you are starting off, please read and follow the tuturial that
available with your Python installation or on the Python.org site at
http://docs.python.org/tut/tut.html

Thank you,
--Kartic

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


Re: Help With Python

2005-01-26 Thread Steven Bethard
Thomas Guettler wrote:
Am Wed, 26 Jan 2005 15:55:28 + schrieb Judi Keplar:

I am currently taking a course to learn Python and was looking for 
some help.  I need to write a Python statement to print a comma-
separated repetition of the word, "Spam", written 511 times ("Spam, 
Spam, ï Spam").

Can anybody help me get started?  I am completely new to programming!

Hi,
# This way, there is a comma after the last:
import sys
for i in range(511):
sys.stdout.write("Spam, ")
# No comma at the end:
mylist=[]
for i in range(511):
mylist.append("Spam")
print ", ".join(mylist)
# also no comma at the end, using a list comprehension
print ", ".join(["Spam" for _ in xrange(511)])
# also no comma at the end, using a generator expresssion (Python 2.4)
print ", ".join("Spam" for _ in xrange(511))
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: Help With Python

2005-01-26 Thread Kent Johnson
Thomas Guettler wrote:
# No comma at the end:
mylist=[]
for i in range(511):
mylist.append("Spam")
or just
mylist = ["Spam"] * 511
Kent
print ", ".join(mylist)
 Thomas
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >