ANN: PyComicsViewer-0.7 released

2005-01-11 Thread ionutz
PyComicsViewer-0.7 has been released

What is PyComicsViewer?
===

Is a comics viewer written in python, PyGTK and PIL. I made it as I
didn't fully like any of the existing viewers and I wanted something
that works the same (nice) way on both Linux and Windows.

Because of the way it was implemented, you can also use it like a kind
of image browser/viewer, but this is not its primary destination.
Browsing images from uncompressed directories is provided because
resulted naturally from the implementation and because I've seen some
people that distribute their scaned comics uncompressed.

What's new in version 0.7?
==

This is the first public release of the viewer. 90% of the
functionality is already in place. Some things need better
implementation and some are still to be implemented. However, you
should be able to read cbr and cbz files with it.

Licensing
=

PyComicsViewer is released under the GPL.

Where can I get it?
===

You can download it from:
http://borco.net/html/PyComicsViewer/

Cheers,

Ionutz

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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: python3: 'where' keyword

2005-01-11 Thread Paul Rubin
Steve Holden [EMAIL PROTECTED] writes:
 Well I for one disagreed with many of your estimates of the zen's
 applicability to macros, but I just couldn't be arsed saying so.

Well, I was being somewhat flip with them, as I felt Carl was being
snotty in referring me to the Zen list.  The point there is that one
can interpret each of the Zen points in many ways regarding macros.  I
don't feel there's a conflict between macros and the Zen list.  Macros
in Python are a deep subject and gurus have been discussing them for a
long time.  I think that with PyPy it will become easier to experiment
with possible approaches.  In other posts I've suggested a moratorium
on new Python syntax until after PyPy is deployed.

  An amazing amount of the headaches that both newbies and experienced
  users have with Python, could be solved by macros It's not clear
  what the best way to do design them is, but their existence can have a
  profound effect on how best to do these ad-hoc syntax extensions like
  where.  
 This is not a justifiable assertion, IMHO, and if you think that
 newbies will have their lives made easier by the addition of ad hoc
 syntax extensions then you and I come from a different world (and I
 suspect the walls might be considerably harder in mine than in yours).

I'm saying that many proposals for ad hoc extensions could instead be
taken care of with macros.  Newbies come to clpy all the time asking
how to do assignment expressions, or conditional expressions, or
call-by-reference.  Sometimes new syntax results.  Lots of times,
macros could take care of it.

 I don't really understand why, if macros are so great (and you are
 reading the words of one who was using macros back in the days of
 Strachey's GPM) why somebody doesn't produce a really useful set of
 (say) M4 macros to prove how much they'd improve Python.

You can't really do Python macros with something like M4.  How would
M4 even generate multi-line output that's indented to the right depth
for the place where the macro was called?  How would you write an
m4 macro like cond(x,y,z) that does the equivalent of (x ? y : z)?
Even if you could, it doesn't begin to address the hassle of running
Python scripts through m4 before you can execute the scripts, especially
in an interactive environment.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python serial data aquisition

2005-01-11 Thread Flavio codeco coelho
[EMAIL PROTECTED] (Michael Fuhr) wrote in message news:[EMAIL PROTECTED]...
 If the actual byte and/or bit order is different then you'll have
 to modify the expression, but this should at least give you ideas.

Hi Michael, 

It all looks pretty god but there is a couple of things I still don't
understand, 1) in Steve's solution (which seems equivalent to your
own), he does the masking, shifts by seven, and then  sums the two
numbers while you, instead of summing, use a logical or. How can these
operations be equivalent? or are they? Is the logical or  equivalent
to a concatenation?

2) why 7? why do we have shift 7 bits? is that so the 8th bit on byte
one is aligned with the first bit on the second byte?

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


Re: Python serial data aquisition

2005-01-11 Thread Bengt Richter
On 9 Jan 2005 14:13:28 -0800, [EMAIL PROTECTED] (Flavio codeco coelho) wrote:

Hi,

I am using pyserial to acquire data from an A/D converter plugged to
my serial port.

my hardware represents analog voltages as 12bit numbers. So, according
to the manufacturer, this number will be stored in two bytes like
this;
 |-bits(1-8)---|
Byte1: x  x   x   n1 n2 n3   n4   n5
Byte2: x  n6 n7 n8 n9 n10 n11 n12

where x is some other information, and nx are the digits of my number.

My problem is to how to recover my reading from these bytes, since
pyserial gives me a character (string) from each byte... I dont know
how to throw away the   unneeded bits and concatenate the remaining
bits to form a number...

The others have shown how to recover a 12 bit positive value 0 through 4095,
but if the number is signed, and you want the signed value, you'll have to
find out how signed numbers are represented. An offset is common, in which
case you would subtract 2048 (2**11). If it's two's complement by some chance,
you'll want  (I think -- untested ;-) to do num -= 2*(num2048) instead of 
always num -= 2048

If you need speed in converting large strings of byte pairs, you could
convert pairs of bytes with the array module ('H' for unsigned 2-byte numbers)
and use the resulting 16-bit numbers as indices into another array of final 
values
prepared beforehand with redundant information that will accomplish the effect
of masking and shifting and adjusting sign.

If you need this speed, volunteers will magically appear. Maybe even if you 
don't ;-)

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


Re: PyChecker messages

2005-01-11 Thread Roger Binns
 runner.py:878: Function (main) has too many lines (201)

 What does this mean? Cannot functions be large? Or is it simply an advice that
 functions should be small and simple?

It is advice.

 runner.py:200: Function (detectMimeType) has too many returns (11)

 The function is simply a long else-if clause, branching out to different
 return statements. What's wrong? It's simply a probably ugly code advice?

That is also advice.  Generally you use a dict of functions, or some other
structure to lookup what you want to do.

 _must_ take two arguments; is there any way that I can make 'frame' go away?

Yes, you can name it just _  (underscore).  There are a few other names like
that that are ignored.  (Check the doc).

 Also, another newbie question: How does one make a string stretch over several
 lines in the source code? Is this the proper way?

 print asda asda asda asda asda asda  \
 asda asda asda asda asda asda  \
 asda asda asda asda asda asda

Depends what you are trying to achieve.  Look at triple quoting as well.

Roger 


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


Re: Python serial data aquisition

2005-01-11 Thread Flavio codeco coelho
Paul Rubin http://[EMAIL PROTECTED] wrote in message news:[EMAIL 
PROTECTED]...
 or something like that.

Hi Paul,

thanks for your answer.
I Noticed, however that although your solution is almost identical to
that of Michael (earlier in the thread) your masking for the second
byte is different than the one he used. Since hex numbers get me all
confused (and python doesn't convert to binary), I was wondering which
one is the correct masking...

thnaks,

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


Re: Handing a number of methods to the same child class

2005-01-11 Thread Steven Bethard
Dave Merrill wrote:
Somewhat silly example:
I know you've hedged this by calling it a silly example, but I would 
like to point out that your set_X methods are unnecessary -- since 
Python allows you to overload attribute access, getters and setters are 
generally unnecessary.

class Address:
def __init__():
self.displayed_name = ''
self.adr = ''
self.city = ''
self.state = ''
def set_name(name):
self.displayed_name = name
def set_adr(adr):
self.adr = adr
def set_city(city):
self.city = city
def set_state(state):
self.state = state
class Phone:
def __init__():
self.displayed_name = ''
self.number = ''
def set_name(name):
self.displayed_name = name
def set_number(number):
self.number = number
class Customer:
def __init__():
self.last_name = ''
self.first_name = ''
self.adr = Adr()
self.phone = Phone()
def set_adr_name(name):
self.adr.set_name(name)
def set_adr_adr(adr):
self.adr.set_adr(adr)
def set_adr_city(city):
self.adr.set_city(city)
def set_adr_state(state):
self.adr.set_state(state)
def set_phone_name(name):
self.phone.set_name(name)
def set_phone_number(number):
self.phone.set_number(number)
IOW, all the adr methods go to the corresponding method in self.adr, all the
phone methods go to self.phone, theorectically etc for other rich
attributes.
What I'd really like is to say, the following list of methods pass all
their arguments through to a method of the same name in self.adr, and the
following methods do the same but to self.phone. Is there some sane way to
express that in python?
py class Address(object):
... def __init__(self, city, state):
... self.city = city
... self.state = state
...
py class Customer(object):
... def __init__(self, name, addr):
... self.name = name
... self.addr = addr
... def __getattr__(self, attr):
... if attr.startswith('adr_'):
... return getattr(self.addr, attr[4:])
... raise AttributeError(attr)
...
py c = Customer(Steve, Address(Tucson, AZ))
py c.adr_city
'Tucson'
py c.adr_state
'AZ'
I've used a slightly different example from yours, but hopefully you can 
see how to apply it in your case.  The __getattr__ method is called when 
an attribute of an object cannot be found in the normal locations (e.g. 
self.__dict__).  For all attributes that begin with adr_, I delegate 
the attribute lookup to the self.addr object instead.

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


Re: Command line and GUI tools : need a single threading solution

2005-01-11 Thread Adrian Casey
Diez B. Roggisch wrote:

 I'm thinking it may be possible to modify the command line tools to use
 qt
 threads instead of native python threads.  Is this the way to go?  Are
 there other options?
 
 Why don't you use python threads in qt - I do so and so far it didn't make
 any troubles for me. And I would strongly advise against using qthreads
 with your commandline-tools, as these then would only run on machines
 where pyqt is installed - which opens a small part of dependency hell
 for your users.
 
I have a QThread which polls a queue object via queue.get().  The command
line tools spawn a number of threads each of which writes its output to
this queue using queue.put().  As soon as the gui gets something off the
queue, it creates a QCustomEvent and sets the data property with the data
read from the queue.  My application has a customEvent() method which reads
the data item from the customEvent and processes it accordingly.  

The odd thing is, I have a non-threaded version of the command line tools
which work 100% with the gui.  The multi-threaded version of the command
line tools all work OK at the console - just not with the gui.

I will try your suggestion and replace my QCustomEvent mechanism with a
plain python queue.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tuples vs lists

2005-01-11 Thread Antoon Pardon
Op 2005-01-10, Bruno Desthuilliers schreef [EMAIL PROTECTED]:
 Antoon Pardon a écrit :
 Op 2005-01-08, Bruno Desthuilliers schreef [EMAIL PROTECTED]:
 
worzel a écrit :

I get what the difference is between a tuple and a list, but why would I 
ever care about the tuple's immuutability?

Because, from a purely pratical POV, only an immutable object can be 
used as kay in a dict.

my-bad s/kay/key/ /my-bad

 This is not true.

 Chapter and verse, please ?

I don't need chapter and verse. I have already used mutable
objects as keys and it works just fine.

 class hlst(list):
  
  def __hash__(self):
sum = 0
for el in self:
  sum += hash(el)
return sum % 0x3777

 lst = hlst([3,5,7])
 lst
[3, 5, 7]
 lst[0] = 12
 lst
[12, 5, 7]
 d = {}
 d[lst] = 4

 
So you can use tuples for 'composed key'. 
 
 lists can be so used too. Just provide a hash.

 Please show us an example, and let's see how useful and handy this is 
 from a purely practical POV ?-)

It is handy from a pratical point of view when most operations you
do on your data are the equivalent of appending, deleting and changing
one element. Simulating these with tuples will cost you more than 
putting a copy of your list in the dictionary as a precaution against
accidently mutating a key.

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


Re: Python unicode

2005-01-11 Thread Radovan Garabik
Michel Claveau - abstraction mta-galactique non triviale en fuite 
perptuelle. [EMAIL PROTECTED] wrote:
 Hi !
 
 and plain Latin letters
 
 But not all letters  (no : etc.)
 

... and some more letters that are not latin (j,w,u,z)
ok, I'd better shut up :-)


-- 
 ---
| Radovan Garabk http://melkor.dnp.fmph.uniba.sk/~garabik/ |
| __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
 ---
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing huge Sets() to disk

2005-01-11 Thread Bengt Richter
On Mon, 10 Jan 2005 17:11:09 +0100, =?ISO-8859-2?Q?Martin_MOKREJ=A9?= [EMAIL 
PROTECTED] wrote:

Hi,
  I have sets.Set() objects having up to 20E20 items,
What notation are you using when you write 20E20?
IOW, ISTM 1E9 is a billion. So 20E20 would be 2000 billion billion.
Please clarify ;-)

each is composed of up to 20 characters. Keeping
them in memory on !GB machine put's me quickly into swap.
I don't want to use dictionary approach, as I don't see a sense
to store None as a value. The items in a set are unique.

  How can I write them efficiently to disk? To be more exact,
I have 20 sets. _set1 has 1E20 keys of size 1 character.

alphabet = ('G', 'A', 'V', 'L', 'I', 'P', 'S', 'T', 'C', 'M', 'A', 'Q', 'F', 
'Y', 'W', 'K', 'R', 'H', 'D', 'E')
for aa1 in alphabet:
# l = [aa1]
#_set1.add(aa1)
for aa2 in alphabet:
# l.append(aa2)
#_set2.add(''.join(l))
[cut]

  The reason I went for sets instead of lists is the speed,
availability of unique, common and other methods.
What would you propose as an elegant solution?
Actually, even those nested for loops take ages. :(

If you will explain a little what you are doing with these set items
perhaps someone will think of another way to represent and use your data.

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


Re: Securing a future for anonymous functions in Python

2005-01-11 Thread Jacek Generowicz
Jeff Shannon [EMAIL PROTECTED] writes:

 Jacek Generowicz wrote:
  Anna [EMAIL PROTECTED] writes:
 
 But first, wouldn't something like:
 
 [x+1 for x in seq]
 
 be even clearer?
  I'm glad you mentioned that. [...]
 
  As to whether it is clearer. That depends. I would venture to suggest
 
  that, given a pool of laboratory rats with no previous exposure to
  Python, more of them would understand the map-lambda than the list
  comprehension.
 
 
 I would venture to suggest the exact opposite, that the syntax of a
 list comprehension is in itself suggestive of its meaning, while 'map'
 and 'lambda' are opaque until you've researched them.

In the population of all laboratory rats, I think that the proportion
that would understand either form, would be as good as zero.

Given a population with previous exposure to computer programming, my
money is on the map-lambda version. But this last point is mostly
irrelevant. The fact is that you cannot program computers without
doing a bit of learning ... and the lambda, map and friends really do
not take any significant learning.

 Speaking for *this* laboratory rat, at least, map/lambda was always a
 nasty puzzle for me and difficult to sort out.  But when list comps
 were introduced, after reading just a sentence or two on how they
 worked, they were completely clear and understandable -- much more so
 than map/lambda after many months of exposure.

Forgetting about lambda, map, filter and reduce, do you find that you
pass callables around in your Python programs, or is this not
typically done in your programs?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Operating System???

2005-01-11 Thread Roose

 Huh?  I'm just baffled why you think writing a scheduler in an OS is
 harder than writing one in an application.  You have some means of
 doing a coroutine switch in one situation, and some means of doing a
 hardware context switch in the other.  Aside from that the methods are
 about the same.

Because of performance.  Task schedulers and device drivers tend to be
timing sensitive.  Go look up task schedular latency.  The longer your
scheduler spends trying to figure out which thread to run, the longer the
latency will be.

I mean in the worst case, if you are interpreting everything, what if you
change the task scheduler code?  Then an interrupt happens, and oh shit we
have to parse and recompile all the scheduling code.  Oh wait now we ran out
of kernel memory -- now we have to run the garbage collector!  Let your
interrupt wait, no?

It just seems nonsensical.  Maybe not impossible, as I've already said.  I
haven't tried it.  But go ahead and try it -- I would honestly be interested
in the results, all kidding aside.  It shouldn't be too time-consuming to
try, I suppose.  Get Python running in the Linux kernel, and then replace
the task scheduling algorithm with some Python code.  See how it works.  I
suspect you will degrade the performance of an average system significantly
or unacceptably.  But who knows, I could be wrong.

Of course, hardware is getting faster as you say.  But multitasking
performance is still an active and important area of OS research, and I
doubt that any designer of an OS (that is actually meant to be used) would
spend any cycles to have their task scheduler in Python -- and that will be
probably be true for a very long time.  Or maybe I'm wrong -- go bring it up
on comp.os.linux or whatever the relevant newsgroup is.  I'd like to hear
what they have to say.



 Why do you think there's anything difficult about doing this stuff in
 Python, given the ability to call low level routines for some hardware
 operations as needed?



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


Re: Python unicode

2005-01-11 Thread michele . simionato
Uhm ...

 class C(object):
... pass
...
 setattr(C, è, The letter è)
 getattr(C, è)
'The letter \xe8'

;-)

   Michele Simionato

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


Re: Command line and GUI tools : need a single threading solution

2005-01-11 Thread Adrian Casey
Phil Thompson wrote:

 I have a collection of multi-threaded command line tools which I want
 wrap a
 PyQt gui around.  I'm using queues to route messages from the command
 line tools to the PyQt gui. The command line tools use python threads to
 do
 their work.  The gui uses a QThread object to read incoming messages.

 This does not work consistently - and I've since read that mixing python
 threads and QThreads is a bad idea.  The command line tools work well
 using
 python threads.
 
 How well mixing the two threading APIs works depends on version numbers. A
 PyQt generated with SIP v4.x (rather than SIP v3.x) with Python v2.4
 should be Ok.
 
 I don't want to maintain two copies of the tools - one for command line
 and
 another for the PyQt version.

 I'm thinking it may be possible to modify the command line tools to use
 qt
 threads instead of native python threads.  Is this the way to go?  Are
 there other options?
 
 Using QThreads only should work - just tell the QApplication ctor that you
 have a console application.
 
 Phil
Phil,

I'm running python 2.4, sip-4.0 and PyQt-x11-gpl-3.11 (or .13 - not sure as
I'm not at work).

A little more detail.

My script, if invoked from the command line, creates a queue object (let's
call it logQueue) which is used to take the output from each individual
thread.  If invoked via the gui, the script is passed a logQueue created by
the gui.  Each thread dumps its output using logQueue.put().  There are
other queues which are used to service threaded access to a database etc.

The scripts use the pexpect module to login to remote systems and do
sysadmin tasks (e.g. reset passwords).  This works like a charm in console
mode.

The gui uses a QThread to poll logQueue (logQueue.get()).  When it gets
something, it creates a QCustomEvent and sets the data portion using the
data read from the logQueue.  I have a customEvent method in my application
which grabs the data from the customEvent and processes it accrodingly
(writing output to a QTable).

The gui locks up after an arbitrary number of rows have been inserted in the
QTable.  It is not consistent.  Sometimes it does not lock at all.

I have a non-threaded set of the command line tools which run perfectly with
the gui.

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


Re: Securing a future for anonymous functions in Python

2005-01-11 Thread michele . simionato
Jacek:
 Given a population with previous exposure to computer programming, my
 money is on the map-lambda version. But this last point is mostly
 irrelevant. The fact is that you cannot program computers without
 doing a bit of learning ... and the lambda, map and friends really do
 not take any significant learning.

This kind of sociological study would be pretty interesting to me ;-)

Personally, I find out that my mind manage pretty well one-level of
indirection
at time, not two. Consider for instance

def add1(x): return x+1
map(add1, mylist)

Here there are *two* levels of indirection:

first, I need to define add1;
second I need to translate mentally map to a loop.

Using lambda does not help:

map(lambda x: x+1, mylist)

still would require two levels for me, one to recognize the lambda
and one to convert map to a loop.

This is too much for me, so I just write

[x+1 for x in mylist]

where everything is explicit (or if you wish, I have just to recognize
that there
is a loop going on, pretty easy).

However, if I can skip a level of indirection (i.e. I do not need to
define
a function) I just prefer map:

map(int, mylist)

is simpler for me than

[int(x) for x in mylist]

since the latter introduces an useless x (which is also polluting my
namespace,
but this not my point, I could use a generator-expression instead).

So, in practice, I only use map with built-in or with predefined
functions, i.e. functions
which are already there for some other purpose; I do not like to be
forced to write a
function (or a lambda) for the only purpose of using map (at least in
Python).

Incidentally, I am not fond of the name lambda too. fn, as Paul
Graham says,
looks much better.

What I would like, in Python, is some facility to manage callbacks in
the standard
library, then I would live pretty well without lambdas.
Just IMHO, YMMV, etc.

  Michele Simionato

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


Re: Python unicode

2005-01-11 Thread michele . simionato
I forgot to add the following:

 setattr(C, è, uThe letter è)
 getattr(C, è)
u'The letter \xe8'
 print getattr(C, è)
The letter è

Python identifiers can be generic strings, including Latin-1
characters;
they cannot be unicode strings, however:

 setattr(C, uè, The letter è)
Traceback (most recent call last):
File stdin, line 1, in ?
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in
position 0: ordinal not in range(128)

So you are right after all, but I though most people didn't know that
you can have
valid identifiers with accented letters, spaces, and non printable
chars.

 setattr(C,  , this works)
 getattr(C,  )


Michele Simionato

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


Re: Statement local namespaces summary (was Re: python3: 'where' keyword)

2005-01-11 Thread Nick Coghlan
Nick Coghlan wrote:
Semantics
-
The code::
statement with:
   suite
translates to::
def unique_name():
suite
statement
unique_name()
Bleh. Not only was my proposed grammar change wrong, my suggested semantics are 
wrong, too.

Raise your hand if you can see the problem with applying the above semantics to 
the property descriptor example.

So I think the semantics will need to be more along the lines of pollute the 
namespace but mangle the names so they're unique, and the programmer can *act* 
like the names are statement local.

This will be much nicer in terms of run-time performance, but getting the 
locals() builtin to behave sensibly may be a challenge.

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


Re: PyChecker messages

2005-01-11 Thread Sylvain Thenault
On Tue, 11 Jan 2005 06:54:54 +, Frans Englich wrote:
 
 Hello,

Hi

 I take PyChecker partly as an recommender of good coding practice

You may alos be interested by Pylint [1].

Pylint is less advanced in bug detection than pychecker, but imho its good
coding practice detection is more advanced and configurable (as the pylint
author, i'm a little biased... ;), including naming conventions, code
duplication, bad code smells, presence of docstring, etc...


Side note : I wish that at some point we stop duplicated effort between
pylint and pychecker. In my opinion that would be nice if each one focus
on its strenghs (as i said bugs detection for pychecker and convention
violation / bad code smell for pylint). That would be even better if both
tools could be merged in one, but (at least last time I took a look at
pychecker) the internal architecture is so different that it's not an easy
task today. Any thoughts ?

[1] http://www.logilab.org/projects/pylint

-- 
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: Statement local namespaces summary (was Re: python3: 'where' keyword)

2005-01-11 Thread Andrey Tatarinov
Nick Coghlan wrote:
Semantics
-
The code::
statement with:
   suite
translates to::
def unique_name():
suite
statement
unique_name()
Bleh. Not only was my proposed grammar change wrong, my suggested 
semantics are wrong, too.

Raise your hand if you can see the problem with applying the above 
semantics to the property descriptor example.

So I think the semantics will need to be more along the lines of 
pollute the namespace but mangle the names so they're unique, and the 
programmer can *act* like the names are statement local.

This will be much nicer in terms of run-time performance, but getting 
the locals() builtin to behave sensibly may be a challenge.
afair you told yourself that
var = statement where:
suite
translates to:
def unique_name():
suite
return statement
var = unique_name()
in this case class gets unique_name() function? is it that bad?
anyway I'd prefer to change semantics deeper. adding new statement-only 
scope and adding our suite-definitions there.
--
http://mail.python.org/mailman/listinfo/python-list


python and macros (again) [Was: python3: 'where' keyword]

2005-01-11 Thread michele . simionato
Paul Rubin wrote:
 How about macros? Some pretty horrible things have been done in C
 programs with the C preprocessor. But there's a movememnt afloat to
 add hygienic macros to Python. Got any thoughts about that?

Movement seems quite an exaggeration. Maybe 2-3 people made some
experiments, but nobody within the core Python developers seems
to be willing to advocate the introduction of macros.

 Why should you care whether the output of a macro is ugly or not,
 if no human is ever going to look at it?

But at least some human eye have to look at it!
rethorical-question
Did you ever debug a macro?
/rethorical-question

More seriuosly, I have given some thought to the issue, and I am very
much against the introduction of macros in Python.

Here are a few reasons:

1. I like defmacro in Lisp. Problem is, Lisp is an s-expression based
language, Python is not. We cannot implement defmacro in Python and
even if we could, if would be too ugly to be used (at least, IMHO).

2. One could proposed hygienic pattern-matching macros in Python,
similar to
Scheme syntax-rules macros. Again, it is not obvious how to
implement pattern-matching in Python in a non-butt-ugly way. Plus,
I feel hygienic macros quite limited and not worth the effort.

3. We would add to Python the learning curve of macros and their
subtilities and we do not want it.

4. Macros would complicate a lot Python module system.

5. We have Guido providing a good syntax for us all, why we should be
fiddling with it? More seriously, if some verbosity is recognized
in the language (think to the raison d'etre of decorators, for
instance) I very much prefer to wait for Guido to take care of
that, once and for all, than having 100 different custom made
solutions based on macros.

I am sure I could find other reasons if I think a bit more, but these
should suffice for the moment ;)

What I would be interested in is a Lisp/Scheme implementation
compiling to Python bytecode, but I am not aware of any project
in that direction.


Michele Simionato

P.S. some pointers for people interested on the topic:

http://logix.livelogix.com/ (a Python-like language with macros)
https://sourceforge.net/projects/pymac/ (an experimental
Dylan-inspired macro system for Python)

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


Re: Port blocking

2005-01-11 Thread Mark Carter
Ed Leafe wrote:
On Jan 10, 2005, at 8:00 PM, Steve Holden wrote:

There isn't, IMHO, anything with the polish of (say) Microsoft Access, 
or even Microsoft SQL Server's less brilliant interfaces. Some things 
Microsoft *can* do well, it's a shame they didn't just stick to the 
knitting.

shameless plugThough it's certainly not anywhere near the polish 
of Access, you should check out Dabo.
Thanks. I'll look into it.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Statement local namespaces summary (was Re: python3: 'where' keyword)

2005-01-11 Thread Nick Coghlan
Nick Coghlan wrote:
Nick Coghlan wrote:
Semantics
-
The code::
statement with:
   suite
translates to::
def unique_name():
suite
statement
unique_name()
Bleh. Not only was my proposed grammar change wrong, my suggested 
semantics are wrong, too.

Raise your hand if you can see the problem with applying the above 
semantics to the property descriptor example.
Eh, never mind. The following works today, so the semantics I proposed are 
actually fine. (This is exactly the semantics proposed for the property example)

Py class C(object):
...   def _x():
... def get(self):
...   print Hi!
... def set(self, value):
...   print Hi again!
... def delete(self):
...   print Bye
... return property(get, set, delete)
...   x = _x()
...
Py C.x
property object at 0x009E6738
Py C().x
Hi!
Py C().x = 1
Hi again!
Py del C().x
Bye
Cheers,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: 20050110: string join, substring, length

2005-01-11 Thread Jürgen Exner
Xah Lee wrote:
[...]
 # perldoc -tf substr

Is there a specific reason why you are 'ugly-printing' the doc pages?
From 'perldoc perldoc':

-t text output
 Display docs using plain text converter, instead of nroff. This may
 be faster, but it won't look as nice.

jue 


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


Re: Statement local namespaces summary (was Re: python3: 'where' keyword)

2005-01-11 Thread Nick Coghlan
Andrey Tatarinov wrote:
afair you told yourself that
var = statement where:
suite
translates to:
def unique_name():
suite
return statement
var = unique_name()
in this case class gets unique_name() function? is it that bad?
No, I wasn't thinking clearly and saw problems that weren't there.
However, you're right that the semantic definition should include unbinding the 
unique name after the statement finishes. E.g. for assignments:

  def unique_name():
  suite
  return expr
  target = unique_name()
  del unique_name
anyway I'd prefer to change semantics deeper. adding new statement-only 
scope and adding our suite-definitions there.
A new scope essentially *is* a nested function :)
My main purpose with the nested function equivalent is just to make the intended 
semantics clear - whether an implementation actually _does_ things that way is 
immaterial.

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


Re: Securing a future for anonymous functions in Python

2005-01-11 Thread Bengt Richter
On Mon, 10 Jan 2005 21:15:50 -0500, Tim Peters [EMAIL PROTECTED] wrote:

...

[Anna]
 BTW - I am *quite* happy with the proposal for where: syntax - I
 think it handles the problems I have with lambda quite handily.

[Steve Holden]
 Whereas I find it to be an excrescence, proving (I suppose) that one
 man's meat is another person's poison, or something.

I've been waiting for someone to mention this, but looks like nobody
will, so I'm elected.  Modern functional languages generally have two
forms of local-name definition, following common mathematical
conventions.  where was discussed here.  The other is let/in, and
Well, I did say it reminded me of some kind of weird let ;-)
http://groups-beta.google.com/groups?q=%20Reminds%20me%20of%20some%20kind%20of%20weird%20lethl=enlr=sa=Ntab=wg

seems a more natural fit to Python's spelling of block structure:

let:
suite
in:
suite

There's no restriction to expressions here.  I suppose that, like the
body of a class, the `let` suite is executed starting with a
conceptually empty local namespace, and whatever the suite binds to a
local name becomes a temporary binding in the `in` suite (like
whatever a class body binds to local names becomes the initial value
of the class __dict__).  So, e.g.,

i = i1 = 3
let:
i1 = i+1
from math import sqrt
in:
print i1, sqrt(i1)
print i1,
print sqrt(i1)

would print

4 2
3

and then blow up with a NameError.

LIke it or not, it doesn't seem as strained as trying to pile more
gimmicks on Python expressions.
I could get to like it ;-)

Hm, a little extension to this could provide a new way to populate closure 
variables,
and also (never mind, one thing at a time ;-)

#1: If you gave your 'let' above a list of 'externs' that can be rebound from 
within the let.
E.g.,

let(sqrt):

the effect in your example would be to eliminate the NameError you mention.
The compiler would make an entry for sqrt in the enclosing namespace, and 
generate
code to bind/rebind if assigned from within the let.

This would be an interesting way to create closure bindings:

let(foo):
preset = 'another way to make closure vairables'
in:
def foo(): return preset
...
print foo()

#2: Making the in: suite callable as a light weight function with no arguments. 
An optional
binding name after in would bind like def and create a persistent named 
callable instead of just an
implicitly called anonymous suite.

Then you could define the same effective foo by

let:
preset = 'another way to make closure vairables'
in foo:
return preset  # return now legal 
...
print foo()

The combination would work like:

let(rebindable):
factor = 10
in bar:
rebindable *= factor

rebindable = 2
bar()
print rebindable  # = 20
rebindable += 5
bar()
print rebindable  # = 250

You can see this could be used nicely in case functionality, with a dict of 
named in-functions.

What do you think?

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


Re: Statement local namespaces summary (was Re: python3: 'where' keyword)

2005-01-11 Thread Nick Coghlan
Andrey Tatarinov wrote:
I think using 'with' keyword can cause some ambiguity. for example I 
would surely try to write

  x = a+b with self:
  b = member
and using with at the end of block brings more ambiguity:
  stmt1()
  stmt2()
  with self:
  member = stmt3()
compare to:
  stmt1()
  stmt2()
  with:
  variable = stmt3()
a way different semantics with just one word added/deleted.
Except that for a with expr: block, attributes of the expression must be 
preceded by a dot:

Py stmt1()
Py stmt2()
Py with self:
....member = stmt3()
The advantages of the 'with' block are that 'self' is only looked up once, and 
you only need to type it once. The leading dot is still required to disambiguate 
attribute references from standard name references.

Despite that, I think you are right that the ambiguity is greater than I first 
thought. Correct code is reasonably easy to distinguish, but in the presence of 
errors it is likely to be unclear what was intended, which would make life more 
difficult than it needs to be.

However, I still agree with Alex that the dual life of where outside of Python 
(as an 'additional definitions' clause, as in mathematics, and as a 
'conditional' clause, as in SQL), and the varied background of budding 
Pythoneers is a cause for concern.

'in' is worth considering, as it is already used by Python at least once for 
declaring use of a namespace (in the 'exec' statement). However, I suspect it 
would suffer from ambiguity problems similar to those of 'with' (consider 
expr in expr and expr in: expr). There's also the fact that the 
statement isn't *really* executed in the inner namespace - any name binding 
effects are seen in the outer scope, whereas 'exec x in dict' explicitly 
protects the containing namespace from alteration.

So of the four keywords suggested so far ('where', 'with', 'in', 'using'), I'd 
currently vote for 'using' with 'where' a fairly close second. My vote goes to 
'using' because it has a fairly clear meaning ('execute the statement using this 
extra information'), and doesn't have the conflicting external baggage that 
'where' does.

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


here document

2005-01-11 Thread Nader Emami
L.S.,
Would somebody help me how i can write the 'here document' in
Python script please? I have a csh script in which a program
is invoked with some argument in the form of here document:
/bin/exe.x  End_Here
CategorY   = GRIB
etc.
End_Here
I translate this script to Python and i don't know how can I
do this!
with regards,
Nader
--
http://mail.python.org/mailman/listinfo/python-list


Re: Statement local namespaces summary (was Re: python3: 'where' keyword)

2005-01-11 Thread Andrey Tatarinov
So of the four keywords suggested so far ('where', 'with', 'in', 
'using'), I'd currently vote for 'using' with 'where' a fairly close 
second. My vote goes to 'using' because it has a fairly clear meaning 
('execute the statement using this extra information'), and doesn't have 
the conflicting external baggage that 'where' does.
I should agree with you =)
Though I love with for historical reasons and addiction to functional 
languages using is not that bad and I do not mind using it. =)
--
http://mail.python.org/mailman/listinfo/python-list


Re: The limitation of the Photon Hypothesis

2005-01-11 Thread Jacek Generowicz
Steve Holden [EMAIL PROTECTED] writes:

 Steve Horsley wrote:

  Also, I think you probably accidentally posted to the wrong
  newsgroup.
 
 No, he deliberately posted to the wrong newsgroup.

Heh ... I initially read the subject line as The limitation of the
Python Hypothesis.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Securing a future for anonymous functions in Python

2005-01-11 Thread Nick Coghlan
Tim Peters wrote:
LIke it or not, it doesn't seem as strained as trying to pile more
gimmicks on Python expressions.
Some of us are piling gimmicks on statements, not expressions :)
And I'm looking for out-of-order code execution as well as local namespaces, so 
the let/in syntax wouldn't help much. (The out-of-order execution is what really 
makes the property definition example pretty, IMO)

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


Frameworks for database/forms applications?

2005-01-11 Thread Wolfgang Keller
Hello,

apart from GNUe (forms) and Dabo, what other Delphi-lookalike Python
frameworks are there for typical forms-oriented database applications?

It's not that the above mentioned are not enough for me, I just want to get
a candidate list that is as exhaustive as possible for my evaluation...

TIA,

Best regards

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


Upgraded to python2.3 but httpd taking old version

2005-01-11 Thread Gurpreet Sachdeva
I upgraded my python to 2.3 from 2.2 but Apache (V 2.0.4) is taking
old libraries for processing. I also made a soft link redirecting the
old files to new files but of no help... These error logs shows that
it is still using 2.2 :o(

[Tue Jan 11 16:18:45 2005] [error] [client 127.0.0.1] import cgi
[Tue Jan 11 16:18:45 2005] [error] [client 127.0.0.1]   File
/usr/lib/python2.2/cgi.py, line 38, in ?

Please help
-- Garry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Securing a future for anonymous functions in Python

2005-01-11 Thread Carl Banks
Tim Peters wrote:
 ...

 [Anna]
  BTW - I am *quite* happy with the proposal for where: syntax - I
  think it handles the problems I have with lambda quite handily.

 [Steve Holden]
  Whereas I find it to be an excrescence, proving (I suppose) that
one
  man's meat is another person's poison, or something.

 I've been waiting for someone to mention this, but looks like nobody
 will, so I'm elected. Modern functional languages generally have two
 forms of local-name definition, following common mathematical
 conventions.  where was discussed here.  The other is let/in, and
 seems a more natural fit to Python's spelling of block structure:

 let:
 suite
 in:
 suite

Ah.  During that discussion, I did kind of suggest this (spelling it
where...do) as an alternative to where (thinking I was clever).  Only
no one seemed to take notice, probably because I suggested something
more poignant at the same time.

Now I see why I liked the idea so much; it was exactly like let forms.


 There's no restriction to expressions here.  I suppose that, like the
 body of a class, the `let` suite is executed starting with a
 conceptually empty local namespace, and whatever the suite binds to a
 local name becomes a temporary binding in the `in` suite (like
 whatever a class body binds to local names becomes the initial value
 of the class __dict__).  So, e.g.,

 i = i1 = 3
 let:
 i1 = i+1
 from math import sqrt
 in:
 print i1, sqrt(i1)
 print i1,
 print sqrt(i1)

 would print

 4 2
 3

 and then blow up with a NameError.

 LIke it or not, it doesn't seem as strained as trying to pile more
 gimmicks on Python expressions.

Indeed.


-- 
CARL BANKS

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


Re: here document

2005-01-11 Thread Roland Heiber
harold fellermann wrote:
f = open(/bin/exe.x,w)
print f , CategoryY = GRIB
etc.

This would overwrite the existing /bin/exe.x ...
HtH, Roland
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python unicode

2005-01-11 Thread P
Michel Claveau - abstraction mta-galactique non triviale en fuite 
perptuelle. wrote:
Hi !
If  Python is Ok with Unicode, why the next script not run ?
# -*- coding: utf-8 -*-
 
def (toto):
return(toto*3)
Because the coding is only supported in string literals.
But I'm not sure exactly why. It would be nice to do:
import math
 = math.pi
--
Pdraig Brady - http://www.pixelbeat.org
--
--
http://mail.python.org/mailman/listinfo/python-list


Re: shutil.move has a mind of its own

2005-01-11 Thread Daniel Bickett
Oh, I'm sorry, that was my mistake. The example contained that error,
but my code does not.

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


Checking for X availability

2005-01-11 Thread Flavio codeco coelho
I have a program that uses pythondialog for its UI.

Pythondialog is a wrapper of the shell dialog and xdialog libs.

But I would like for it to switch between using Dialog ( when X is not
available )  and xdialog (when X is available)

So my question is: how can I check for the availability of X? i.e.,
How will my program know if its running in a text only console or in
console window over X?

thanks,

Flávio
-- 
http://mail.python.org/mailman/listinfo/python-list


[csv module] duplication of end of line character in output file generated

2005-01-11 Thread simon.alexandre
Hi all,

I use csv module included in python 2.3. I use the writer and encouter the
following problem: in my output file (.csv) there is a duplication of the
end of line character, so when I open the csv file in Ms-Excel a blank line
is inserted between each data line.

OS: W2k

Someone has an idea ?

thanks in advance

the source code is the following:

--
import csv

class CsvDumper:

   def __init__(self):
   self.object =
[['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']]
   self.writer = csv.writer(file(Test.csv, w))

   def DumpCsvFile(self):
  for row in self.object:
  self.writer.writerow(row)

c = CsvDumper()
c.DumpCsvFile()


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


Re: Uploading files

2005-01-11 Thread Peter Mott
Thanks for this.

Peter

Robert Brewer [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
Peter Mott wrote:
 If you upload a file using the cgi module is there any
 way to discover the file name that the user submitted
 as well as the file data? I've googled till I squint
 but I can't find anything.

Working example (for ASP, which uses BinaryRead to get the request
stream):

contentLength = int(env['CONTENT_LENGTH'])
content, size = request.BinaryRead(contentLength)

content = StringIO.StringIO(content)
form = cgi.FieldStorage(content, None, , env, True)
content.close()

for key in form:
value = form[key]

try:
filename = value.filename
except AttributeError:
filename = None

if filename:
# Store filename, filedata as a tuple.
self.requestParams[key] = (filename, value.value)
else:
for subValue in form.getlist(key):
self.requestParams[key] = subValue


Robert Brewer
MIS
Amor Ministries
[EMAIL PROTECTED] 


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


Re: [csv module] duplication of end of line character in output file generated

2005-01-11 Thread Peter Otten
simon.alexandre wrote:

 I use csv module included in python 2.3. I use the writer and encouter the
 following problem: in my output file (.csv) there is a duplication of the
 end of line character, so when I open the csv file in Ms-Excel a blank
 line is inserted between each data line.
 
 OS: W2k
 
 Someone has an idea ?
 
 thanks in advance
 
 the source code is the following:
 
 --
 import csv
 
 class CsvDumper:
 
def __init__(self):
self.object =
 [['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']]
self.writer = csv.writer(file(Test.csv, w))

Try opening the file in binary mode: file(Test.csv, wb)

 
def DumpCsvFile(self):
   for row in self.object:
   self.writer.writerow(row)
 
 c = CsvDumper()
 c.DumpCsvFile()

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


Re: Checking for X availability

2005-01-11 Thread Nils Nordman
On Tue, Jan 11, 2005 at 03:32:01AM -0800, Flavio codeco coelho wrote:
 So my question is: how can I check for the availability of X? i.e.,
 How will my program know if its running in a text only console or in
 console window over X?

Well, one way to do it is to check whether the environment variable
DISPLAY is set (which it is when running under X, and should not be
otherwise).

Cheers,

-- 
Nils Nordman [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: here document

2005-01-11 Thread Craig Ringer
On Tue, 2005-01-11 at 18:46, harold fellermann wrote:
 On 11.01.2005, at 11:34, Nader Emami wrote:
  Would somebody help me how i can write the 'here document' in
  Python script please? I have a csh script in which a program
  is invoked with some argument in the form of here document:
 
  /bin/exe.x  End_Here
  CategorY   = GRIB
  etc.
  End_Here
 
  I translate this script to Python and i don't know how can I
  do this!
 
 f = open(/bin/exe.x,w)
 print f , CategoryY = GRIB
 etc.
 

You mean os.popen not open I assume? The former opens a pipe to a
command, the latter overwrites the file.

I'd use:

os.popen(/bin/exe.x, w).write(\
CategorY   = GRIB
etc.
)
myself, but that's just taste (well, and performance I suspect).

--
Craig Ringer

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


Re: Architecture of Python was removed ?

2005-01-11 Thread Nick Coghlan
cr999 wrote:
 I found the Architecture of Python ( http://wiki.cs.uiuc.edu/cs427/PYTHON 
 By Jim Jackson, Kar-Han Tan )is very useful for my understanding of the 
 Python's architecture. But I found the link is not link to that document 
 today. It seems that the document was removed. Who knows what happened?
 
 Does anyone here have a copy of that document? Or who can tell me what is the 
 email address of Jim Jackson or Kar-Han Tan. 

http://web.archive.org/web/2003101953/http://wiki.cs.uiuc.edu/cs427/PYTHON

Cheers,
Nick.

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


Re: else condition in list comprehension

2005-01-11 Thread Nick Coghlan
Dan Bishop wrote:
Luis M. Gonzalez wrote:
Hi there,
I'd like to know if there is a way to add and else condition into a
list comprehension. I'm sure that I read somewhere an easy way to do
it, but I forgot it and now I can't find it...
for example:
z=[i+2 for i in range(10) if i%2==0]
what if I want i [sic] to be i-2 if i%2 is not equal to 0?

z = [i + (2, -2)[i % 2] for i in range(10)]
For the specific case of +/- a number, (-1) ** x works, too:
z = [i + 2 * ((-1) ** i) for i in range(10)]
Not that I'm claiming it's particularly readable or anything. . . just that it 
works :)

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


Re: SuSE 9.1: updating to python-2.4

2005-01-11 Thread Peter Otten
Torsten Mohr wrote:

 along with my distribution SuSE 9.1 came python 2.3.3.
 
 I'd like to update to 2.4 now, is this an easy thing to do
 or will lots of installed modules refuse to work then?
 
 Is there an easy way to find out what i need to update?

I shied away from a full upgrade and installed 2.4 from source just to play
around with it. This is painless if you use 

make altinstall

instead of 

make install

If you want Tkinter support you have to install the tk-devel package before
configuring 2.4.

One easy way to find out what depends on python is to mark python for
removal in yast, then click the [Abhängigkeiten prüfen] (check
dependencies) button -- and probably cancel the changes afterwards.

Peter

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


Re: [csv module] duplication of end of line character in output file generated

2005-01-11 Thread Kent Johnson
simon.alexandre wrote:
Hi all,
I use csv module included in python 2.3. I use the writer and encouter the
following problem: in my output file (.csv) there is a duplication of the
end of line character, so when I open the csv file in Ms-Excel a blank line
is inserted between each data line.
From the docs for csv.writer():
writer(  	csvfile[, dialect='excel'[, fmtparam]])
...If csvfile is a file object, it must be opened with the 'b' flag on platforms where that 
makes a difference.

Windows is a platform where that makes a difference. So try
  self.writer = csv.writer(file(Test.csv, wb))
Kent
OS: W2k
Someone has an idea ?
thanks in advance
the source code is the following:
--
import csv
class CsvDumper:
   def __init__(self):
   self.object =
[['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']]
   self.writer = csv.writer(file(Test.csv, w))
   def DumpCsvFile(self):
  for row in self.object:
  self.writer.writerow(row)
c = CsvDumper()
c.DumpCsvFile()

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


Re: [csv module] duplication of end of line character in output file generated

2005-01-11 Thread simon.alexandre
ok thanks
it works

S.


Kent Johnson [EMAIL PROTECTED] a écrit dans le message de
news:[EMAIL PROTECTED]
 simon.alexandre wrote:
  Hi all,
 
  I use csv module included in python 2.3. I use the writer and encouter
the
  following problem: in my output file (.csv) there is a duplication of
the
  end of line character, so when I open the csv file in Ms-Excel a blank
line
  is inserted between each data line.

  From the docs for csv.writer():
 writer(  csvfile[, dialect='excel'[, fmtparam]])
  ...If csvfile is a file object, it must be opened with the 'b' flag
on platforms where that
 makes a difference.

 Windows is a platform where that makes a difference. So try
self.writer = csv.writer(file(Test.csv, wb))

 Kent

 
  OS: W2k
 
  Someone has an idea ?
 
  thanks in advance
 
  the source code is the following:
 
  --
  import csv
 
  class CsvDumper:
 
 def __init__(self):
 self.object =
  [['la','mb','mc','md'],['ma','mb','mc','md'],['ma','mb','mc','md']]
 self.writer = csv.writer(file(Test.csv, w))
 
 def DumpCsvFile(self):
for row in self.object:
self.writer.writerow(row)
 
  c = CsvDumper()
  c.DumpCsvFile()
 
 


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


including folders with McMillan Installer

2005-01-11 Thread Linda Eyambe



Hi everyone,
After months of hacking i managed to get my python 
software to work properly, and have even managed to turn it into an exe with 
Mcmillan's Installer
(ran into a LookupError with py2exe so i tossed 
it).

Anyway, now i'm wondering how to include entire 
folders and their content into the distribution directory. I created a COLLECT 
subclass for each folder something like this:

coll1 = COLLECT ( [('file1.txt', 
'C:/my/folder1/file1', 'DATA')], 
  

 [('file2.txt', 'C:/my/folder1/file2', 
'DATA')],
 
...
 
name = folder1 )


coll2 = COLLECT ( [('file1.txt', 
'C:/my/folder2/file1', 'DATA')], 
 
name = folder2 )

I have to do that for each file and each folder i 
want to include. How can i do this more efficiently?

Also, when i run the exe by double-clicking on it 
directly from within the distribution directory it works fine, but once i create 
a shortcut or try to access it with the command-line eg C:/project/dist/project.exe it doesnt seem 
to be able to find the files that i imported with the COLLECT statement, even 
though in my source code all the file locations are relative. I get an error 
that goes something like... Cannot find the file or directory named 
'./icons/splash.bmp' although it is clearly there. 

Any ideas?

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

Exception not captured

2005-01-11 Thread Miki Tebeka
Hello All,

Can someone please explain how is the following code fragment possible?
(If you're interested I can place the whole project somewhere).

def checkout(dest, log):
'''Get latest version from SCM

client - SCM client to use
dest - Destination directory
'''
try:
SCM.checkout(dest, log)
except SCMError, e:
raise NightlyError(Checkout)
except Exception, e:
import inspect
file = inspect.getsourcefile(e.__class__)
line = inspect.getsourcelines(e.__class__)[1]
print %s:%d % (file, line)
file = inspect.getsourcefile(SCMError)
line = inspect.getsourcelines(SCMError)[1]
print %s:%d % (file, line)
print SCMError is e.__class__
raise SystemExit

I get to the second except clause, and the printout is:
/home/mikit/work/nightly/scm/common.py:3
/home/mikit/work/nightly/scm/common.py:3
False

How is this possible?
Bye.
--

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: Writing huve ge Sets() to disk

2005-01-11 Thread Batista, Facundo
Title: RE: Writing huve ge Sets() to disk





[Martin MOKREJ]


#- When importing data from a flatfile into mysql table, there's an
#- option to delay indexing to the very last moment, when all keys are
#- loaded (it doesn't make sense to re-create index after each new
#- row into table is added). I believe it's exactly same waste of cpu/io
#- in this case - when I create a dictionary and fill it with data,
#- I want to create index afterward, not after every key/value pair
#- is recorded.


Premature optimization is the root of all evil.. Use dict as is, profile all your code, start optimizing the slower parts, you'll never get to dicts.


. Facundo


Bitcora De Vuelo: http://www.taniquetil.com.ar/plog
PyAr - Python Argentina: http://pyar.decode.com.ar/



  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ADVERTENCIA.


La informacin contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener informacin confidencial o propietaria, cuya divulgacin es sancionada por la ley.

Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no est autorizado a divulgar, copiar, distribuir o retener informacin (o parte de ella) contenida en este mensaje. Por favor notifquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magntico) que pueda haber realizado del mismo.

Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefnica Comunicaciones Personales S.A. o alguna empresa asociada.

Los mensajes electrnicos pueden ser alterados, motivo por el cual Telefnica Comunicaciones Personales S.A. no aceptar ninguna obligacin cualquiera sea el resultante de este mensaje.

Muchas Gracias.



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

Re: fetching method names from a class, and the parameter list from a methodRe: fetching method names from a class, and the parameter list from a method

2005-01-11 Thread Philippe C. Martin
 import inspect
 help(inspect)


Thanks,

I have not seen the func params yet, but the default values are so 

Regards,

Philippe

-- 
***
Philippe C. Martin
SnakeCard LLC
www.snakecard.com
***

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


Re: Ranting about the state of Python IDEs for Windows

2005-01-11 Thread Nick Vargish
AkioIto [EMAIL PROTECTED] writes:

 Look at http://www.pspad.com/en/index.html.

Thanks for the tip, looks perfect for the flash memory toolkit, since
it can just run from the directory it was unpacked into. 

Nick

-- 
#  sigmask  ||  0.2  ||  20030107  ||  public domain  ||  feed this to a python
print reduce(lambda x,y:x+chr(ord(y)-1),' Ojdl!Wbshjti!=obwAcboefstobudi/psh?')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Exception not captured

2005-01-11 Thread Peter Otten
Miki Tebeka wrote:

 Hello All,
 
 Can someone please explain how is the following code fragment possible?
 (If you're interested I can place the whole project somewhere).
 
 def checkout(dest, log):
 '''Get latest version from SCM
 
 client - SCM client to use
 dest - Destination directory
 '''
 try:
 SCM.checkout(dest, log)
 except SCMError, e:
 raise NightlyError(Checkout)
 except Exception, e:
 import inspect
 file = inspect.getsourcefile(e.__class__)
 line = inspect.getsourcelines(e.__class__)[1]
 print %s:%d % (file, line)
 file = inspect.getsourcefile(SCMError)
 line = inspect.getsourcelines(SCMError)[1]
 print %s:%d % (file, line)
 print SCMError is e.__class__
 raise SystemExit
 
 I get to the second except clause, and the printout is:
 /home/mikit/work/nightly/scm/common.py:3
 /home/mikit/work/nightly/scm/common.py:3
 False
 
 How is this possible?

Some kind of duplicate import, maybe? E.g.:

 import sys
 import inspect
 getsource = inspect.getsource
 del sys.modules[inspect]
 import inspect
 getsource is inspect.getsource
False

Peter

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


Re: Locale confusion

2005-01-11 Thread Serge . Orlov
Jorgen Grahn wrote:
[snip]


 frailea cat foo
 import locale
 print locale.getlocale()
 locale.setlocale(locale.LC_CTYPE)
 print locale.getlocale()

 When I paste it into an interactive Python session, the locale is
already
 set up correctly (which is what I suppose interactive mode /should/
do):

  import locale
  print locale.getlocale()
 ['sv_SE', 'ISO8859-1']
  locale.setlocale(locale.LC_CTYPE)
 'sv_SE'
  print locale.getlocale()
 ['sv_SE', 'ISO8859-1']
 

 When I run it as a script it isn't though, and the setlocale() call
does not
 appear to fall back to looking at $LANG as it's supposed to(?), so my
 LC_CTYPE remains in the POSIX locale:

 frailea python foo
 (None, None)
 (None, None)

 The corresponding program written in C works as expected:

 frailea cat foot.c
 #include stdio.h
 #include locale.h
 int main(void) {
 printf(%s\n, setlocale(LC_CTYPE, 0));
 printf(%s\n, setlocale(LC_CTYPE, ));
 printf(%s\n, setlocale(LC_CTYPE, 0));
 return 0;
 }
 frailea ./foot
 C
 sv_SE
 sv_SE

 So, is this my fault or Python's?  I realize I could just adapt and
set
 $LC_CTYPE explicitly in my environment, but I don't want to
capitulate for a
 Python bug, if that's what this is.

Try locale.setlocale(locale.LC_CTYPE,) as in your C program. It would
be great if locale.setlocale with one parameter would be deprecated,
because it suddenly acts like getlocale. It's unpythonic.

By the way, since you took time to setup various LC_* variables there
is no need to play with LC_CTYPE category. Just use the standard idiom.
import locale
locale.setlocale(LC_ALL,)

 Serge.

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


Re: Exception not captured

2005-01-11 Thread Roy Smith
In article [EMAIL PROTECTED],
 Miki Tebeka [EMAIL PROTECTED] wrote:

 print SCMError is e.__class__
 raise SystemExit
 
 I get to the second except clause, and the printout is:
 /home/mikit/work/nightly/scm/common.py:3
 /home/mikit/work/nightly/scm/common.py:3
 False
 
 How is this possible?

I suspect you meant to do:

print SCMError is, e.__class__

The way you have it now, it's printing out the result of the is 
operator, which tests for identity.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedded scripts debugging

2005-01-11 Thread Andrey Tatarinov
Miki Tebeka wrote:
So the question is: Is there suitable library for simple python gui 
debugger, or may be there are some other techniques for debugging 
embedded scripts?
What I usually do is add
from pdb import set_trace
in the embedded module somewhere and then add a call to set_trace
(breakpoint) whenever I with.
When the code reaches the call to set_trace, you'll have pdb prompt and you
can debug as you like.
Note that you can't add breakpoint dynamically this way.
Thanks, I gathered pros and cons of embedding and decided to use python 
extending (i.e. creating python modules) instead of embedding. Happily I 
have an option to choose
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python unicode

2005-01-11 Thread Serge . Orlov
Michel Claveau - abstraction méta-galactique non triviale en fuite
perpétuelle. wrote:
 Hi !

  and plain Latin letters

 But not all letters  (no : é à ç à ê ö ñ  etc.)



 Therefore, the Python's support of Unicode is... limited.


So is the support of Unicode in virtually every computer language
because they don't support ... digits except 0..9. Does anyone know a
language that supports?

  Serge.

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


Re: Old Paranoia Game in Python

2005-01-11 Thread Paul McGuire
McBooCzech [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Newbie in Python.
 I did copy the whole script form the web and save it as para1.py. I did
 download pyparsing module and save it to
 C:\\Python23\\Lib\\pyparsing122.
 I did run following script:

 import sys
 sys.path.append('C:\\Python23\\Lib\\pyparsing122')

 from pyparsing import *
 extraLineBreak = White( ,exact=1) + LineEnd().suppress()
 text = file(Para1.py).read()
 newtext = extraLineBreak.transformString(text)
 file(para2.py,w).write(newtext)

 I did try to run para2.py script, but following message

 File para2.py, line 169
 choose(4,You give your correct clearance,5,You lie and claim
 ^
 SyntaxError: EOL while scanning single-quoted string

 So my questions are:
 Why pyparser didn't correct the script?
 What I am doing wrong?
 Is it necessary to correct the script by hand anyway?

 Petr

Petr -

After running the little script, I still had to make one correction by hand,
on line 1057.  There was a line that needed to be indented that wasn't.
This little pyparsing script only takes out the line-breaks that were added
because of the news server's word wrapping algorithm, and does not catch
indentation errors.  After correcting that by hand, I ran the program
para2.py successfully.

Did you extract *just* the Python code in the previous post?  I did not find
the line you listed as line 169 in either my pre-pyparsing nor
post-pyparsing versions of the program.  In para1.py, your line 169 shows up
as my line 159, in para2.py, it is line 152, and it looks like:
   choose(4,You give your correct clearance,5,You lie and claim
Ultraviolet clearance)
(of course, this is likely to get word-wrapped again, but the point is, it
includes the rest of the quoted string after the word 'claim').

What encoding are you using?  I am currently working on a Unicode-compatible
pyparsing, and this may help resolve your problem.  Since your e-mail domain
country code is cz, it's possible that the encoding for spaces and/or line
breaks is treated differently.   This is just a wild guess.

Anyway, in the interest of tracking down a potential pyparsing problem,
could you please e-mail me your para1.py file?

-- Paul




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


Re: [Python-Dev] PEP 246, redux

2005-01-11 Thread Nick Coghlan
Alex Martelli wrote:
I really wish the language had 
private inheritance because I'm using Abstract as a base just for code 
reuse
Funny you should say that. . . what about a __nonconformant__ entry that accepts 
a list of base classes that is used to indicate inheritance without a proper 
is-a relationship?

So if the isinstance check succeeds and there is no '__nonconformant__' entry, 
then adapt() just returns the object.

If, on the other hand, __nonconformant__ is supplied, then adapt() can check the 
list of base classes that remains after removing the entries in 
__nonconformant__ to see if the object would *still* be an instance a subtype, 
even after removing the noncomformant bases, and if it is, return it.

Otherwise, continue on to the rest of the adaptation process.
This should give a better idea what I mean:
# The 'fast path'
if isinstance(obj, protocol):
  if not hasattr(obj, __nonconformant__):
return obj
  conformant_bases = set(obj.__bases__) - set(obj.__nonconformant__)
  for base in conformant_bases:
if issubtype(base, protocol):
  return obj
# Continue on with the other adaptation possibilities (including __conform__)
Then you can get 'discreet' inheritance (you have the methods, but you don't 
brag about the fact) by writing:

class Dubious(Abstract):
  __noncomformant__ = [Abstract]
  # etc
rather than:
class Dubious(Abstract):
  def __comform__(self, protocol):
if issubtype(protocol, Abstract):
  raise LiskovViolation
  # etc
Regards,
Nick.
--
Nick Coghlan   |   [EMAIL PROTECTED]   |   Brisbane, Australia
---
http://boredomandlaziness.skystorm.net
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python serial data aquisition

2005-01-11 Thread Diez B. Roggisch
 It all looks pretty god but there is a couple of things I still don't
 understand, 1) in Steve's solution (which seems equivalent to your
 own), he does the masking, shifts by seven, and then  sums the two
 numbers while you, instead of summing, use a logical or. How can these
 operations be equivalent? or are they? Is the logical or  equivalent
 to a concatenation?

No, but look at this:

111000 + 000111 = 11
111000 | 000111 = 11

Adding and or are yielding the same results as long as at least one of the
bits combined is zero. By shifting the appropriate number of bits and thus
clearing the lower ones and anding the second argument with 0x7f, this is
ensured for the whole numbers.

 
 2) why 7? why do we have shift 7 bits? is that so the 8th bit on byte
 one is aligned with the first bit on the second byte?

Because of the specification you gave - look at the Byte2 spec closely.
-- 
Regards,

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


Re: Exception not captured

2005-01-11 Thread Nick Coghlan
Miki Tebeka wrote:
I get to the second except clause, and the printout is:
/home/mikit/work/nightly/scm/common.py:3
/home/mikit/work/nightly/scm/common.py:3
False
How is this possible?
Is line 3 inside a function? Then the class will be recreated anew each time the 
function is run.

Has common.py been reload()'ed at some point? Then previously imported modules 
may still have names bound to the old instances.

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


Re: why not datetime.strptime() ?

2005-01-11 Thread Skip Montanaro

Josh OK, it was pretty straightforward. Thanks for the direction.

Glad to help.

Josh To whom should I send the patch (attached)?

Patches should be posted to SourceForge using this form:

http://sourceforge.net/tracker/?func=addgroup_id=5470atid=305470

Note that you will have to be registered at SourceForge if you aren't
already.  Full details about submitting patches are here:

http://www.python.org/patches/

(though I think we're just as happy to read unified diffs as context diffs
these days).

The patch you posted looks like a good start.  I have a few quick comments:

* The references returned by PySequence_GetItem() are leaking.  An easy
  way to see is to run it in an infinite loop and watch your process's
  memory size:

while True:
x = datetime.datetime.strptime(2004-12-01, %Y-%m-%d)

  If it's leaking, memory size should grow pretty quickly.  A debug
  build will also show the memory growth:

   x = datetime.datetime.strptime(2004-12-01, %Y-%m-%d)
  [29921 refs]
   x = datetime.datetime.strptime(2004-12-01, %Y-%m-%d)
  [29928 refs]
   x = datetime.datetime.strptime(2004-12-01, %Y-%m-%d)
  [29935 refs]
   x = datetime.datetime.strptime(2004-12-01, %Y-%m-%d)
  [29942 refs]

  You can see the leaking references quite clearly.

* The seventh item returned from time.strptime() is the day of the week.
  You're passing it into the microsecond arg of the datetime constructor
  and ignoring the timezone info (ninth item returned from
  time.strptime(), eighth arg to the datetime constructor).

* The return values of the Py* calls must always be checked.

* A documentation patch for Doc/lib/libdatetime.tex is needed.

* Lib/test/test_datetime.tex should be extended to add one or more test
  cases for the new constructor.

* It would be nice if the import happened only once and was cached:

  static PyObject *time_module;
  ...
  if (time_module == NULL 
  (time_module = PyImport_ImportModule(time)) == NULL)
return NULL;
  obj = PyObject_CallMethod(time_module, ...);

After awhile these sorts of things become second nature.  They are part of
the boilerplate/details required for most changes though.

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


Re: Python unicode

2005-01-11 Thread michele . simionato
Kent:
 I don't think so. You have hacked an attribute with latin-1
characters in it, but you
 haven't actually created an identifier.

No, I really created an identifier. For instance
I can create a global name in this way:

 globals()[è]=1
 globals()[è]
1

 According to the language reference, identifiers can only contain
letters a-z and A-Z,
 digits 0-9 and underscore.
http://docs.python.org/ref/identifiers.html

The parser has this restriction, so it gets confused if it finds è.
But the underlying
implementation just works for generic identifiers.
Michele Simionato

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


Re: Importing Problem on Windows

2005-01-11 Thread brolewis
I launched the interpreter shell from the same directory in both
Windows and Linux before posting. That's what sent the red flag up for
me.

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


Re: Python 2.4 and os.open question?

2005-01-11 Thread Antoon Pardon
Op 2005-01-11, Eino Mäkitalo schreef [EMAIL PROTECTED]:
 I just test in Windows XP with Python 2.4

 I'd like to create a file with exclusive flag.

Why? What is it about the exclusive flag that
makes you like to use it?

 If file exist I try to use it, if not I'd like to create it.

If you want that, you cant use the exclusive flag.

 Python (and underlying library) works differently with/without O_EXCL 
 flag.

Well if the absence and presence of this flag wouldn't make a
difference, it would hardly be usefull to have such a flag,
wouldn't it?

 Is this okay. How I should use this.

 Has somebody manual :-) ?

 Eino Mäkitalo

 see scenarios (1 without flag ) (2 with flag)

 Scenario 1:

 To create file if it's not available this works ok

  aa=os.open(c:\\temp\\a.txt,os.O_RDWR|os.O_CREAT)
  os.close(aa)
  aa=os.open(c:\\temp\\a.txt,os.O_RDWR|os.O_CREAT)
  os.close(aa)


 Scenario 2:
 But if you try to do same with O_EXCL then it does not use same logic???

That is what flags are for: to change the logic. O_EXCL, makes sure
you are the one that creats the file. If the file exists it fails.
This is to make sure that if two programs can create the same file
but shouldn't work on it the same time, the file isn't opened
multiple times.

  aa=os.open(c:\\temp\\a.txt,os.O_RDWR|os.O_EXCL|os.O_CREAT)
  os.close(aa)
  aa=os.open(c:\\temp\\a.txt,os.O_RDWR|os.O_CREAT)

I suppose this should again be the instrcution two lines above;
this actually works. (At least on my linux box, if it didn't on
your XP box, that is a bug)

 Traceback (most recent call last):
File string, line 1, in string
 OSError: [Errno 17] File exists: 'c:\\temp\\a.txt'

Which is exactly as it should, provided you actually used the os.O_EXCL
flag twice.

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


Gecko bindings for Python?

2005-01-11 Thread Cordula's Web
Hello,

I'd like to use the Gecko engine in GTK+ or Qt programs written in
Python. Could you recommend a module for this? A tutorial to get
started? I didn't find anything useful, but I may have been looking in
all the wrong places... :)
Thanks,
-cpghost.

-- 
Cordula's Web. http://www.cordula.ws/

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


Re: Python 2.4 and os.open question?

2005-01-11 Thread Eino Mäkitalo
Antoon Pardon wrote:
Why? What is it about the exclusive flag that
makes you like to use it?
Ok. Thanks, I misunderstood the meaning of flag.
What I' like to do is to open file and keep it exclusive locked for me.
Apparently this flag is not for me.
Eino Mäkitalo
--
http://mail.python.org/mailman/listinfo/python-list


Re: Importing Problem on Windows

2005-01-11 Thread Peter Otten
brolewis wrote:

 I have a directory that has two files in it:
 
 parse.py
 parser.py
 
 parse.py imports a function from parser.py and uses it to parse out the
 needed information. On Linux, the following code works without a
 problem:
 
 parse.py, line 1:
 from parser import regexsearch
 
 However, when I run the same command in Windows, I get the following
 error:
 
 ImportError: cannot import name regexsearch
 Any suggestions on why this would work on Linux but not on Windows?

This has nothing to do with Linux vs. Windows. Depending on sys.path and
your current working directory either your own parser.py or the parser.py
module in the library is imported.
If you want to play it safe, rename your parser.py to myparser.py or another
name that is not already used by the standard library and avoid the
confusion between the two modules. If you do that, don't forget to delete
the compiled module parser.pyc or parser.pyo, too.

Peter



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


Re: else condition in list comprehension

2005-01-11 Thread Anthony
On Mon, 10 Jan 2005 09:13:17 -0700, Steven Bethard
[EMAIL PROTECTED] wrote:
 Luis M. Gonzalez wrote:
  It's me wrote:
  z = [i + (2, -2)[i % 2] for i in range(10)]
 
  But then why would you want to use such feature?  Wouldn't that make
  the code much harder to understand ...
  Or are we trying to write a book on Puzzles in Python?
 
  Once you get used to list comprehensions (and it doesn't take long),
  they are a more concise and compact way to express these operations.
 
 After looking the two suggestions over a couple of times, I'm still
 undecided as to which one is more readable for me.  The problem is not
 the list comprehensions (which I love and use extensively).  The problem
 is the odd syntax that has to be used for an if/then/else expression in
 Python.

They're both pretty unreadable, IMHO. Why not just factor out the
if/then/else function like this:

.def plusMinusTwo(i):
.   if  i%2 == 0:
.   return i-2
.   else:
.   return i+2
.
.z = [plusMinusTwo(i) for i in range(10)]

Then you can add whatever you like into the function.

Anthony

-- 
-
 HyPEraCtiVE? HeY, WhO aRE YoU cALliNg HypERaCtIve?!
 [EMAIL PROTECTED]
-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: MoinMoin and Mediawiki?

2005-01-11 Thread Alexander Schremmer
On 10 Jan 2005 18:45:16 -0800, Paul Rubin wrote:

 I need to set up a wiki for a small group.  I've played with MoinMoin
 a little bit and it's reasonably straightforward to set up, but
 limited in capabilities and uses BogusMarkupConventions.

At which point do you see limitations?
And what of the markup don't you like?

 In the larger world, though, there's currently One True wiki package,
 namely Mediawiki (used by Wikipedia).

It is just very famous because of Wikipedia IMHO.

  Mediawiki is written in PHP and
 is far more complex than MoinMoin, plus it's database backed, meaning
 you have to run an SQL server as well as the wiki software itself
 (MoinMoin just uses the file system).

Having a DBMS backend is good in your opinion? It has some severe
disadvantages like not easy to scale (you would need to setup DBMS
replication), two potential points of failure, more complex setup, bigger
memory requirements, etc.

  Plus, I'll guess that it really
 needs mod_php, while MoinMoin runs tolerably as a set of cgi's, at
 least when traffic is low.

Both should run fine in CGI mode I guess.

 What I'm getting at is I might like to install MoinMoin now and
 migrate to Mediawiki sometime later.  Anyone have any thoughts about
 whether that's a crazy plan?

If you really want to use the wiki for content, you have to agree on a
markup style. You could use an independent one (like RestructuredText) and
hope that MediaWiki supports it (MoinMoin does). Or you end up writing
complex migration scripts just for the markup.

Finding some script which just imports the data files into the DB should be
rather easy.

  Should I just bite the bullet and run Mediawiki from the beginning?

IMHO you should not bite it but choose MoinMoin. :-)

 Is anyone here actually running Mediawiki who can say just how
 big a hassle it is?

A few months I tried to install it. I got it running. But I did not like
the necessary complex administration tasks.

 The other one will be public and is planned grow to medium size (a few
 thousand active users), but which I don't need immediately.  I
 definitely want the second one to eventually run Mediawiki.  I can
 probably keep the first one on MoinMoin indefinitely, but that would
 mean I'm eventually running two separate wiki packages, which gets
 confusing.

There are even MoinMoin sites that are as big as that. Maybe you should
rethink your kind of prejudice and re-evaluate MoinMoin.

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


Python 2.4 and os.open question?

2005-01-11 Thread Eino Mäkitalo
I just test in Windows XP with Python 2.4
I'd like to create a file with exclusive flag.
If file exist I try to use it, if not I'd like to create it.
Python (and underlying library) works differently with/without O_EXCL 
flag. Is this okay. How I should use this.

Has somebody manual :-) ?
Eino Mäkitalo
see scenarios (1 without flag ) (2 with flag)
Scenario 1:
To create file if it's not available this works ok
 aa=os.open(c:\\temp\\a.txt,os.O_RDWR|os.O_CREAT)
 os.close(aa)
 aa=os.open(c:\\temp\\a.txt,os.O_RDWR|os.O_CREAT)
 os.close(aa)
Scenario 2:
But if you try to do same with O_EXCL then it does not use same logic???
 aa=os.open(c:\\temp\\a.txt,os.O_RDWR|os.O_EXCL|os.O_CREAT)
 os.close(aa)
 aa=os.open(c:\\temp\\a.txt,os.O_RDWR|os.O_CREAT)
Traceback (most recent call last):
  File string, line 1, in string
OSError: [Errno 17] File exists: 'c:\\temp\\a.txt'
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python serial data aquisition

2005-01-11 Thread Flavio codeco coelho
[EMAIL PROTECTED] (Bengt Richter) wrote in message news:[EMAIL PROTECTED]...
 On 9 Jan 2005 14:13:28 -0800, [EMAIL PROTECTED] (Flavio codeco coelho) wrote:
 
 Hi,
 
 I am using pyserial to acquire data from an A/D converter plugged to
 my serial port.
 
 my hardware represents analog voltages as 12bit numbers. So, according
 to the manufacturer, this number will be stored in two bytes like
 this;
  |-bits(1-8)---|
 Byte1: x x x n1 n2 n3 n4 n5
 Byte2: x n6 n7 n8 n9 n10 n11 n12
 
 where x is some other information, and nx are the digits of my number.
 
 My problem is to how to recover my reading from these bytes, since
 pyserial gives me a character (string) from each byte... I dont know
 how to throw away the unneeded bits and concatenate the remaining
 bits to form a number...
 
 The others have shown how to recover a 12 bit positive value 0 through 4095,
 but if the number is signed, and you want the signed value, you'll have to
 find out how signed numbers are represented. An offset is common, in which
 case you would subtract 2048 (2**11). If it's two's complement by some chance,
 you'll want (I think -- untested ;-) to do num -= 2*(num2048) instead of 
 always num -= 2048
 If you need speed in converting large strings of byte pairs, you could
 convert pairs of bytes with the array module ('H' for unsigned 2-byte numbers)
 and use the resulting 16-bit numbers as indices into another array of final 
 values
 prepared beforehand with redundant information that will accomplish the effect
 of masking and shifting and adjusting sign.
 If you need this speed, volunteers will magically appear. Maybe even if you 
 don't ;-)
 Regards,
 Bengt Richter


Hi Bengt,

The Idea of using Array is realy cool Though I have to think about it
since I would to plot the values as they are sampled...

Anyway, how would you set up this array to do the shifting and
masking?

BTW, since this thread is generating quite a bit of attention let me
post a complete description of my problem so that it may serve as
reference to others:

Hardware: DI-151RS from Dataq (2 analog channels, 2 digital input,
single ended/differential recording, max sampling rate 240Hz) connects
to the serial pro through a standard db9 plug.

Encryption table:


   B7  B6  B5  B4  B3  B2  B1  B0
Byte1   A4  A3  A2  A1  A0  1   Din 0
Byte2   A11 A10 A9  A8  A7  A6  A5  1
Byte3   B4  B3  B2  B1  B0  1   Din 1
Byte4   B11 B10 B9  B8  B7  B6  B5  1

first two bytes are for analog ch 1 and remaining two are for ch 2.
Din stands for digital in. AXX and BXX are the nth bits of each
reading. A0 and B0 are the least significant bits.

The latest and preferred solution on how to convert these bytes is,
according to the suggestion of Chris Liechti (author of pyserial) is:
(this is for the first channel only, repeat for the second)

import struct

 l, h = struct.unpack(BB, ser.read(2))
 n = (l  3) + ((h  1)5)

struct.unpack returns a tuple of values represented by a string(the
output of the read command) packed according to the format specified
by BB
In this forma string,  stands for big Endian representation and B
stands for unsigned char.

If anyone has a better suggestion, speack up!

oof! I started this thread knowing next to nothing about this stuff,
It seem that I am finally getting the idea! :))

cheers,

Flávio
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why not datetime.strptime() ?

2005-01-11 Thread josh
David M. Cookie writes:
 You don't check for errors: an exception being thrown by
 PyObject_CallMethod will return obj == NULL.

Oops, missed that one. Thanks.

 If there's a module in sys.path called time that overrides the stdlib
 time, things will fail, and you should be able to catch that.

Maybe someone really does want to override the time module, and then we
shouldn't get in their way? For example, if someone adds a new field
descriptor for nanoseconds to time.strptime, then it'd be nice to have
it work with datetime.datetime.strptime as well.

Incidentally, this is the way that the rest of datetime does it.

 Are you positive those PySequence_GetItem calls will succeed? That
 they will return Python integers?

Well, without interfaces, I can't be sure :). Throwing an exception
is cool (especially if we do allow user implemented time.strptime).

--- Modules/datetimemodule.c.orig   2003-10-20 10:34:46.0 -0400
+++ Modules/datetimemodule.c2005-01-11 10:42:23.0 -0500
@@ -3774,6 +3774,47 @@
return result;
 }
 
+/* Return new datetime from time.strptime(). */
+static PyObject *
+datetime_strptime(PyObject *cls, PyObject *args)
+{
+   PyObject *result = NULL, *obj, *module;
+   const char *string, *format;
+
+   if (!PyArg_ParseTuple(args, ss:strptime, string, format))
+   return NULL;
+
+   if ((module = PyImport_ImportModule(time)) == NULL)
+   return NULL;
+   obj = PyObject_CallMethod(module, strptime, ss, string, format);
+   Py_DECREF(module);
+
+   if (obj != NULL) {
+   int good_timetuple = 1;
+   if (PySequence_Check(obj)  PySequence_Size(obj)  6) {
+   int i;
+   for (i=0; i = 6; i++)
+   if (!PyInt_Check(PySequence_GetItem(obj, i)))
+   good_timetuple = 0;
+   } else
+   good_timetuple = 0;
+   if (good_timetuple)
+   result = PyObject_CallFunction(cls, iii,
+   PyInt_AsLong(PySequence_GetItem(obj, 0)),
+   PyInt_AsLong(PySequence_GetItem(obj, 1)),
+   PyInt_AsLong(PySequence_GetItem(obj, 2)),
+   PyInt_AsLong(PySequence_GetItem(obj, 3)),
+   PyInt_AsLong(PySequence_GetItem(obj, 4)),
+   PyInt_AsLong(PySequence_GetItem(obj, 5)),
+   PyInt_AsLong(PySequence_GetItem(obj, 6)));
+   else
+   PyErr_SetString(PyExc_ValueError,
+   unexpected value from time.strptime);
+   Py_DECREF(obj);
+   }
+   return result;
+}
+
 /* Return new datetime from date/datetime and time arguments. */
 static PyObject *
 datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
@@ -4385,6 +4426,11 @@
 PyDoc_STR(timestamp - UTC datetime from a POSIX timestamp 
   (like time.time()).)},
 
+   {strptime, (PyCFunction)datetime_strptime,
+METH_VARARGS | METH_CLASS,
+PyDoc_STR(strptime - new datetime parsed from a string
+  (like time.strptime()).)},
+
{combine, (PyCFunction)datetime_combine,
 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
 PyDoc_STR(date, time - datetime with same date and time fields)},
--- Doc/lib/libdatetime.tex.orig2003-09-06 01:36:56.0 -0400
+++ Doc/lib/libdatetime.tex 2005-01-11 11:06:22.699348152 -0500
@@ -624,6 +624,13 @@
   ignored.
   \end{methoddesc}
 
+\begin{methoddesc}{strptime}{date_string, format}
+  Return the date corresponding to date_string, parsed according
+  to format. This is equivalent to \code{datetime(*(time.strptime(
+  date_string, format)[0:7]))}. \exception{ValueError} is raised if
+  \code{time.strptime()} returns a value which isn't a timetuple.
+\end{methoddesc}
+
 Class attributes:
 
 \begin{memberdesc}{min}
-- 
http://mail.python.org/mailman/listinfo/python-list

os.spawnv stdin trouble

2005-01-11 Thread Jelle Feringa // EZCT / Paris








##I know I should be using 2.4 and os.Popen,
I know, I know

##However, since most modules I need, Im using 2.3
for this script





Im having troubles executing a shell script.

The thing is that Im produing
material and geometry files that need to be compiled to a binary description (for
those familiar to Radiance, oconv)

The trouble Im having is that when python goes
through my loop, files are overwritten before os.system
was able to process these! (who ways complaining
python is slow, well Im not!! ;-) So the obvious thing to do is to swap os.system for os.spawnv.



Heres where I run into trouble.

In my os.system version, Im
perfectly able to pipe into another file, since the process has no real
connection to python whatsoever.

Would someone be able to explain me how to do this, all the
tools Im using for this script are unix-like
tools and heavily rely on piping.





program =
'xform.exe'

path =
'c:\Radiance\bin\'

args = ['-t 0 8
0', 'wall0.rad', '', 'wall0.TRANS.rad']

os.spawnv(os.P_WAIT, path, ('xform', args))



heres the cmd error message:

xform: cannot
find file 





##for your info Im on win/xp,
python 2.3.4





Cheers,



Jelle.






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

Re: OT: MoinMoin and Mediawiki?

2005-01-11 Thread Paul Rubin
Alexander Schremmer [EMAIL PROTECTED] writes:
  I need to set up a wiki for a small group.  I've played with MoinMoin
  a little bit and it's reasonably straightforward to set up, but
  limited in capabilities and uses BogusMarkupConventions.
 
 At which point do you see limitations?

It doesn't have features that MW has, like user pages, lists of
incoming links to wiki pages, automatic discussion links for every
wiki page, automatic update notification for specific pages of your
choice, support for managing image uploads and embedding them
into wiki pages, etc. etc.

 And what of the markup don't you like?

The BogusMixedCaseLinkNames.  I'd rather have ordinary words with
spaces between them, like we use in ordinary writing.

  In the larger world, though, there's currently One True wiki package,
  namely Mediawiki (used by Wikipedia).
 
 It is just very famous because of Wikipedia IMHO.

Well, it's gotten a lot more development attention because of that
same Wikipedia.

 Having a DBMS backend is good in your opinion? It has some severe
 disadvantages like not easy to scale (you would need to setup DBMS
 replication), two potential points of failure, more complex setup, bigger
 memory requirements, etc.

I didn't say that it was good, in fact I was listing it as a
disadvantage there.  I think for a small wiki like I was discussing,
it's just an extra administrative hassle.  For a large wiki though,
MoinMoin's approach is completely unworkable and MoinMoin's
documentation actually says so.  First of all MoinMoin uses a separate
subdirectory for every page, and all those subdirs are in a flat top
level directory, so if you have 100,000 wiki pages, the top level
directory has that many subdirs.  Most file systems are not built to
handle such large directories with any reasonable speed.  (Also, every
revision has its own file in the subdir.  Lots of Wikipedia pages have
thousands of revisions).  Second, DBMS's have indexes and
transactions, that make it simple to have features like what links
here.  Yes you could do something like that in MoinMoin with
additional files, but then you'd have to update multiple files when
you commit a change, which can leave stuff inconsistent if there's a
crash partway through the update (I wonder just how crash-resilient
MoinMoin is right now, even).  The DBMS can also handle stuff like
replication automatically.

 If you really want to use the wiki for content, you have to agree on
 a markup style. You could use an independent one (like
 RestructuredText) and hope that MediaWiki supports it (MoinMoin
 does). Or you end up writing complex migration scripts just for the
 markup.

I looked at RestructuredText once and hated it.  WikiMedia's markup
language has bogosities just like anything else, but for the most part
it's not too bad.  Anyway, lots more people are used to it than any
other Wiki markup language, just because of Wikipedia's popularity.

  Is anyone here actually running Mediawiki who can say just how
  big a hassle it is?
 
 A few months I tried to install it. I got it running. But I did not like
 the necessary complex administration tasks.

I'm not too surprised.  That's why MoinMoin was the first one I tried.

  The other one will be public and is planned grow to medium size (a few
  thousand active users)

 There are even MoinMoin sites that are as big as that. Maybe you should
 rethink your kind of prejudice and re-evaluate MoinMoin.

I don't doubt there are MoinMoin sites that size, but with that large
a user base, I want something nicer looking than those
StupidMixedCasePageNames.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.spawnv stdin trouble

2005-01-11 Thread Denis S. Otkidach
On Tue, 11 Jan 2005 17:31:07 +0100
Jelle Feringa // EZCT / Paris [EMAIL PROTECTED] wrote:

 ##I know I should be using 2.4 and os.Popen, I know, I know.
 ##However, since most modules I need, I'm using 2.3 for this script

There is os.popen in 2.3, as well as popen2 module.  Did you mean
subprocess?  I guess it's ported to 2.3 too.

 Here's where I run into trouble.
 In my os.system version, I'm perfectly able to pipe into another file,
 since the process has no real connection to python whatsoever.
 Would someone be able to explain me how to do this, all the tools I'm
 using for this script are unix-like tools and heavily rely on piping.

os.system passes commend to shell, which handles redirect for you
instead of passing '' to xform.exe as parameter.  Use os.system or
subprocess (a.k.a. popen5).

 program = 'xform.exe'
 path = 'c:\Radiance\bin\'
 ^^
Syntax error here.  Did you mean 'c:\\Radiance\\bin\\xform.exe'?

 args = ['-t 0 8 0', 'wall0.rad', '', 'wall0.TRANS.rad']
 os.spawnv(os.P_WAIT, path, ('xform', args))

This corresponds to 
c:\RadianceBSin\ '-t 0 8 0' wall0.rad '' wall0.TRANS.rad'
command line.

 here's the cmd error message:
 xform: cannot find file 

Don't understand how you got this error having syntax error and wrong
path to executable.

 ##for your info I'm on win/xp, python 2.3.4

BTW, you are trying to redirect stdout.  Wrong subject?

-- 
Denis S. Otkidach
http://www.python.ru/  [ru]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OT: MoinMoin and Mediawiki?

2005-01-11 Thread Richie Hindle

[Paul]
 [MoinMoin] doesn't have [...] automatic update notification for
 specific pages of your choice

Yes it does.  See http://entrian.com/sbwiki for example - register there
and you'll see in your preferences Subscribed wiki pages (one regex per
line)

 The BogusMixedCaseLinkNames.  I'd rather have ordinary words with
 spaces between them, like we use in ordinary writing.

MoinMoin has an option to display WikiWords with spaces between them
(albeit still capitalised), again in the user preferences.

I'm not saying that MoinMoin is better than MediaWiki, just that it really
does have some of the features you say it doesn't (perhaps you've been
looking at an old version).

-- 
Richie Hindle
[EMAIL PROTECTED]

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


os.spawn stdOUT trouble

2005-01-11 Thread Jelle Feringa // EZCT / Paris
Yikes, how painful, I meant stdOUT  trouble instead of stdin...
Awefully sorry

Cheers,

Jelle

##thanks for pointing that out Denis!



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


Re: Python unicode

2005-01-11 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
Kent:
I don't think so. You have hacked an attribute with latin-1
characters in it, but you
haven't actually created an identifier.

No, I really created an identifier. For instance
I can create a global name in this way:

globals()[è]=1
globals()[è]
1
Maybe I'm splitting hairs but to me an identifier is a syntactical element that can be used in 
specific ways. For example the syntax defines
attributeref ::=
 primary . identifier
so if identifiers can contain latin-1 characters you should be able to say
C.è=1

Kent

According to the language reference, identifiers can only contain
letters a-z and A-Z,
digits 0-9 and underscore.
http://docs.python.org/ref/identifiers.html

The parser has this restriction, so it gets confused if it finds è.
But the underlying
implementation just works for generic identifiers.
Michele Simionato
--
http://mail.python.org/mailman/listinfo/python-list


Time script help sought!

2005-01-11 Thread kpp9c

I am kind of in a bit of a jam  (okay a big jam) and i was hoping that
someone here could give me a quick hand. I had a few pages of time
calculations to do. So, i just started in on them typing them in my
time calculator and writing them in by hand. Now i realize, that i
really need a script to do this because:

1. It turns out there are hundreds of pages of this stuff.
2. I have to do something similar in again soon.
3. By doing it by hand i am introducing wonderful new errors!
4. It all has to be typed up anyway (which means weeks of work and even
more typos!)

The input would like so:

Item_1TAPE_1100:238:23

Item_2TAPE_128:239:41

Item_3TAPE_139:4110:41
Item_3TAPE_1410:4711:19
Item_3TAPE_1511:2111:55
Item_3TAPE_1611:5812:10
Item_3TAPE_1712:1512:45Defect in analog tape sound.
Item_3TAPE_1812:5824:20Defect in analog tape sound.

Item_4TAPE_1924:33
Item_4TAPE_11025:48
Item_4TAPE_11129:48
Item_4TAPE_11231:46
Item_4TAPE_11334:17Electronic sounds.
Item_4TAPE_11435:21
Item_4TAPE_11536:06
Item_4TAPE_11637:0137:38

These are analog tapes that were digitized (on to CD or a digital tape)
that have now been exported as individual files that are meant to be
part of an on-line audio archive. The timings refer to the time display
on the CD or digital tape. The now all have to adjusted so that each
item starts at 0.00 since they have all been edited out of their
context and are now all individual items that start at 00:00. So Item_1
which was started at 00:23 on the tape and ended at 8:23 needs to have
23 seconds subtracted to it so that it says:

Item_1TAPE_1100:0008:00

Item_2TAPE_1208:2309:41

would change to:

Item_2TAPE_1200:0001:18

etc.

but as always you may notice a wrinkle some items have many times
(here 6) indicated:

Item_3TAPE_139:4110:41
Item_3TAPE_1410:4711:19
Item_3TAPE_1511:2111:55
Item_3TAPE_1611:5812:10
Item_3TAPE_1712:1512:45Defect in analog tape sound.
Item_3TAPE_1812:5824:20Defect in analog tape sound.

This is all a single sound file and these separate times mark where
there was a break, defect, or edit in the individual item. These have
to be adjusted as well to show where these events would appear in the
new sound file which now starts at 00:00.

Item_3TAPE_1300:0001:00
Item_3TAPE_1401:0001:38
Item_3TAPE_1501:3802:14
Item_3TAPE_1602:1402:29
Item_3TAPE_1702:2903:04Defect in analog tape sound.
Item_3TAPE_1803:0414:39Defect in analog tape sound.

Further wrinkles: Some have start and end times indicated, some only
start times. I suppose that the output would ideally have both some
have comments and others don't ... and I need these comments echo-ed or
since i probably need to make a database or table eventually non
comments just have some place holder.

I'd have a lot of similar type calculations to do... I was hoping and
praying that some one here was feeling generous and show me the way and
then, of course i could modify that to do other tasks... Usually i am
happy to take the long road and all but i'll be honest, i am in a big
jam here and this huge task was just dumped on me. I am frankly a
little desperate for help on this and hoping someone is feeling up to
spoon feeding me a clear modifiable example that works. Sorry.
cheers,

kevin

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


Re: OT: MoinMoin and Mediawiki?

2005-01-11 Thread Paul Rubin
Richie Hindle [EMAIL PROTECTED] writes:
  [MoinMoin] doesn't have [...] automatic update notification for
  specific pages of your choice
 
 Yes it does.  See http://entrian.com/sbwiki for example - register there
 and you'll see in your preferences Subscribed wiki pages (one regex per

Oh interesting, thanks.

 MoinMoin has an option to display WikiWords with spaces between them
 (albeit still capitalised), again in the user preferences.

Oh good, that's cool too, though this goes to show that the MoinMoin
documentation could stand a lot of improvement (this holds in other
areas as well).  I don't understand why using spaces is the default.
Who except for demented Java programmers really likes this MixedCase
nonsense?  Is there a way to turn it off altogether, so you can use
mixed case words on wiki pages without automatically generating a
link?

 I'm not saying that MoinMoin is better than MediaWiki, just that it really
 does have some of the features you say it doesn't (perhaps you've been
 looking at an old version).

I'm not saying MoinMoin is worse than MediaWiki, just as I wouldn't
say a rowboat is worse than an aircraft carrier.  MediaWiki is the
only choice that makes any sense for large wikis (say  20k pages).
For small ones, MoinMoin is easier to operate in many ways, which is a
big plus.

It would be nice if MoinMoin changed its markup language to be closer
to MediaWiki's.  I edit MediaWiki pages all the time and I hate having
to switch back and forth between languages (actually that's another
reason I've reacted not-so-well to MoinMoin's language).  I think I
saw something in the MoinMoin docs saying that some standard was being
developed that would look like MediaWiki, and that MoinMoin would
support the standard, so I guess this will work out in the long run.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why not datetime.strptime() ?

2005-01-11 Thread josh
On Tue, Jan 11, 2005 at 08:56:33AM -0600, Skip Montanaro wrote:
 * The seventh item returned from time.strptime() is the day of the week.
   You're passing it into the microsecond arg of the datetime constructor

Thanks!

   and ignoring the timezone info (ninth item returned from
   time.strptime(), eighth arg to the datetime constructor).
 

This is intentional. time.strptime() doesn't expose the timezone (only
the daylight savings flag), so i'd have to duplicate its logic in order
to distinguish between local time and utc. Since it's easy to explicitly
call somedatetime.replace(tzinfo=sometzinfo), having strptime() always
create naive datetimes seemed most sensible.

 * It would be nice if the import happened only once and was cached:
 
   static PyObject *time_module;
   ...
   if (time_module == NULL 
   (time_module = PyImport_ImportModule(time)) == NULL)
 return NULL;
   obj = PyObject_CallMethod(time_module, ...);

The datetime is full of these calls. Would it make sense to make this a
separate patch? (Or maybe the PyImport_ImportModule could implement such
a cache :) ?)
*** Modules/datetimemodule.c.orig   2003-10-20 10:34:46.0 -0400
--- Modules/datetimemodule.c2005-01-11 12:19:36.839337336 -0500
***
*** 3774,3779 
--- 3774,3819 
return result;
  }
  
+ /* Return new datetime from time.strptime(). */
+ static PyObject *
+ datetime_strptime(PyObject *cls, PyObject *args)
+ {
+   PyObject *result = NULL, *obj, *module;
+   const char *string, *format;
+ 
+   if (!PyArg_ParseTuple(args, ss:strptime, string, format))
+   return NULL;
+ 
+   if ((module = PyImport_ImportModule(time)) == NULL)
+   return NULL;
+   obj = PyObject_CallMethod(module, strptime, ss, string, format);
+   Py_DECREF(module);
+ 
+   if (obj != NULL) {
+   int i, good_timetuple = 1;
+   long int ia[6];
+   if (PySequence_Check(obj)  PySequence_Size(obj) = 6)
+   for (i=0; i  6; i++) {
+   PyObject *p = PySequence_GetItem(obj, i);
+   if (PyInt_Check(p))
+   ia[i] = PyInt_AsLong(p);
+   else
+   good_timetuple = 0;
+   Py_DECREF(p);
+   }
+   else
+   good_timetuple = 0;
+   if (good_timetuple)
+   result = PyObject_CallFunction(cls, ii,
+   ia[0], ia[1], ia[2], ia[3], ia[4], ia[5]);
+   else
+   PyErr_SetString(PyExc_ValueError,
+   unexpected value from time.strptime);
+   Py_DECREF(obj);
+   }
+   return result;
+ }
+ 
  /* Return new datetime from date/datetime and time arguments. */
  static PyObject *
  datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
***
*** 4385,4390 
--- 4425,4435 
 PyDoc_STR(timestamp - UTC datetime from a POSIX timestamp 
   (like time.time()).)},
  
+   {strptime, (PyCFunction)datetime_strptime,
+METH_VARARGS | METH_CLASS,
+PyDoc_STR(strptime - new datetime parsed from a string
+  (like time.strptime()).)},
+ 
{combine, (PyCFunction)datetime_combine,
 METH_VARARGS | METH_KEYWORDS | METH_CLASS,
 PyDoc_STR(date, time - datetime with same date and time fields)},
*** Doc/lib/libdatetime.tex.orig2003-09-06 01:36:56.0 -0400
--- Doc/lib/libdatetime.tex 2005-01-11 12:02:30.0 -0500
***
*** 624,629 
--- 624,636 
ignored.
\end{methoddesc}
  
+ \begin{methoddesc}{strptime}{date_string, format}
+   Return the date corresponding to date_string, parsed according
+   to format. This is equivalent to \code{datetime(*(time.strptime(
+   date_string, format)[0:6]))}. \exception{ValueError} is raised if
+   \code{time.strptime()} returns a value which isn't a timetuple.
+ \end{methoddesc}
+ 
  Class attributes:
  
  \begin{memberdesc}{min}
*** Lib/test/test_datetime.py.orig  2005-01-11 11:56:36.0 -0500
--- Lib/test/test_datetime.py   2005-01-11 12:28:30.268243816 -0500
***
*** 1351,1356 
--- 1351,1365 
  # Else try again a few times.
  self.failUnless(abs(from_timestamp - from_now) = tolerance)
  
+ def test_strptime(self):
+ import time
+ 
+ string = '2004-12-01'
+ format = '%Y-%m-%d'
+ expected = self.theclass(*(time.strptime(string, format)[0:6]))
+ got = self.theclass.strptime(string, format)
+ self.assertEqual(expected, got)
+ 
  def test_more_timetuple(self):
  # This tests fields beyond those tested by the 
TestDate.test_timetuple.
  t = 

Re: Time script help sought!

2005-01-11 Thread Paul Rubin
kpp9c [EMAIL PROTECTED] writes:
 These are analog tapes that were digitized (on to CD or a digital tape)
 that have now been exported as individual files that are meant to be
 part of an on-line audio archive. ...
 I was hoping and
 praying that some one here was feeling generous and show me the way...

Is this online archive going to be accessible by the public for free?
What's in the archive?  If you're asking for volunteer labor it's
generally appropriate to say precisely what that the labor is for.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Windows GUIs from Python

2005-01-11 Thread Thomas Bartkus
Bob Swerdlow [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Anyone have opinions about whether we will be better off using PythonNet
or
 wxPython for the GUI layer of our application on Windows?  Our code is all
 Python and is now running on Mac OS X with PyObjC and Cocoa, which works
 very well.  Our goal is not necessarily to move to a cross-platform
 solution, but rather to create a solid Windows version that looks and
feels
 like a native application.  All the code that interacts with the user is
 factored out of our business logic, so it is a matter of find a good
 view/controller library and writing a thin glue layer.  And, of course, we
 want to build it as efficiently and robustly as we can.

Everyone has opinions :-)

I have settled on wxPython principally because of
   1) Linux/Gnome - MS Windows portablility of the code.
   2) The fact that wxPython follows the look and feel of whatever window
themes might be installed in Linux/Gnome or MS Windows.
   3) Apps so written have that native look and feel and fit right in.

Thomas Bartkus


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


Re: complex numbers

2005-01-11 Thread Anno Siegel
It's me [EMAIL PROTECTED] wrote in comp.lang.perl.misc:

[reply moved to bottom into context]

 Jürgen Exner [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
  [EMAIL PROTECTED] wrote:
   #python supports complex numbers.
  [...]
 
  So?
 
 
 The world would come to a halt if all of a sudden nobody understands complex
 numbers anymore.  :-)
 
   # Perl doesn't support complex numbers. But there are packages that
   supports it.
 
  The Math::Complex module is part of the standard installation already, no
  need for any packages (whatever that might be).
  Did you check perldoc Math::Complex
 
  NAME
  Math::Complex - complex numbers and associated mathematical functions
  [...]

 For those of us that works with complex numbers, having complex number as a
 natively supported data type is a big advantage.  Non-native add-ons are not
 sufficient and lead to very awkward program code.

Like this?

use Math::Complex;

my $z = sqrt( -1);
print 1 + $z, \n; # prints 1+i

Operator overloading makes it possible to work with complex numbers as if
they were a native data type.

Anno

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


Re: Time script help sought!

2005-01-11 Thread kpp9c
Yes, Ultimately it will be part of a large digital archive available
for researchers on site and eventually probably on-line for the New
York Public Library. It is a huge undertaking and most of the
soundfiles have been made. I (we) are struggling with the   sheer size
of the documentation Sorry about that i should have been more
clear, epecially since i am sort of begging for a little help. Sorry, i
am slightly overwhelmed at the moment...

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


Re: else condition in list comprehension

2005-01-11 Thread Serhiy Storchaka1659322541
Nick Coghlan wrote:
Dan Bishop wrote:
Luis M. Gonzalez wrote:
Hi there,
I'd like to know if there is a way to add and else condition into a
list comprehension. I'm sure that I read somewhere an easy way to do
it, but I forgot it and now I can't find it...
for example:
z=[i+2 for i in range(10) if i%2==0]
what if I want i [sic] to be i-2 if i%2 is not equal to 0?

z = [i + (2, -2)[i % 2] for i in range(10)]

For the specific case of +/- a number, (-1) ** x works, too:
z = [i + 2 * ((-1) ** i) for i in range(10)]
Not that I'm claiming it's particularly readable or anything. . . just 
that it works :)
Yet another variant:
z = [i + ( (i % 2) and -2 or 2 ) for i in range(10)]
--
Serhiy Storchaka
--
http://mail.python.org/mailman/listinfo/python-list


exporting from Tkinter Canvas object in PNG

2005-01-11 Thread Nicolas Pourcelot
Hello,
I'm new to this mailing list and quite to Pyhon too.
I would like to know how to export the contain of the Canvas object 
(Tkinter) in a PNG file ?
Thanks :)
Nicolas Pourcelot
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python unicode

2005-01-11 Thread Scott David Daniels
[EMAIL PROTECTED] wrote:
Because the coding is only supported in string literals.
But I'm not sure exactly why. 
The why is the same as why we write in English on this newsgroup.
Not because English is better, but because that leaves a single
language for everyone to use to communicate in.  If you allow
non-ASCII characters in symbol names, your source code will be
unviewable (and uneditable) for people with ASCII-only terminals,
never mind how comprehensible it might otherwise be.  It is a
least-common-denominator argument, not a this is better
argument.
-Scott David Daniels
[EMAIL PROTECTED]

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


how to set doc-string of new-style classes

2005-01-11 Thread harold fellermann
Hello,
does anyone know a way to set the __doc__ string of a new style class?
Any attempt I tried results in the following error:
Python 2.4 (#1, Dec 30 2004, 08:00:10)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type help, copyright, credits or license for more information.
 class Foo(object) :
... pass
...
 Foo.__doc__ = bar
Traceback (most recent call last):
  File stdin, line 1, in ?
TypeError: attribute '__doc__' of 'type' objects is not writable
I can understand someone arguing that changing a doc string is during
programm execution and should therefore be forbidden! But, I cannot
even find out a way to set the doc string, when I CREATE a class using
type(name,bases,dict) ... At least this should be possible, IMHO.
- harold -
--
If you make people think they're thinking, they'll love you;
but if you really make them think they'll hate you.
--
http://mail.python.org/mailman/listinfo/python-list


Re: complex numbers

2005-01-11 Thread It's me
Operator overloading (and function overloading) helps but not enough.You
have to be aware of the complex type *everywhere* you go and that's very
annoying and error prone.  I've been the works with C++, and later with
Modelica.   I am very happy that Python included *native* complex number
support.

I really like Python's notion of having just one data type: the duck.



Anno Siegel [EMAIL PROTECTED] wrote in message
news:cs145l$8d6

snip


 Like this?

 use Math::Complex;

 my $z = sqrt( -1);
 print 1 + $z, \n; # prints 1+i

 Operator overloading makes it possible to work with complex numbers as if
 they were a native data type.

 Anno



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


Re: exporting from Tkinter Canvas object in PNG

2005-01-11 Thread harold fellermann
On 11.01.2005, at 19:14, Nicolas Pourcelot wrote:
Hello,
I'm new to this mailing list and quite to Pyhon too.
I would like to know how to export the contain of the Canvas object
(Tkinter) in a PNG file ?
Thanks :)
Nicolas Pourcelot
--
http://mail.python.org/mailman/listinfo/python-list
you can make a postscript dump using
 canvas = Tkinter.Canvas(master)
 canvas.postscript(file=your_file_name.ps)
If you have ImageMagick, you can later use
% convert your_file_name.ps your_file_name.png
on the comand line, if you want to have png.
- harold -
--
Science is to see what everybody else has seen,
and think what nobody else has thought.
--
--
http://mail.python.org/mailman/listinfo/python-list


Game programming in Python

2005-01-11 Thread Baza
I'm looking for any books or on-line resources on game programming using
Python. Does anyone have any advice?
--  
Computer says, 'no'


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


Re: OT: MoinMoin and Mediawiki?

2005-01-11 Thread Robin Becker
Paul Rubin wrote:
Brion Vibber [EMAIL PROTECTED] writes:
MediaWiki should run with PHP configured in CGI handler mode, but
these days mod_php has got its claws just about everywhere anyway. If
you control your own server and don't have multi-user security
worries, mod_php is simple enough to install and will probably perform
better.

Thanks, yes, I could run a special apache instance with mod_php
installed.  I'm pretty good with apache.  I have no MySQL admin
experience but I suppose enough people are using MySQL that the
installation procedures and docs are pretty well developed and I can
follow the instructions.
What I'm wondering is just how big an adventure I'd be setting off on,
simply to get MediaWiki itself installed, configured, and running.
Any thoughts about that?
.
A few months ago I tried and failed to get squirrelmail/php to run with Apache2 
and freeBSD 4.9. It seems that php prefers the old style apache 1.3 work flow. I 
got some  help from the php guys, but not enough. I suppose I could have run a 
separate apache13 server, but that seems like a cop out to me. We don't want to 
maintain an extra set of configs etc etc.

Mailman, moinmoin and others work fine with apache2 maybe because they use a cgi 
style interface. I would stick with a pythonic solution unless there's a good 
reason not too.
-too old to learn a new language-ly yrs-
Robin Becker

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


Re: Time script help sought!

2005-01-11 Thread Mark McEahern
kpp9c wrote:
The input would like so:
 

[...]
Attached is a first cut at a parser that actually uses the raw content 
of your original email.  You'll notice that the net effect is that the 
parser instance's items attribute contains the source ordered list of 
items with attributes for each of the various parts of the line.  From 
this, it should be pretty easy to adjust the times and what not.

Cheers,
// m
#!/usr/bin/env python

usage: %prog


raw = I am kind of in a bit of a jam  (okay a big jam) and i was hoping that
someone here could give me a quick hand. I had a few pages of time
calculations to do. So, i just started in on them typing them in my
time calculator and writing them in by hand. Now i realize, that i
really need a script to do this because:

1. It turns out there are hundreds of pages of this stuff.
2. I have to do something similar in again soon.
3. By doing it by hand i am introducing wonderful new errors!
4. It all has to be typed up anyway (which means weeks of work and even
more typos!)

The input would like so:

Item_1TAPE_1100:238:23

Item_2TAPE_128:239:41

Item_3TAPE_139:4110:41
Item_3TAPE_1410:4711:19
Item_3TAPE_1511:2111:55
Item_3TAPE_1611:5812:10
Item_3TAPE_1712:1512:45Defect in analog tape sound.
Item_3TAPE_1812:5824:20Defect in analog tape sound.

Item_4TAPE_1924:33
Item_4TAPE_11025:48
Item_4TAPE_11129:48
Item_4TAPE_11231:46
Item_4TAPE_11334:17Electronic sounds.
Item_4TAPE_11435:21
Item_4TAPE_11536:06
Item_4TAPE_11637:0137:38

These are analog tapes that were digitized (on to CD or a digital tape)
that have now been exported as individual files that are meant to be
part of an on-line audio archive. The timings refer to the time display
on the CD or digital tape. The now all have to adjusted so that each
item starts at 0.00 since they have all been edited out of their
context and are now all individual items that start at 00:00. So Item_1
which was started at 00:23 on the tape and ended at 8:23 needs to have
23 seconds subtracted to it so that it says:

Item_1TAPE_1100:0008:00

Item_2TAPE_1208:2309:41

would change to:

Item_2TAPE_1200:0001:18

etc.

but as always you may notice a wrinkle some items have many times
(here 6) indicated:

Item_3TAPE_139:4110:41
Item_3TAPE_1410:4711:19
Item_3TAPE_1511:2111:55
Item_3TAPE_1611:5812:10
Item_3TAPE_1712:1512:45Defect in analog tape sound.
Item_3TAPE_1812:5824:20Defect in analog tape sound.

This is all a single sound file and these separate times mark where
there was a break, defect, or edit in the individual item. These have
to be adjusted as well to show where these events would appear in the
new sound file which now starts at 00:00.

Item_3TAPE_1300:0001:00
Item_3TAPE_1401:0001:38
Item_3TAPE_1501:3802:14
Item_3TAPE_1602:1402:29
Item_3TAPE_1702:2903:04Defect in analog tape sound.
Item_3TAPE_1803:0414:39Defect in analog tape sound.

Further wrinkles: Some have start and end times indicated, some only
start times. I suppose that the output would ideally have both some
have comments and others don't ... and I need these comments echo-ed or
since i probably need to make a database or table eventually non
comments just have some place holder.

I'd have a lot of similar type calculations to do... I was hoping and
praying that some one here was feeling generous and show me the way and
then, of course i could modify that to do other tasks... Usually i am
happy to take the long road and all but i'll be honest, i am in a big
jam here and this huge task was just dumped on me. I am frankly a
little desperate for help on this and hoping someone is feeling up to
spoon feeding me a clear modifiable example that works. Sorry.
cheers,

kevin

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

import optparse
import re

pat = re.compile('\s+')

class Item:

def __init__(self, line):
parts = pat.split(line)
self.name, self.tape, self.number, self.start = parts[:4]
if len(parts) == 5:
self.end = parts[4]
else:
self.end = None
if len(parts)  5:
self.comment = ' '.join(parts[5:])
else:
self.comment = None

class Parser:

def __init__(self):
self.items = []

def feed(self, line):
item = Item(line)
self.items.append(item)

def parseCommandLine(usage, requiredArgCount, argv=None):
Parse the command line and return (options, args).

Raise an error if there are insufficient 

Re: What could 'f(this:that=other):' mean?

2005-01-11 Thread Jonathan Fine
Nick Coghlan wrote:
If the caller is meant to supply a namespace, get them to supply a 
namespace.

def f(ns1, ns2):
  print ns1['a'], ns1['b'], ns2['a'], ns2['b']
f(ns1 = dict(a=1, b=2), ns2 = dict(a=3, b=4))
Hey, where's Steve? Maybe his generic objects should be called 
namespaces instead of bunches. . .

def f(ns1, ns2):
  print ns1.a, ns1.b, ns2.a, ns2.b
f(ns1 = namespace(a=1, b=2), ns2 = namespace(a=3, b=4))

Basically, there are three main possibilities.
  f_1(ns1=dict(a=1, b=2), ns2=dict(a=3, b=4))
  f_2(ns1_a=1m, ns1_b=2, ns2_a=3, ns2_b=4)
  f_3(ns1:a=1m, ns1:b=2, ns2:a=3, ns2:b=4)
f_3 is the suggested extension to Python.
f_3 is similar to f_2 for the caller of f_3.
f_3 is similar to f_1 for the implementor of f_3.
Nick points out that a key issue is this:  Is the user meant
to supply arguments belonging to a namespace?
I'm not, at this time, wishing to promote my suggestion.
If I were, I would be well advised to find usage cases.
Rather, I simply wish to point out that the
  f(this:that=other)
syntax may have uses, other than optional static typing.
And this I've done.  So for me the thread is closed.
Jonathan

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


Re: OT: MoinMoin and Mediawiki?

2005-01-11 Thread Paul Rubin
Robin Becker [EMAIL PROTECTED] writes:
 A few months ago I tried and failed to get squirrelmail/php to run
 with Apache2 and freeBSD 4.9. It seems that php prefers the old style
 apache 1.3 work flow. I got some  help from the php guys, but not
 enough. I suppose I could have run a separate apache13 server, but
 that seems like a cop out to me. We don't want to maintain an extra
 set of configs etc etc.

I think mod_php doesn't play nice with apache2 but am not aware of any
cgi interoperability problems.  I ran squirrelmail/php as an apache
1.3 cgi a while back (low enough traffic to not get killed by cgi
overhead), if that helps.  Note that squirrelmail itself has a bunch
of security bugs that the maintainers refuse to acknowledge as bugs.
Anyway, I'm still using apache 1.3 (haven't had a reason to modernize)
so I can run mod_php if I need to.

 Mailman, moinmoin and others work fine with apache2 maybe because they
 use a cgi style interface. I would stick with a pythonic solution
 unless there's a good reason not too.

Yes, I certainly prefer Python to PHP.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Game programming in Python

2005-01-11 Thread Batista, Facundo
Title: RE: Game programming in Python





[Baza]


#- I'm looking for any books or on-line resources on game 
#- programming using
#- Python. Does anyone have any advice?


Check PyGame: http://www.pygame.org/


. Facundo


Bitácora De Vuelo: http://www.taniquetil.com.ar/plog
PyAr - Python Argentina: http://pyar.decode.com.ar/



  . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

ADVERTENCIA.


La información contenida en este mensaje y cualquier archivo anexo al mismo, son para uso exclusivo del destinatario y pueden contener información confidencial o propietaria, cuya divulgación es sancionada por la ley.

Si Ud. No es uno de los destinatarios consignados o la persona responsable de hacer llegar este mensaje a los destinatarios consignados, no está autorizado a divulgar, copiar, distribuir o retener información (o parte de ella) contenida en este mensaje. Por favor notifíquenos respondiendo al remitente, borre el mensaje original y borre las copias (impresas o grabadas en cualquier medio magnético) que pueda haber realizado del mismo.

Todas las opiniones contenidas en este mail son propias del autor del mensaje y no necesariamente coinciden con las de Telefónica Comunicaciones Personales S.A. o alguna empresa asociada.

Los mensajes electrónicos pueden ser alterados, motivo por el cual Telefónica Comunicaciones Personales S.A. no aceptará ninguna obligación cualquiera sea el resultante de este mensaje.

Muchas Gracias.



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

Re: Game programming in Python

2005-01-11 Thread Doug Holton
Baza wrote:
I'm looking for any books or on-line resources on game programming using
Python. Does anyone have any advice?
See http://pygame.org/
There is also a book called Game Programming with Python.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >