Re: Can I use a conditional in a variable declaration?

2006-03-19 Thread Ron Adam
[EMAIL PROTECTED] wrote:
> I've done this in Scheme, but I'm not sure I can in Python.
> 
> I want the equivalent of this:
> 
> if a == "yes":
>answer = "go ahead"
> else:
>answer = "stop"
> 
> in this more compact form:
> 
> 
> a = (if a == "yes": "go ahead": "stop")
> 
> 
> is there such a form in Python? I tried playing around with lambda
> expressions, but I couldn't quite get it to work right.


I sometimes find it useful to do:


 answers = {True: "go ahead", False: "stop"}

 answer = answers[a == "yes"]



This is also sometimes useful when you want to alternate between two values.

 values = {'a':'b', 'b':'a'}   # define outside loop

 while 1:
v = values[v] # alternate between 'a' and 'b'
 ...

There are limits to this, both the keys and the values need to be hashable.


Cheers,
   Ron













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


Re: ANNOUNCE: xlrd 0.5.2 -- extract data from Excel spreadsheets

2006-03-19 Thread John Machin
On 19/03/2006 2:30 PM, Kent Johnson wrote:
> John Machin wrote:
> 
>> On 19/03/2006 8:31 AM, Kent Johnson wrote:
>>
>>> How does xlrd compare with pyexcelerator? At a glance they look 
>>> pretty similar.
>>>
>>
>> I have an obvious bias, so I'll just leave you with a not-very-PC 
>> analogy to think about:
>>
>> Depending on the ambient light and the quantity of mead drunk in the 
>> hall, Helen of Troy and Grendel's mum might at a glance look pretty 
>> similar, too. Perhaps a more thorough investigation is needed. What 
>> about your requirements: a partner for the graduation ball, or someone 
>> to lift the truck off you when the jack collapses?
> 
> 
> That didn't shed much light. I'm interested in your biased opinion, 
> certainly you must have had a reason to write a new package.
> 
> I don't have current requirements for this, I'm curious.

* It's not new. First public release was on 2005-05-15. When I started 
writing it, there was no pure-Python Excel reading facility available at 
all. Roman Kiseliov's pyExcelerator was first announced on c.l.py.ann 
on 2005-03-22 (write only) and later with an import facility on 2005-05-12.

* I wrote it because I needed to get data out of Excel spreadsheets in a 
production environment. I had tried COM, ODBC, and manual save-as-CSV 
and all those approaches were unsatisfactory in terms of reliability and 
robustness.

* Creating Excel files: xlrd doesn't do this. If you have Python 2.4, 
pyExcelerator is the best choice. The alternative is PyXLWriter which 
works with Python 2.2 onwards but is no longer maintained and writes 
only the older Excel 5.0 / Excel 95 file format (no Unicode support, 
limited to 16K rows).

* Herewith the biased comparison:
[I've CCed Roman on this & the previous posting, by the way]

** Python versions: xlrd 2.1 to 2.4, pyExcelerator 2.4 only

** Excel file versions: xlrd 3.0 onwards, pyExcelerator 5.0 onwards [I 
doubt there are many 3.0, 4S and 4W files hanging about but I had some
Excel 4.0 files so I did it as a jeu d'esprit]

** Date support: Excel stores dates as real numbers of days sort-of 
since some variable date ... a long shocking story, read the xlrd docs. 
xlrd puts considerable effort into examining the formats used by number 
cells so that they can be classifed as date or not-date. It provides 
functions for converting between Excel date numbers and datetime tuples.

** Speed: On a 3.2GHz Intel P4 with 1 GB of RAM, xlrd loads a 128 Mb 
spreadsheet [yes sir, real live user data] in a little over a minute, 
while pyExcelerator takes a little over 3 minutes. Taking out half of 
that memory doesn't bother xlrd at all, but ...

** Memory footprint: pyExcelerator can use from 2.5 to 4 times as much 
memory as xlrd.

** Docs: xlrd has docs.

Hoping that shed some light :-)
Cheers,
John
-- 
http://mail.python.org/mailman/listinfo/python-list


python newb has problem with import statements

2006-03-19 Thread danielmcbrearty
Hi

Old hand at perl, giving python a try. Trying to get pymedia running on
my winxp box.

Have installed activestate python 2.4 and pymedia using precompiled
installers.

Problem is it SEEMS that the __init__.py is not getting run when I
import a module.

So, I have pymedia installed and it imports fine:

>>> import pymedia
>>> dir(pymedia)
['__builtins__', '__doc__', '__file__', '__name__']
>>>

the init file looks like this:

(docs and comments skipped)

print "in pymedia"  # added by me to see
__all__= [ 'muxer', 'audio', 'video', 'removable' ]
import muxer, audio, video, removable

but I can't import submodules of pymedia:

>>> import pymedia.sound
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named sound
>>>

if I do this

>>> from pymedia import *
>>> import pymedia.sound
Traceback (most recent call last):
  File "", line 1, in ?
ImportError: No module named sound
>>>

the weird thing is teh IDE (pythonwin) knows about the sub modules - it
shows them in the auto-suggest thingy when I type "pymedia."

so what's going on? do I have an install problem? (I did try removing
and reinstalling, no avail) am I just misunderstanding how this should
work?

all helpful stuff much appreciated

Daniel

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


Re: python newb has problem with import statements

2006-03-19 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> the init file looks like this:
> 
> (docs and comments skipped)
> 
> print "in pymedia"  # added by me to see
> __all__= [ 'muxer', 'audio', 'video', 'removable' ]
> import muxer, audio, video, removable
> 
> but I can't import submodules of pymedia:

The file with the contents given above is clearly not the one that is
imported here,

> >>> import pymedia
> >>> dir(pymedia)
> ['__builtins__', '__doc__', '__file__', '__name__']

as __all__, muxer, audio etc. are missing. 

Maybe you have created a test script 'pymedia.py' in the working directory?
You can check what file you are dealing with by entering

>>> pymedia.__file__ 

If that is 'whatever/site-packages/pymedia/__init__.pyc' I'm guessing wrong.
Otherwise removing that file (probably 'pymedia.pyc') and the corresponding
source (pymedia.py) should fix your problem.

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


Re: Can I use a conditional in a variable declaration?

2006-03-19 Thread Georg Brandl
Jeffrey Schwab wrote:
> [EMAIL PROTECTED] wrote:
> 
>> I want the equivalent of this:
>> 
>> if a == "yes":
>>answer = "go ahead"
>> else:
>>answer = "stop"
>> 
>> in this more compact form:
>> 
>> a = (if a == "yes": "go ahead": "stop")
>> 
>> is there such a form in Python? I tried playing around with lambda
>> expressions, but I couldn't quite get it to work right.
> 
> Rather than lambda, this merits a named function.  You only have to 
> define it once.
> 
> def mux(s, t, f):
>  if s:
>  return t
>  return f

But be aware that this is not a complete replacement for a syntactic
construct. With that function, Python will always evaluate all three
arguments, in contrast to the and/or-form or the Python 2.5 conditional.

You can show this with

test = mux(False, 1/0, 1)

and

test = False and 1/0 or 1

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


Re: Is Jython development active?

2006-03-19 Thread Ray
[EMAIL PROTECTED] wrote:
> Don't seem to see much progress in getting out a new version of Jython.
> The last beta was out in March 2005. When will a final release be made?

Not sure, but I've been checking jython-dev and jython-checkins once
every few days (yes, I am *that* interested in Jython).

Seems that Frank Wierzbicki and Otmar Humbel have been quite busy in
the past 2 months! :) Keep your fingers crossed.

I hope Frank will finish the new website and get back to Jython itself
soon. (Not to discount anything that Frank has been doing, but IMHO the
old website was just fine.)

For myself, I've been looking into Jython code whenever I have the
time, I hope I can help one day and contribute instead of just checking
those two lists like 4 times a week :)

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


Re: Python compiler

2006-03-19 Thread Rc

"robert" <[EMAIL PROTECTED]> schreef in bericht 
news:[EMAIL PROTECTED]
> Rc wrote:
>> "DaveM" <[EMAIL PROTECTED]> schreef in bericht
>> news:[EMAIL PROTECTED]
>>
>>>On Thu, 16 Mar 2006 13:34:14 +0100, "Méta-MCI"
>>><[EMAIL PROTECTED]> wrote:
>>>
>>>
Après, vous pourrez aussi fréquenter le newsgroup :
   fr.comp.lang.python
qui a l'avantage d'être en français.
>>>
>>>But perhaps he's a Flemish speaker - are you trying to start a riot?
>>>
>>>DaveM
>>
>> Yes,I'm a Flemish speaker, I have been to school in the evening
>> to study Englisch and also now for the last year I'm study French.
>> To improve my English it's maybe good to work with English
>> newsgroupes.I'm not looking for a riot,because I don't understand
>> the word.By the way, in case to learn Python,they told me it's
>> the most esay language to start.
>> But ,my question is when I start Python it is a Dos Window
>> that opened.I think it is not possible on a XP computer?
>> Or am I wrong.
>> Thanks by advances
>> Rc
>
> install Pythonwin (pywin32) for a GUI


Thank for the answers.But I have looked to several sites
where can I download that install Pythonwin(pywin32) for a GUI.
There are so much ,I don't no exactly, which site or which download.
Thanks by advance
Rc



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

Re: Python 2.5 Schedule

2006-03-19 Thread Gregory Petrosyan
Yes, it's very annoying to see VC8 warnings on perfectly legal C
constructs (AFAIK even sprinf is now considered "unsafe", MS wants
everybody to use sprintf_s). But the optimisation capacities of VC8 are
really great. Maybe someone can measure the speedup?

P.S. there's an "_CRT_SECURE_NO_DEPRECATE" flag that eliminates most of
this kind of warnings. Also, #pragma 's can be used (although this
isn't nice at all).

P.P.S. are there any experiments with compiling CPython with Intel's
compiler?

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


Re: ANNOUNCE: xlrd 0.5.2 -- extract data from Excel spreadsheets

2006-03-19 Thread Kent Johnson
John Machin wrote:
> On 19/03/2006 2:30 PM, Kent Johnson wrote:

>>That didn't shed much light. I'm interested in your biased opinion, 
>>certainly you must have had a reason to write a new package.
> 
> * It's not new. First public release was on 2005-05-15. When I started 
> writing it, there was no pure-Python Excel reading facility available at 
> all. Roman Kiseliov's pyExcelerator was first announced on c.l.py.ann 
> on 2005-03-22 (write only) and later with an import facility on 2005-05-12.

Ah, my mistake, sorry. I didn't recall hearing about xlrd before and 
jumped to the conclusion that it was new, though your OP is very clear 
that this is an update release.

> * Herewith the biased comparison:

Thank you!

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


Re: python library for web discussions

2006-03-19 Thread Gregory Petrosyan
reddit is written with webpy (webpy.org), maybe you should give it a
try?

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


Re: How do I use the subprocess module with mswindows?

2006-03-19 Thread Thomas Bellman
Darren Dale <[EMAIL PROTECTED]> wrote:

> import subprocess
> process = subprocess.Popen(['dir'], stderr=subprocess.STDOUT,
> stdout=subprocess.PIPE)
> stat = process.wait()
> print process.stdout.read()

You have already gotten the answer to why 'dir' doesn't work for
you, but there is a bug hiding in that code that you might not
notice in simple tests.

You are waiting for your subprocess to complete without reading
away what it prints.  That will quickly fill the buffer available
in the pipe between you and the subprocess, and the subprocess
will block.  Try calling Popen() with something that prints more
data, like ['find', '/', '-print'] on a Unix box, and you will
notice that problem.

What you should do is:

output = process.stdout.read()
stat = process.wait()
print output

Or, you could use the .communicate() method on the Popen object
instead of .stdout.read().

If you find yourself juggling several subprocesses running in
parallel, producing and/or consuming data "incrementally", or
just trying to handle both sending input to and reading output
from a single subprocess without deadlocking, you may be helped
by using my asyncproc module, which you can download from

http://www.lysator.liu.se/~bellman/download/asyncproc.py

I suspect that it only works on Unix, though.


-- 
Thomas Bellman,   Lysator Computer Club,   Linköping University,  Sweden
"Beware of bugs in the above code; I have!  bellman @ lysator.liu.se
 only proved it correct, not tried it."  !  Make Love -- Nicht Wahr!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: interrupting pythonD with ^C

2006-03-19 Thread Steve Holden
John Savage wrote:
> I'm finding that many times when I inadvertently code an endless loop
> in pythonD code, on MSDOS, execution cannot be interrupted by ctrl-C
> and I am forced to reboot and this is rapidly loses its novelty.
> 
> Do users of pythonD have a coding technique, or a library file to include,
> to endow a program with keyboard interrupt-ability?
> 
> Endless loops arise when I forget to increment a loop index, or code
> incorrectly the end condition test, or indent wrongly, etc.

Well, you could try programming more carefully :-)

Alternatively, try CTRL/Break. That seems to interrupt even when a 
program is waiting on a network socket, which CTRL/C doesn't seem to.

Note, however, that this terminates the process without raising 
KeyboardInterrupt.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


Re: Can I use a conditional in a variable declaration?

2006-03-19 Thread andy
[EMAIL PROTECTED] wrote:

>I've done this in Scheme, but I'm not sure I can in Python.
>
>I want the equivalent of this:
>
>if a == "yes":
>   answer = "go ahead"
>else:
>   answer = "stop"
>
>in this more compact form:
>
>
>a = (if a == "yes": "go ahead": "stop")
>
>
>is there such a form in Python? I tried playing around with lambda
>expressions, but I couldn't quite get it to work right.
>
>  
>
How about:

a = ["stop","go ahead"][a == "yes"]

This works because:

>>> int("yes" == "yes")
1
>>> int("yes" == "no")
0

Taking into account all the previous comments - both the literal list
elements are evaluated; there is no short-cirtuiting here. If they're
just literals, it's no problem, but if they're (possibly
compute-intensive) function calls, it would matter. I find the list
evaluation easier to parse than the and/or equation, and in instances
where that would be necessary, I will use the longhand if ... else ...
structure for readability.

hth,
-andy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python library for web discussions

2006-03-19 Thread Amir Michail
Gregory Petrosyan wrote:
> reddit is written with webpy (webpy.org), maybe you should give it a
> try?

I'm looking for a library that provides commenting on items in a
similar way to reddit/digg/slashdot.  I would rather not write all that
code from scratch.

I don't think web.py comes with that functionality, although of course,
some free package may provide it on top of web.py.

Amir

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


Re: Getting .NET SDK to work with Python 2.4.2

2006-03-19 Thread gregarican
Dave wrote:

> yea i have .net 1.1, but not the sdk. do i need the 1.1 SDK too?

I think so. The .Net 1.1 runtime (i.e. - not the SDK) is missing the
support files necessary for compiling programs. Gotta love those huge
downloads. I thought the Java SDK's were big :-)~

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


Counting number of each item in a list.

2006-03-19 Thread sophie_newbie
I have a list a little something like this:

StringA
StringC
StringB
StringA
StringC
StringD
StringA
...
etc.

Basically I was wondering if there was an easy way to return how many
of each string are in the list, something like this:

StringA - 3
StringB - 1
StringC - 2
StringD - 1

I suppose that the easiest way to do that is to convert it to a 2
dimensional array? Is there any easy way?

Thanks.

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


Re: Getting .NET SDK to work with Python 2.4.2

2006-03-19 Thread Martin v. Löwis
Dave wrote:
> So i go to the cmd and go to the directory and type
> "python setup.py build" (Will have to install after) and it comes up
> with this(after everything else runs smoothly):
> running build_ext
> error: The .NET SDK needs to be installed before building extensions
> for python.

The error message is misleading. It is not the SDK that you need,
but Visual Studio 7.1.

Alternatively, you can try building the extension with the GNU
mingw32 compiler.

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


Want to re-pack() a Frame displaying a collection

2006-03-19 Thread Charles Krug
List,

I'd like to do the following with Tkinter's Frame() object:

1. Display a collection of pack()-able objects.  Easy.  Done.  I hold
the objects in a dictionary, mostly so that the owning program can refer
to them uniformly.

2. Whenever the collection is added to or deleted from, re-pack() the
owning object.

Will this happen automatically simply whenever I add or delete from the
object's __dict__, or do I need to add to __setattr__ and __delattr__ to
detect when the user has added or removed an object?

Thanks

Not Quite Related:

I'm doing a lot of displaying of (Label, Entry) pairs so I've another
subclass of Frame() that simplifies that action for me.  These are items
from a collection that's created at runtime where the labels aren't
known in advance.

Right now, I'm raising an exception if grid() or place() is called on
the object.  Eventually, what I'd like to do is flesh out the grid() and
place() methods so that the Label and Entry are placed in what I think
are sensible default positions reletive to the desired placement.

With grid(), how do I determine my current column and row in the case
when grid() is invoked without arguments?

With place() . .pretty much the same song.  I need to determine my
position so that I can Do The Right Thing (or at least the expected
thing).

Thanks




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


Re: Counting number of each item in a list.

2006-03-19 Thread Paul Rubin
"sophie_newbie" <[EMAIL PROTECTED]> writes:
> I suppose that the easiest way to do that is to convert it to a 2
> dimensional array? Is there any easy way?

Use a hash table.  Untested:

   h = 0
   for x in your_list:
  h[x] = h.get(x, 0) + 1

You can then use something like sorted(h.items()) to get a sorted list
of those counts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting .NET SDK to work with Python 2.4.2

2006-03-19 Thread Dave
Well i don't have the whole visual studio. I don't have 7 either, I
have 8. I have VB and VC++ Express. If there is no way to download VS7,
could someone point me to directions on how to build the extensions
with mingw32?

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


Re: Python 2.5 Schedule

2006-03-19 Thread Pekka Niiranen
Hi,

what I would like to see in (www.python.org) is
Windows installation package (*.msi)
compiled with option "--enable-unicode=ucs4".
See http://www.xml.com/pub/a/2005/06/15/py-xml.html

-pekka-

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


Re: Counting number of each item in a list.

2006-03-19 Thread Bruno Desthuilliers
sophie_newbie a écrit :
> I have a list a little something like this:
> 
> StringA
> StringC
> StringB
> StringA
> StringC
> StringD
> StringA
> ...
> etc.
> 
> Basically I was wondering if there was an easy way to return how many
> of each string are in the list, something like this:
> 
> StringA - 3
> StringB - 1
> StringC - 2
> StringD - 1

There is.

str_list = ['StringA', 'StringC', 'StringB',
 'StringA', 'StringC', 'StringD',
 'StringA' ]

str_counts = dict((s, str_list.count(s) for s in set(str_list))

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


Re: Counting number of each item in a list.

2006-03-19 Thread sophie_newbie
Hey Bruno,

I got an invalid syntax error when i tried using your "str_counts =
dict((s, str_list.count(s) for s in set(str_list))" bit of code? Maybe
there is a missing bracket or comma? Or maybe I need to import
something.

Thanks so much for your help.

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


Re: How to run SimpleHTTPServer on IronPython on Mono

2006-03-19 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
> Paul Boddie wrote:
> > [1] http://lists.debian.org/debian-legal/2005/08/msg00089.html
>
> Do you realize *I* was the person asking for clarification of the license
> on debian-legal mailing list?

Yes. And I thereby deduce that you also believe that having Debian
approval would mean a lot for IronPython's acceptance, since the Debian
people are regarded as being the most stringent with respect to Free
Software-compatible licensing in distributions.

> > If IronPython users consider themselves to be
> > part of the wider Python community, is it a good thing that they're
> > reliant on Microsoft to keep that community from fragmenting?
>
> I quite don't get what you are trying to say here.

This was about how CPython can get away from other implementations by
adding new features. As we've seen with Jython, if there's relatively
little community interest in keeping other Python implementations
up-to-date, and if there's no sponsor with the manpower on hand to do
the work, then everyone in the CPython camp is busy using such new
features in their code, while everyone else is busy wondering if
they'll ever see such new features. Microsoft seem to be committed to
delivering IronPython, and perhaps if they lose interest the community
will step in and do the work, but in such a situation I feel that the
whole Python community (users of CPython *and* other implementations
combined) will suffer "fragmentation" as CPython speeds ahead and
IronPython lags behind just as Jython has done.

Sure, choosing Jython or IronPython is usually a trade-off between
wanting some of the nice Python libraries and wanting access
respectively to Java and CLR libraries, and perhaps many people using
these implementations don't consider themselves as part of (or primary
members of) the wider Python community; if so, it could be said that
the Python "brand" is somewhat diminished already, since people may be
willing to accept slightly more limited variants of the language, using
implementation-specific libraries where standard library facilities
exist, and generally writing an increasingly divergent dialect of the
language.

Personally, I think that having more implementations is a good thing
for the language, mostly because it leads to new and interesting
technical opportunities, but more engagement and support from the
community "standards legislators" will definitely become necessary over
time to avoid confusion about what is and is not "proper Python",
especially if more people don't arrive at Python via CPython.

Paul

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


Re: Counting number of each item in a list.

2006-03-19 Thread sophie_newbie
Hi Paul,

Ur bit of code works, thanks so much, just for anyone reading this use
'h = {}' instead of h = 0.

Thanks

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


Problems redirecting STDOUT (NOT sys.stdout) to a pipe.

2006-03-19 Thread Elad
Hello All,

I am trying to capture some printf's from a C function called by
python.


I have tried to following:

STDOUT = 1# stdout fd
(re, we) = os.pipe()# Create re / write handlers
dup2(we, STDOUT)# override system's stdout, should dup first and
restore later..

call_my_hello_world()   # if stdout is not overriden will print hello
world on console screen

x = os.read(re, 11)

sadly, x = '' after the code is executed.

help ? :-)

Thanks, 

Elad.

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


Re: Getting .NET SDK to work with Python 2.4.2

2006-03-19 Thread Vincent Wehren

"Dave" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Well i don't have the whole visual studio. I don't have 7 either, I
| have 8. I have VB and VC++ Express. If there is no way to download VS7,
| could someone point me to directions on how to build the extensions
| with mingw32?
|

I used the free MS Visual C++ Toolkit 2003 successfully to compile 
extenstions before I had access to VS.
There's a how to here: http://www.vrplumber.com/programming/mstoolkit/

Regards,

Vincent Wehren 


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


Re: Have you ever considered of mousing ambidextrously?

2006-03-19 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 John Salerno <[EMAIL PROTECTED]> wrote:

> Roy Smith wrote:
> > In article <[EMAIL PROTECTED]>,
> >  Scott David Daniels <[EMAIL PROTECTED]> wrote:
> > 
> >> Roy Smith wrote:
> >>> I never understood why people switch mouse buttons.  I'm left handed, so 
> >>> I 
> >>> put the mouse on the left side of my keyboard.  It never occurred to me 
> >>> to 
> >>> flip the buttons around.
> >> Well, I switch 'em because the "forefinger is primary" is ingrained.
> > 
> > I do both buttons with my forefinger.  It just seems like the normal thing 
> > to do.
> 
> How do you manage that? Do you keep your finger hovered over the mouse? 
> It seems like quite an effort to move it back and forth between the two 
> buttons, unless you have a smaller mouse.

Mostly, I've got both hands on the keyboard.  I don't spend a lot of time 
holding the mouse.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting number of each item in a list.

2006-03-19 Thread Kent Johnson
sophie_newbie wrote:
> Hey Bruno,
> 
> I got an invalid syntax error when i tried using your "str_counts =
> dict((s, str_list.count(s) for s in set(str_list))" bit of code? Maybe
> there is a missing bracket or comma? Or maybe I need to import
> something.

It should be
str_counts = dict((s, str_list.count(s)) for s in set(str_list))

or for Python < 2.4
str_counts = dict([(s, str_list.count(s)) for s in set(str_list)])

Note that this solution iterates str_list once for each element of 
str_list - the call to count traverses the entire list to create the 
count. I expect Paul Rubin's solution will be dramatically faster for 
large lists as it only iterates str_list once.

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


Re: Getting .NET SDK to work with Python 2.4.2

2006-03-19 Thread Dave
So this means that I have to download .NET 1.1 SDK. Visual Studio 8
comes with msvcrt.lib, but im assuming it's the wrong version.

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


C-API: A beginner's problem

2006-03-19 Thread Fabian Steiner
I recently started learning C since I want to be able to write Python 
extension modules. In fact, there is no need for it, but I simply want 
to try something new ...

I tried to implement the bubblesort algorithm in C and to use it in 
python; bubblesort.c compiles fine, but whenever I want to import the 
modul and call the function I get a segmentation fault. This is what the 
code looks like:

static PyObject *py_bubblesort(PyObject *self, PyObject *args) {
PyObject *seq = NULL, *item, *newseq = NULL;
int seqlen, i;

if(!PyArg_ParseTuple(args, "O", &seq)) {
return NULL;
}
seq = PySequence_Fast(seq, "argument must be iterable");
if(!seq) {
return NULL;
}
seqlen = PySequence_Fast_GET_SIZE(seq);
int list[seqlen];
for (i = 0; i <= seqlen; i++) {
item = PySequence_Fast_GET_ITEM(seq, i);
list[i] = item;
}
bubblesort(list, seqlen);
newseq = PyList_New(seqlen);
if(!newseq) {
return NULL;
}
for(i = 0; i < seqlen; i++) {
PyList_SetItem(newseq, i, list[i]);
}

return newseq;

bubblesort(int list[], int seqlen) is doing the actual job and it is 
working.

What did I do wrong? As I am quite new to C, I probably made many 
mistakes, so please feel free to correct me.

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


Re: C-API: A beginner's problem

2006-03-19 Thread Heikki Salo
Fabian Steiner wrote:
> What did I do wrong? As I am quite new to C, I probably made many 
> mistakes, so please feel free to correct me.

The following line:

 > for (i = 0; i <= seqlen; i++) {

Should be "for (i = 0; i < seqlen; i++) {". Otherwise the last 
assignment will be out of bounds and probably corrupts heap.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 Schedule

2006-03-19 Thread Scott David Daniels
Gregory Petrosyan wrote:
> P.P.S. are there any experiments with compiling CPython with Intel's
> compiler?
Yup, the (older) Intel compiler was quite effective for 2,2 and 2.3
(at least), and I think at least one distro was built with it.

-- 
-Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python newb has problem with import statements

2006-03-19 Thread danielmcbrearty
that was indeed the problem. Thanks!

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


Re: C-API: A beginner's problem

2006-03-19 Thread Heikki Salo
Heikki Salo wrote:
> Fabian Steiner wrote:
>> What did I do wrong? As I am quite new to C, I probably made many 
>> mistakes, so please feel free to correct me.
> 
> The following line:
> 
>  > for (i = 0; i <= seqlen; i++) {
> 
> Should be "for (i = 0; i < seqlen; i++) {". Otherwise the last 
> assignment will be out of bounds and probably corrupts heap.

And closer look tells that the code should not even compile. Is the code 
cut & pasted directly? Line "list[i] = item;" tries to assign a pointer 
to an int-array, which should not compile. There are other similar oddities.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 Schedule

2006-03-19 Thread Martin v. Löwis
Pekka Niiranen wrote:
> what I would like to see in (www.python.org) is
> Windows installation package (*.msi)
> compiled with option "--enable-unicode=ucs4".
> See http://www.xml.com/pub/a/2005/06/15/py-xml.html

Just enabling that option is not enough: the resulting
binary likely crashes. In addition to changing the
type of Py_UNICODE, you also need change all calls to
Microsoft API that expects UCS-2 (i.e. all *W API).

Contributions are welcome.

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


Re: ANNOUNCE: xlrd 0.5.2 -- extract data from Excel spreadsheets

2006-03-19 Thread Scott David Daniels
Kent Johnson wrote:
> John Machin wrote:

>> * Herewith the biased comparison: 
> 
> Thank you!

Thank you (John) as well.  I realize you are a bit reluctant to toot
your own horn, but it is just this kind of biased comparison that
let's us know whether to investigate further.  It also helps that
you mention what pyExcelerator is good at.

-- 
-Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Computing correlations with SciPy

2006-03-19 Thread tkpmep
Tested it and it works like a charm! Thank you very much for fixing
this. Not knowing what an SVN is, I simply copied the code into the
appropriate library files and it works perfectly well.

May I suggest a simple enhancement: modify corrcoef so that if it is
fed two 1 dimensional arrays, it returns a scalar. cov does something
similar for covariances: if you feed it just one vector, it returns a
scalar, and if you feed it two, it returns the covariance matrix i.e:

>>> x = [1, 2, 3, 4, 5]

>>> z = [5, 4, 3, 2, 1]

>>> scipy.cov(x,z)
array([[ 2.5, -2.5],
   [-2.5,  2.5]])

>>> scipy.cov(x)
2.5

I suspect that the majority of users use corrcoef to obtain point
estimates of the covariance of two vectors, and relatively few will
estimate a covariance matrix, as this method tends not to be robust to
the presence of noise and/or errors in the data.

Thomas Philips

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


Initializing a list of lists

2006-03-19 Thread tkpmep
I want to create a list of lists, each of which is identical, but which
can be modified independently i.e:

>>>x = [ [0], [0], [0] ]
>>> x[0].append(1)
>>> x
[[0, 1], [0], [0]]

The above construct works if I have only few items, but if I have many,
I'd prefer to write
>>> N =3
>>> x =N*[[0]]
>>> x
[[0], [0], [0]]

If I now try extending the lists indepently, I cannot, as they all
point to the same list object
>>> x[0].append(1)
>>> x
[[0, 1], [0, 1], [0, 1]]

Is there a simple way to create a list of independent lists?

Thanks in advance

Thomas Philips

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


Re: C-API: A beginner's problem

2006-03-19 Thread Duncan Booth
Heikki Salo wrote:

> 
> And closer look tells that the code should not even compile. Is the
> code cut & pasted directly? Line "list[i] = item;" tries to assign a
> pointer to an int-array, which should not compile. There are other
> similar oddities. 

... such as the declaration of list at a point in the code which is not 
permitted in C, and using a non constant value for the length (which is 
also not allowed).
-- 
http://mail.python.org/mailman/listinfo/python-list


Relative paths in mod_python

2006-03-19 Thread Ivo van der Sangen
I was wondering if I could use relative paths in a mod_python script. At
the moment I am defining a constant string
"/path/to/dir/where/script/resides". The problem with this is that when
I move the script including files I use to get metadata I have to change
this variable. The same problem occurs when I distribute the script; the
person using it will first have to modify it, which is not what I want. Is
it possible that a mod_python script has as current working directory
the directory where the script resides? At the moment os.getcwd()
returns '/'.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Initializing a list of lists

2006-03-19 Thread Tim Chase
> The above construct works if I have only few items, but if I have many,
> I'd prefer to write
> 
N =3
x =N*[[0]]
x
> 
> [[0], [0], [0]]
> 
> If I now try extending the lists indepently, I cannot, as they all
> point to the same list object
> 
x[0].append(1)
x
> 
> [[0, 1], [0, 1], [0, 1]]
> 
> Is there a simple way to create a list of independent lists?

My first thought would be

 >>> N = 10
 >>> x = [[0] for _ in range(N)]
 >>> x[0].append(1)
 >>> x
[[0, 1], [0], [0], [0], [0], [0], [0], [0], [0], [0]]

HTH,

-tkc



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


Re: Initializing a list of lists

2006-03-19 Thread ZeD
Ciao, [EMAIL PROTECTED] Che stavi dicendo?

> Is there a simple way to create a list of independent lists?

N=3
x=[[0] for e in range(N)]

-- 
Up da 1 giorno, 3 ore, 43 minuti e 10 secondi

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


Re: Can I use a conditional in a variable declaration?

2006-03-19 Thread Jeffrey Schwab
Georg Brandl wrote:
> Jeffrey Schwab wrote:
>> [EMAIL PROTECTED] wrote:
>>
>>> I want the equivalent of this:
>>>
>>> if a == "yes":
>>>answer = "go ahead"
>>> else:
>>>answer = "stop"
>>>
>> def mux(s, t, f):
>>  if s:
>>  return t
>>  return f
> 
> But be aware that this is not a complete replacement for a syntactic
> construct. With that function, Python will always evaluate all three
> arguments, in contrast to the and/or-form or the Python 2.5 conditional.

Absolutely true, and I should have mentioned it.  In languages that 
allow ?: syntax, I rarely rely on its short-circuit effect, but it 
certainly is a significant difference.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-API: A beginner's problem

2006-03-19 Thread Nick Smallbone
Duncan Booth wrote:
> Heikki Salo wrote:
>
> >
> > And closer look tells that the code should not even compile. Is the
> > code cut & pasted directly? Line "list[i] = item;" tries to assign a
> > pointer to an int-array, which should not compile. There are other
> > similar oddities.
>
> ... such as the declaration of list at a point in the code which is not
> permitted in C, and using a non constant value for the length (which is
> also not allowed).

They are allowed in C99, according to GCC's manual.

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


Problem with Install wxPython on Solaris10 x86

2006-03-19 Thread zjumty
I want to install wxPython 2.6 on Solaris10 x86.
I have passed "make install", and want to execute python setup.py
install. but i got some problems.

first i run "python setup.py install",and i got the following:

unable to execute cc: No such file or directory
error: command 'cc' failed with exit status 1

so, it seams no cc in my solaris10.

I have installed SunStudio11, and there is a cc at /opt/SUNWspro/bin
this cc is the suncc,so i added "/opt/SUNWspro/bin" to my PATH

but i still got problem :

cc: Warning: option -3 passed to ld
cc: No input file specified, no output generated
error: command 'cc' failed with exit status 1

I also tried to replace "cc" with "gcc", and still failed.

Anyone installed wxPython successfully on solaris10?

ps: sorry for my poor english.

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


Unpythonic? Impossible??

2006-03-19 Thread BrJohan
Assume having this class hierarchy: (in principle and without details)
class A(object):
class B1(A):
class B2(A):
class C1(A1):
class C2(A1):
class C3(B1):
class C4(B2):

each of those classes have an initializer __init__(self, data):  and an 
overloaded __new__(cls, data):

is it then possible to have this call:
obj = A(data)
return an instance of that particular class (e.g. class C3)  in the 
hierarchy that - as decided by the __new__ functions - is the 'correct' one?

A.__new__ could select between A, B1 and B2, while B1.__new__ could choose 
from B1, C3 and C4.

I know how to use a class factory - and could work around using such a 
mechanism. However I am interested to know if I could let the classes do the 
work by themselves.

/BJ 


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


Re: C-API: A beginner's problem

2006-03-19 Thread Duncan Booth
Nick Smallbone wrote:

> Duncan Booth wrote:
>> Heikki Salo wrote:
>>
>> >
>> > And closer look tells that the code should not even compile. Is the
>> > code cut & pasted directly? Line "list[i] = item;" tries to assign a
>> > pointer to an int-array, which should not compile. There are other
>> > similar oddities.
>>
>> ... such as the declaration of list at a point in the code which is not
>> permitted in C, and using a non constant value for the length (which is
>> also not allowed).
> 
> They are allowed in C99, according to GCC's manual.
> 
> 

Which just shows how long it is since I wrote any C.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unpythonic? Impossible??

2006-03-19 Thread Scott David Daniels
BrJohan wrote:
> Assume having this class hierarchy: (in principle and without details)
> class A(object):
> class B1(A):
> class B2(A):
> ...
> each of those classes have an initializer __init__(self, data):  and an 
> overloaded __new__(cls, data):
> 
> is it then possible to have this call:
> obj = A(data)
> return an instance of that particular class (e.g. class C3)  in the 
> hierarchy that - as decided by the __new__ functions - is the 'correct' one?
> 
> A.__new__ could select between A, B1 and B2, while B1.__new__ could choose 
> from B1, C3 and C4.
> 
> I know how to use a class factory - and could work around using such a 
> mechanism. However I am interested to know if I could let the classes do the 
> work by themselves.

Yes, it can be done.  Yes, it is unclear (and hence UnPythonic).
The class factory _is_ the straightforward way to do this.  The
following is the workaround (if you have to maintain A(...)):


 class A(object):
 def __new__(class_, *args, **kwargs):
 if class_ is A:
 if want_a_B1(*args, **kwargs):
 return B1(*args, **kwargs)
 elif want_a_B2(*args, **kwargs):
 return B2(*args, **kwargs)
 return object.__new__(class_) # Use *a,... except for object

 class B1(A):
 def __new__(class_, *args, **kwargs):
 if class_ is B1:
 if want_a_B1(*args, **kwargs):
 return B1(*args, **kwargs)
 elif want_a_B2(*args, **kwargs):
 return B2(*args, **kwargs)
 return super(B1, class_).__new__(class_, *args, **kwargs)


--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Rate of Flow in a Black Box

2006-03-19 Thread [EMAIL PROTECTED]
Hi all.

Here's the problem:  I've got a black box and a bunch of particles in
an environment.  The particles go into the black box, follow a path,
and pop out the end after some processing.  They are processed
first-in-first-out, like a queue.

Inside the black box is a physical layout that can be thought of as a
series of pipes or a lineup at an airport checkin.  The interior layout
can change at runtime (ie, a pipe can be rerouted or the airline
employee can move one of the fabric cordons).  But it is a black box
and we don't know the layout at any given time.

The particles are either Red or Green.  Green particles report their
positions to the server every x seconds.  Red particles do not.  So the
only information we can get out of the black box is the positions of
the green particles as they make their way through the pipes.
Furthermore, there is some errorFactor when a particle reports its
position to the server.  So if two lengths of pipe are close together,
a Green particle could report that it is in a position that would
actually be in the other length of pipe.  The only knowledge the server
has is the reported positions of the Green particles over time, and a
rectangle where the black box is located.

When the particles get to the end of the pipe, they are processed in
batches of 4-8 and then spit out of the black box.  The position where
they are spit out is far away from the rest of the black box, so we
know for sure when a particle is out.

I need to estimate how long it is going to take a new particle entering
the black box to get processed.

First I'll just ask if this is a well known problem or could be
shoehorned into a well known problem.  And additionally - is there some
existing Python library / code that solves it.

I've got 3 (mediocre) candidate solutions, but it seems like something
that should be already solved.

-sjbrown

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


Re: Counting number of each item in a list.

2006-03-19 Thread Bruno Desthuilliers
sophie_newbie a écrit :
> Hey Bruno,
> 
> I got an invalid syntax error when i tried using your "str_counts =
> dict((s, str_list.count(s) for s in set(str_list))" bit of code? Maybe
> there is a missing bracket or comma? 

Yes, sorry, see Kent's post for the correction.

> Or maybe I need to import
> something.

Nope, unless you're running python < 2.4

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


Re: Counting number of each item in a list.

2006-03-19 Thread bearophileHUGS
With CPython this is probably the faster version, the version with
list.count() has to be used only if you are sure to always have a short
input list, because it's O(n^2):

str_list = ['StringA', 'StringC', 'StringB',
 'StringA', 'StringC', 'StringD',
 'StringA' ]

str_counts = {}
for s in str_list:
if s in str_counts:
str_counts[s] += 1
else:
str_counts[s] = 1

Bye,
bearophile

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


Re: Counting number of each item in a list.

2006-03-19 Thread Bruno Desthuilliers
Kent Johnson a écrit :
> sophie_newbie wrote:
> 
>> Hey Bruno,
>>
>> I got an invalid syntax error when i tried using your "str_counts =
>> dict((s, str_list.count(s) for s in set(str_list))" bit of code? Maybe
>> there is a missing bracket or comma? Or maybe I need to import
>> something.
> 
> 
> It should be
> str_counts = dict((s, str_list.count(s)) for s in set(str_list))

Of course, my bad :(

> or for Python < 2.4

from sets import Set as set
> str_counts = dict([(s, str_list.count(s)) for s in set(str_list)])
> 
> Note that this solution iterates str_list once for each element of 
> str_list

once for each *distinct* element or str_list (it iterates over the set 
created from str_list).

> - the call to count traverses the entire list to create the 
> count. I expect Paul Rubin's solution will be dramatically faster for 
> large lists as it only iterates str_list once.

Yeps. But I would benchmark it before choosing one or the other solution.
-- 
http://mail.python.org/mailman/listinfo/python-list


[ann] markup.py - HTML/XML generator

2006-03-19 Thread Daniel Nogradi
Just in case the thought of not having a millionth implementation of a
HTML/XML generator for Python makes the world as we know it a
miserable place, well then your suffering might be over soon since
exactly the one millionth implementation is out. You can download
markup.py from

http://markup.sourceforget.net/

Oh, and the code is in the public domain.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-API: A beginner's problem

2006-03-19 Thread Fabian Steiner
Heikki Salo wrote:
> Heikki Salo wrote:
>> Fabian Steiner wrote:
>>> What did I do wrong? As I am quite new to C, I probably made many 
>>> mistakes, so please feel free to correct me.
>>
>> The following line:
>>
>>  > for (i = 0; i <= seqlen; i++) {
>>
>> Should be "for (i = 0; i < seqlen; i++) {". Otherwise the last 
>> assignment will be out of bounds and probably corrupts heap.
> 
> And closer look tells that the code should not even compile. Is the code 
> cut & pasted directly? Line "list[i] = item;" tries to assign a pointer 
> to an int-array, which should not compile. There are other similar 
> oddities.

Okay, thank you (and the others) for these hints. As you see, I am quite 
new to C and I just wrote these lines by using parts I have found in the 
newsgroup. Unfortunately, the Python C-API documentation / tutorial 
won't help me since it is quite difficult to understand because of the 
lack of basics.

What do I have to change in order to make the code work?

Thank you very much in advance!

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


Re: Python equivalent of Perl-ISAPI?

2006-03-19 Thread Waldemar Osuch
What Roger says and also:
http://pyisapie.sourceforge.net/

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


Re: Unpythonic? Impossible??

2006-03-19 Thread Felipe Almeida Lessa
Em Dom, 2006-03-19 às 08:54 -0800, Scott David Daniels escreveu:
>  class A(object):
>  def __new__(class_, *args, **kwargs):
>  if class_ is A:
>  if want_a_B1(*args, **kwargs):
>  return B1(*args, **kwargs)
>  elif want_a_B2(*args, **kwargs):
>  return B2(*args, **kwargs)
>  return object.__new__(class_) # Use *a,... except for object
> 
>  class B1(A):
>  def __new__(class_, *args, **kwargs):
>  if class_ is B1:
>  if want_a_B1(*args, **kwargs):
>  return B1(*args, **kwargs)
>  elif want_a_B2(*args, **kwargs):
>  return B2(*args, **kwargs)
>  return super(B1, class_).__new__(class_, *args, **kwargs)

Why you have that if on B1.__new__? B1 will be created only by
A.__new__, which already did a check.

-- 
Felipe.

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

Re: Unpythonic? Impossible??

2006-03-19 Thread BrJohan

"Scott David Daniels" <[EMAIL PROTECTED]> skrev i meddelandet 
news:[EMAIL PROTECTED]
> BrJohan wrote:
...
>> is it then possible to have this call:
>> obj = A(data)
>> return an instance of that particular class (e.g. class C3)  in the 
>> hierarchy that - as decided by the __new__ functions - is the 'correct' 
>> one?
>>
>> A.__new__ could select between A, B1 and B2, while B1.__new__ could 
>> choose from B1, C3 and C4.
>>
>> I know how to use a class factory - and could work around using such a 
>> mechanism. However I am interested to know if I could let the classes do 
>> the work by themselves.
>
> Yes, it can be done.  Yes, it is unclear (and hence UnPythonic).
> The class factory _is_ the straightforward way to do this.  The
> following is the workaround (if you have to maintain A(...)):
>
>
> class A(object):
> def __new__(class_, *args, **kwargs):
> if class_ is A:
> if want_a_B1(*args, **kwargs):
> return B1(*args, **kwargs)
> elif want_a_B2(*args, **kwargs):
> return B2(*args, **kwargs)
> return object.__new__(class_) # Use *a,... except for object
>
> class B1(A):
> def __new__(class_, *args, **kwargs):
> if class_ is B1:
> if want_a_B1(*args, **kwargs):
> return B1(*args, **kwargs)
> elif want_a_B2(*args, **kwargs):
> return B2(*args, **kwargs)
> return super(B1, class_).__new__(class_, *args, **kwargs)
>
>
> --Scott David Daniels
> [EMAIL PROTECTED]

Agreed that the class factory method most often (maybe always) is the best 
one. For certain reasons, and in this particular case, I prefer the 
UnPythonic way. Sometimes it's good to have "more than one way to do it".

It was the "return object.__new__(class_) " that I did not came to think of 
myself, that did it. Thank you for yor helpfulness.

BrJohan 


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


Re: Relative paths in mod_python

2006-03-19 Thread Jochem Berndsen
Ivo van der Sangen wrote:
> I was wondering if I could use relative paths in a mod_python script. At
> the moment I am defining a constant string
> "/path/to/dir/where/script/resides".
> [snip]

You can use Python's built-in __file__ variable. It is set to the absolute
location of your script. You can then use one of the built-in functions in
the `os' module (I forgot which) to extract the directory your script
resides.

Jochem.

-- 
E-mail address encrypted using ROT13.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Server applications - avoiding sleep

2006-03-19 Thread Lev Elbert
You can make it a service, which has an advantage, that it survives logouts. 
SOME PROGRAMMING IS REQIURED. If I need something running the "fast and 
dirty" way, I run a regular python application as window application (start 
pythonw.exe).
As a way o communication (start, stop, pause) I use tray. If you nee an 
example of such a program, I can send one.

"rodmc" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>I have written a small server application (for Windows) which handles
> sending and receiving information from an instant messaging client and
> a database. This server needs to run 24/7, however it stops when the
> computer screen is locked.
>
> I assume there is a way to make it run in the background 24/7 but how
> do I go about doing this?
>
> At present the application runs from within a wxPython GUI, however
> this is only used to start and stop it. It could be entire faceless and
> the GUI only used to execute it.
>
> Best,
>
> rod
> 


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


Re: Unpythonic? Impossible??

2006-03-19 Thread Scott David Daniels
Felipe Almeida Lessa wrote:
> Em Dom, 2006-03-19 às 08:54 -0800, Scott David Daniels escreveu:
>>  class A(object):
>>  def __new__(class_, *args, **kwargs):
>>  if class_ is A:
>>  if want_a_B1(*args, **kwargs):
>>  return B1(*args, **kwargs)
>>  elif want_a_B2(*args, **kwargs):
>>  return B2(*args, **kwargs)
>>  return object.__new__(class_) # Use *a,... except for object
>>
>>  class B1(A):
>>  def __new__(class_, *args, **kwargs):
>>  if class_ is B1:
>>  if want_a_B1(*args, **kwargs):
>>  return B1(*args, **kwargs)
>>  elif want_a_B2(*args, **kwargs):
>>  return B2(*args, **kwargs)
>>  return super(B1, class_).__new__(class_, *args, **kwargs)
> 
> Why you have that if on B1.__new__? B1 will be created only by
> A.__new__, which already did a check.

Of course your are right.  It needs to be more like:
   class B1(A):
   def __new__(class_, *args, **kwargs):
   if class_ is B1:
   if want_a_C1(*args, **kwargs):
   return C1(*args, **kwargs)
   elif want_a_C2(*args, **kwargs):
  return C1(*args, **kwargs)
   return super(B1, class_).__new__(class_, *args, **kwargs)


--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Writing web bots in python

2006-03-19 Thread Ben C
On 2006-03-18, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hello,
> I hav a question..How do I write a webbot that logs onto some website,
> fills text into a textbox and submit that form, Sorry I am a novice in
> python, apparently I have to use urllib, but I hav a few queries on
> this, What happens when there are more input interfaces..does urllib
> make somekind of a template when it does so..need more info on
> this..links and tutorilas would be appreciated..thanx

Not strictly Python related, but if you use Firefox, get the "Tamper
Data" extension for it. This lets you see exactly what Firefox is
submitting in the formdata, and what the urls are of the cgi scripts
etc.

I usually invoke a program called curl from python with os.popen, but
this twill someone has suggested looks interesting.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting number of each item in a list.

2006-03-19 Thread Bruno Desthuilliers
Bruno Desthuilliers a écrit :
> Kent Johnson a écrit :
> 
>> sophie_newbie wrote:
>>
>>> Hey Bruno,
>>>
>>> I got an invalid syntax error when i tried using your "str_counts =
>>> dict((s, str_list.count(s) for s in set(str_list))" bit of code? Maybe
>>> there is a missing bracket or comma? Or maybe I need to import
>>> something.
>>
>>
>>
>> It should be
>> str_counts = dict((s, str_list.count(s)) for s in set(str_list))
> 
> 
> Of course, my bad :(
> 
>> or for Python < 2.4
> 
> 
> from sets import Set as set
> 
>> str_counts = dict([(s, str_list.count(s)) for s in set(str_list)])
>>
>> Note that this solution iterates str_list once for each element of 
>> str_list
> 
> 
> once for each *distinct* element or str_list (it iterates over the set 
> created from str_list).
> 
>> - the call to count traverses the entire list to create the count. I 
>> expect Paul Rubin's solution will be dramatically faster for large 
>> lists as it only iterates str_list once. 
> 
> Yeps. But I would benchmark it before choosing one or the other solution.

And of course, I was right. My solution seems to be faster than Paul's 
one (but slower than bearophile's), be it on small, medium or large lists.

nb: A is mine, B is Paul's and C is bearophile's, and the number after 
is the size of the list...

A100 (1 times): 1.5801050663
B100 (1 times): 1.87287902832
C100 (1 times): 0.991976976395
A1 (100 times): 1.083589077
B1 (100 times): 1.30713891983
C1 (100 times): 0.988032817841
A100 (10 times): 10.5345788002
B100 (10 times): 13.094493866
C100 (10 times): 9.67438292503


source:

def countA(lst):
 return dict((s, lst.count(s)) for s in set(lst))

def countB(lst):
 counts = {}
 for s in lst:
 counts[s] = counts.get(s, 0)+1
 return counts

def countC(lst):
 counts = {}
 for s in lst:
 if s in counts:
 counts[s] += 1
 else:
 counts[s] = 1
 return counts

def mklst(ln):
 from random import choice
 items = ['abc', 'def', 'ghi', 'jkl', 'mno',
  'pqr', 'stu', 'vwx', 'yz']
 return [choice(items) for i in range(ln)]

lst100 = mklst(100)
lst1 = mklst(1)
lst100 = mklst(100)

def run():
 from timeit import Timer

 timers = [
 ('A100',
  Timer('countA(lst100)',
'from __main__ import countA, lst100'),
  1),
 ('B100',
  Timer('countB(lst100)',
'from __main__ import countB, lst100'),
  1),
 ('C100',
  Timer('countC(lst100)',
'from __main__ import countC, lst100'),
  1),
 ('A1',
  Timer('countA(lst1)',
'from __main__ import countA, lst1'),
  100),
 ('B1',
  Timer('countB(lst1)',
'from __main__ import countB, lst1'),
  100),
 ('C1',
  Timer('countC(lst1)',
'from __main__ import countC, lst1'),
  100),
 ('A100',
  Timer('countA(lst100)',
'from __main__ import countA, lst100'),
  10),
 ('B100',
  Timer('countB(lst100)',
'from __main__ import countB, lst100'),
  10),
 ('C100',
  Timer('countC(lst100)',
'from __main__ import countC, lst100'),
  10),
 ]

 for name, timer, repeat in timers:
 print "%s (%s times): %s" % (name,
  repeat,
  timer.timeit(repeat))




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


Re: Relative paths in mod_python

2006-03-19 Thread Bruno Desthuilliers
Ivo van der Sangen a écrit :
> I was wondering if I could use relative paths in a mod_python script. At
> the moment I am defining a constant string
> "/path/to/dir/where/script/resides". The problem with this is that when
> I move the script including files I use to get metadata I have to change
> this variable. The same problem occurs when I distribute the script; the
> person using it will first have to modify it, which is not what I want. Is
> it possible that a mod_python script has as current working directory
> the directory where the script resides? At the moment os.getcwd()
> returns '/'.

You could set this constant in the apache conf as a PythonOption. And/Or 
you could post this question to mod_python's mailing list !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python cgi permision error

2006-03-19 Thread [EMAIL PROTECTED]
Sorry accidently replying using my other google account

[EMAIL PROTECTED] wrote:
> >
> > assuming you are running this python script the standard cgi way and not
> > through modpython or fastcgi.
> yes I'm running it in standard cgi way coz my provider only allow me
> that way.
And it's really just simple script. Sorry for the dumb question, I know
modpython but what do you mean by fast cgi
>
> >
> > try debugging this way.
> >
> > execute the python script from command line as the web user.
> >
> > make sure your python script prints the standard
> >
> > """Content-type: text/html
> >
> > """
>
Yess I've done that. I have also run it on windows machine and it work.
It seem my apache from SuSE 10.0 had some weird error permision that I
don't understand when running cgi. I'm also had that kinda error if I
running other cgi on perl or binary cgi :(

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


Re: message box halts prgram flow

2006-03-19 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> HI
> 
> I am creating a tkinter app.
> 
> example
> 
> tkMessageBox.showinfo("Window Text", "A short message")
> print "blah"
> 
> The execution of the application halts when the message box is
> displayed until the user clicks OK, then "blah is printed.

Yeps, this is pretty much what anyone would expect from a sensible GUI 
toolkit.

> 
> However I want the program to display message box and continue on to
> print blah without waiting for user response.

What's your use case ?

> Any suggestions on how to go about this?

Either use a non-modal window instead of a modal dialog box or use 
different threads.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting number of each item in a list.

2006-03-19 Thread Paul Rubin
Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
> And of course, I was right. My solution seems to be faster than Paul's
> one (but slower than bearophile's), be it on small, medium or large
> lists.
> 
> nb: A is mine, B is Paul's and C is bearophile's, and the number after
> is the size of the list...

Interesting.  I wonder if you could try it with a much larger number
of distinct values in the list.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting number of each item in a list.

2006-03-19 Thread Justin Azoff
Bruno Desthuilliers wrote:
> And of course, I was right. My solution seems to be faster than Paul's
> one (but slower than bearophile's), be it on small, medium or large lists.

Your version is only fast on lists with a very small number of unique
elements.

changing mklist to have
items = range(64) instead of the 9 item list and re-timing you will get
"better" results:

A100 (1 times): 7.63829684258
B100 (1 times): 1.34028482437
C100 (1 times): 0.812223911285

A1 (100 times): 9.78499102592
B1 (100 times): 1.26520299911
C1 (100 times): 0.857560873032

A100 (10 times): 87.6713900566
B100 (10 times): 12.7302949429
C100 (10 times): 8.35931396484



-- 
- Justin

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


Re: remove a directory with special chars

2006-03-19 Thread Peter Hansen
andy wrote:
> Is there a special reason you want to use Python to do this?  The Linux
> command shell would probably do exactly the same job (you can specify
> backslash-escaped characters at the command-line)...
> 
> anyway to do it in python:
> 
>   import os
>   os.remove("/path/to/the/file/.\177\177")
> 
> Note that under Linux, hidden files start with a "." - that's what makes
> them hidden.
> 
> By the way, "\177" (decimal 79) is a letter "O"... I suspect you meant
> "\011" (decimal 9) which is backspace...

Actually, \177 is DEL, while the letter O is \117.

Definitely confusing, but then octal sucks anyway.

-Peter

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


[ANN] PyGNUGK v3.50 is out

2006-03-19 Thread Jerome Alet
Hi there,

I'm pleased to announce PyGNUGK v3.50 which is available under the terms
of the GNU GPL from :

  http://cortex.unice.fr/~jerome/pygnugk/

PyGNUGK is a Python library which allows full control over one or more
instances of the GNU GateKeeper (http://www.gnugk.org) from any Python
program.

PyGNUGK comes with :

  - The Python library.

  - Sample code :

- A sample program which can be run :

  - From the command line : it prints plain text, HTML or XML reports
  about the list of registered endpoints and ongoing calls.

  - As a CGI script : When there's no user authentication, it allows
  the same reports as from the command line. With user authentication
  (i.e. Apache's .htaccess files) the HTML report contains links which
  can disconnect active calls or endpoints and unregister endpoints.

- A test program which tests all available functions of the gatekeeper.

- A Zope Product : For now it can produce HTML and XML reports, but
  more features will be added later.

NB : the sample programs can be used directly, however for advanced needs
you have to use the library.

A screenshot of the CGI script taken from an earlier release is available
from :

http://cortex.unice.fr/~jerome/pygnugk/screenshot.png

Comments are very much welcome.

bye

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


Re: Counting number of each item in a list.

2006-03-19 Thread Bruno Desthuilliers
Paul Rubin a écrit :
> Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
> 
>>And of course, I was right. My solution seems to be faster than Paul's
>>one (but slower than bearophile's), be it on small, medium or large
>>lists.
>>
>>nb: A is mine, B is Paul's and C is bearophile's, and the number after
>>is the size of the list...
> 
> 
> Interesting.  I wonder if you could try it with a much larger number
> of distinct values in the list.

Please do, this could be interesting...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting number of each item in a list.

2006-03-19 Thread Bruno Desthuilliers
Justin Azoff a écrit :
> Bruno Desthuilliers wrote:
> 
>>And of course, I was right. My solution seems to be faster than Paul's
>>one (but slower than bearophile's), be it on small, medium or large lists.
> 
> 
> Your version is only fast on lists with a very small number of unique
> elements.
> 
> changing mklist to have
> items = range(64) instead of the 9 item list and re-timing you will get
> "better" results:
> 
> A100 (1 times): 7.63829684258
> B100 (1 times): 1.34028482437
> C100 (1 times): 0.812223911285
> 
> A1 (100 times): 9.78499102592
> B1 (100 times): 1.26520299911
> C1 (100 times): 0.857560873032
> 
> A100 (10 times): 87.6713900566
> B100 (10 times): 12.7302949429
> C100 (10 times): 8.35931396484
> 

Lol !-)

So much for my benchmarking skills...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Counting number of each item in a list.

2006-03-19 Thread Bruno Desthuilliers
Justin Azoff a écrit :
> Bruno Desthuilliers wrote:
> 

>> My solution seems to be faster than Paul's
>>one (but slower than bearophile's), be it on small, medium or large lists.
> 
> 
> Your version is only fast on lists with a very small number of unique
> elements.
> 
> changing mklist to have
> items = range(64) instead of the 9 item list and re-timing you will get
> "better" results:
> 
> A100 (1 times): 7.63829684258
> B100 (1 times): 1.34028482437
> C100 (1 times): 0.812223911285
> 
> A1 (100 times): 9.78499102592
> B1 (100 times): 1.26520299911
> C1 (100 times): 0.857560873032
> 
> A100 (10 times): 87.6713900566
> B100 (10 times): 12.7302949429
> C100 (10 times): 8.35931396484
> 
> 

Lol ! So much for my benchmarking skills :-/
-- 
http://mail.python.org/mailman/listinfo/python-list


whats your favourite object relational mapper?

2006-03-19 Thread Flavio
With so many object relational mappers out there, I wonder which one is
the preferred tool among the Pythonists... is there a favourite?

Sqlobject, PyDO, SQLAlchemy, dejavu, etc...

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


Re: Xah's Edu Corner: What is Expressiveness in a Computer Language

2006-03-19 Thread Xah Lee
What is Expressiveness in a Computer Language

Xah Lee, 200502, 200603.

In languages human or computer, there's a notion of expressiveness.

English for example, is very expressive in manifestation, witness all
the poetry and implications and allusions and connotations and
dictions. There are a myriad ways to say one thing, fuzzy and warm and
all. But when we look at what things it can say, its power of
expression with respect to meaning, or its efficiency or precision, we
find natural languages incapable.

These can be seen thru several means. A sure way is thru logic,
linguistics, and or what's called Philosophy of Languages. One can also
glean directly the incapacity and inadequacy of natural languages by
studying the artificial language lojban, where one realizes, not only
are natural languages incapable in precision and lacking in efficiency,
but simply a huge number of things are near impossible to express thru
them.

One thing commonly misunderstood in computing industry is the notion of
expressiveness. If a language has a vocabulary of (smile, laugh, grin,
giggle, chuckle, guffaw, cackle), then that language will not be as
expressive, as a language with just (severe, slight, laugh, cry). The
former is “expressive” in terms of nuance, where the latter is
expressive with respect to meaning.

Similarly, in computer languages, expressiveness is significant with
respect to semantics, not syntactical variation.

These two contrasting ideas can be easily seen thru Perl versus Python
languages, and as one specific example of their text pattern matching
capabilities.

Perl is a language of syntactical variegations. Lisp on the other hand,
is a example of austere syntax uniformity, yet its efficiency and power
in expression, with respect to semantics, showcases Perl's poverty in
specification.

Example: String Patterns in Regex

In Perl, the facilities for finding and replacing a text pattern is
this construct “$myText =~ s/myPattern/replStr/”.

In Python, it is “re.sub( myPattern, replStr, myText , myCount)”,
where the replacement string repStr can be a function, and a max number
of replacement myCount can be specified. If there is a match, and if
replStr is given a function myFunc instead, then a special regex match
object is feed to myFunc and it can return different strings based on
how the pattern is matched.

This is a instance where the language is more expressive. In Python's
regex facilities, there are several other flexibilities not present in
Perl. For example, its regex pattern can be frozen as a compiled object
and moved about. And, when a there is a match, Python returns a special
object that contains all information about the regex, such as the
original pattern, the number of matches, the set of matched strings and
so on, and this object can be passed around, or have information
extracted. These facilities are absent in Perl.

In this case, the flexibilities and facilities of Python's texual
patterns matching's capabilities a instance of superior expressiveness
to Perl's.

For more about Python's Regex machinery, see the Re-written Python
Regex Documentation at:
http://xahlee.org/python_re-write/lib/module-re.html

Example: Range, and Computation with Fractions

In Perl, there's a range construct “(a..b)” that returns a list of
numbers from a to b. However, this construct cannot generate a list
with regular intervals such as (1, 3, 5, 7, 9). Nor would it generate
decreasing lists such as (4, 3, 2, 1) when a > b.

In Python, its range function range(a,b,c) returns a range of numbers
from a to b with steps c. For example, range(3,-5, -2) returns [3, 2,
1, -1, -3]. The arguments can be negative, however, they all must be
integers.

In the Mathematica language, there's also a range function
Range[a,b,c]. Here, the arguments can be either real numbers or exact
fractions. If one of the input argument is a decimal, then the
computation is done as machine precision approximations and the result
list's elements are also in decimals. If all inputs are in fractions
(including integers), returned list's elements will also be exact
fractions.

In Mathematica, the language support fractions wherever a number is
used, and if all numbers are specified as fractions (or integers) in
the code, the result of the computation is also in exact fractions,
with it automatically in a reduced fraction form where common factors
in the numerator and denominator are taken out. (Fractions in
Mathematica is written as a/b with a and b integers.)

This section compares the expressiveness of a particular list
generating facility in 3 languages. But far more importantly, being
able to compute with fractions naturally is a expressibility unheard of
in non-commercial languages.
Example: Rich, Systematic Parameters for Functions

In many languages, there is a function called “map”. Usually it
takes the form map(f, myList) and returns a list where f is applied to
every element in myList. For example, here is a example from Python 

Re: Xah's Edu Corner: What is Expressiveness in a Computer Language

2006-03-19 Thread Dag Sunde
"Xah Lee" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> What is Expressiveness in a Computer Language

PLONK.

-- 
Dag.


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


Re: python library for web discussions

2006-03-19 Thread Irmen de Jong
Amir Michail wrote:
> Hi,
> 
> I'm building something like digg/reddit and would like to allow people
> to have discussions on various items.
> 
> Is there a simple lightweight python library that I can use (as opposed
> to a heavyweight web framework)?  Although not necessary, some sort of
> scoring/moderation mechanism would be good also (e.g., like
> reddit/slashdot).

If you don't mind that it is not possible to discuss in "threads",
you may want to have a look at my blog server "Frog":
http://snakelets.sourceforge.net/frog/

Ah, it doesn't support a scoring/moderation system too.
So it may not really suit your needs, but if you can't find
something else ;-)

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


Re: Xah's Edu Corner: What is Expressiveness in a Computer Language

2006-03-19 Thread John Bokma
"Dag Sunde" <[EMAIL PROTECTED]> wrote:

> "Xah Lee" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
>> What is Expressiveness in a Computer Language
> 
> PLONK.

Don't post PLONK messages you idiot. PLONK in silence instead of adding to 
a lot of garbage in serveral groups.

-- 
John Bokma  Freelance software developer
&
Experienced Perl programmer: http://castleamber.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


cmp() on integers - is there guarantee of returning only +-1 or 0?

2006-03-19 Thread Dmitry Anikin
doc says that it must be > 0, or < 0, but it seems that
it returns +1 or -1. Can it be reliably used to get the sign of x:
cmp(x, 0) like pascal Sign() function does? I mean, I'm
pretty sure that it can be used, but is it mentioned somewhere
in language spec, or it may be implementation defined?
If so, any other simple means of _reliably_ getting the sign?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Initializing a list of lists

2006-03-19 Thread Ron Adam
[EMAIL PROTECTED] wrote:
> I want to create a list of lists, each of which is identical, but which
> can be modified independently i.e:
> 
 x = [ [0], [0], [0] ]
 x[0].append(1)
 x
> [[0, 1], [0], [0]]
> 
> The above construct works if I have only few items, but if I have many,
> I'd prefer to write
 N =3
 x =N*[[0]]
 x
> [[0], [0], [0]]
> 
> If I now try extending the lists indepently, I cannot, as they all
> point to the same list object
 x[0].append(1)
 x
> [[0, 1], [0, 1], [0, 1]]
> 
> Is there a simple way to create a list of independent lists?


Try this...

 x, y, value = 3, 3, 0
 L = [[value]*x for i in xrange(y)]


Cheers,
Ron














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


How to check if a directory is exist in python?

2006-03-19 Thread yinglcs
I check the documentation here, but it does not say how to check if a
directory is exist in python?
http://docs.python.org/lib/os-file-dir.html

And why mkdir fails if the directory already exists?

Thank you.

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


Re: Xah's Edu Corner: What is Expressiveness in a Computer Language

2006-03-19 Thread Luc The Perverse
"John Bokma" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> "Dag Sunde" <[EMAIL PROTECTED]> wrote:
>
>> "Xah Lee" <[EMAIL PROTECTED]> wrote in message
>> news:[EMAIL PROTECTED]
>>> What is Expressiveness in a Computer Language
>> 
>> PLONK.
>
> Don't post PLONK messages you idiot. PLONK in silence instead of adding to
> a lot of garbage in serveral groups.

Sometimes you need to make a statement about a local troll.

Though I agree - a massively cross posted thread with no one familiar 
probably doesn't qualify

--
LTP

:) 


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


Re: python library for web discussions

2006-03-19 Thread Pierre Quentel
Take a look at Karrigell (http://www.karrigell.com), it has a built-in
forum application

Regards,
Pierre

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


Re: A Frame-space syntax ? - Re: global, globals(), _global ?

2006-03-19 Thread robert
Marc 'BlackJack' Rintsch wrote:

> In <[EMAIL PROTECTED]>, robert wrote:
> 
> 
>>The fact is:
>>* Python has that big problem with unnecessary barriers for nested frame 
>>access - especially painfull with callback functions where you want to 
>>put back data into the calling frame.
> 
> 
> You mean accessing the locals in the function that invoked the callback!? 
> That sounds ugly.  Makes it hard to decouple the caller and the callee
> here.
> 

That is a frequent need. For read's its anyway wired up. E.g. callbacks:

def f():
 a=1
 def g(var):
 print a # automatic
 .lastvar=var# binds in outer frame
 run_w_callback(1,2,g)
 print lastvar


Ruby blocks for example do that regularly.

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


Re: Relative paths in mod_python

2006-03-19 Thread Steve Holden
Ivo van der Sangen wrote:
> I was wondering if I could use relative paths in a mod_python script. At
> the moment I am defining a constant string
> "/path/to/dir/where/script/resides". The problem with this is that when
> I move the script including files I use to get metadata I have to change
> this variable. The same problem occurs when I distribute the script; the
> person using it will first have to modify it, which is not what I want. Is
> it possible that a mod_python script has as current working directory
> the directory where the script resides? At the moment os.getcwd()
> returns '/'.

 import os
 req.write(os.path.abspath(__file__))

seems to give you the absolute path to the module you are executing. You 
can use the other os.path primitives to extract the directory from that 
and use it to locate the associated data files.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


PyWeek #2 one week before the fun starts!

2006-03-19 Thread richard
The PyWeek challenge invites entrants to write a game in one week from
scratch either as an individual or in a team. Entries must be developed
in Python, during the challenge, and must incorporate some theme chosen
at the start of the challenge.

PyWeek #2 runs from Sunday 26th March to Sunday 2nd April (00:00UTC to
00:00UTC).

THEME VOTING HAS STARTED  --

To register for the challenge, visit:

   http://www.pyweek.org/



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


global statement and scoping

2006-03-19 Thread jochen . stier
Hi everyone,


I am compiling the following script using Py_CompileString


def compute(node):
#global compute

iter = node.getChild(0)
while iter:
if isinstance(iter, Group):
compute(iter)
print iter
iter = iter.next

compute(self.a0)


The I evaluate the script using PyEval_EvalCode and get a ''global name
"compute" is not
defined' error at the line of the recursive call. When I comment in the
"global" statement at the beginning of the function then everything
works fine. What's strange is the once I comment out the statement
again it still works... Somewhere something is written into a
dictionary in dunno where ?

Is it normal to have the global statement at the beginning of a
function like that ?

Cheers
Jochen

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


Re: cmp() on integers - is there guarantee of returning only +-1 or 0?

2006-03-19 Thread Paul Rubin
"Dmitry Anikin" <[EMAIL PROTECTED]> writes:
> doc says that it must be > 0, or < 0, but it seems that
> it returns +1 or -1. Can it be reliably used to get the sign of x:
> cmp(x, 0) like pascal Sign() function does? 

The doc says (http://docs.python.org/lib/built-in-funcs.html):

 cmp(x,y)
 Compare the two objects x and y and return an integer according
 to the outcome. The return value is negative if x < y, zero if
 x == y and strictly positive if x > y.

> I mean, I'm pretty sure that it can be used, but is it mentioned
> somewhere in language spec, or it may be implementation defined?

The doc doesn't specify that it returns -1/0/+1 so by definition
it's implementation defined.

> If so, any other simple means of _reliably_ getting the sign?

Ehh, every way I see offhand is at least a little bit messy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check if a directory is exist in python?

2006-03-19 Thread plahey
Check out os.path.isdir(path_name)

http://docs.python.org/lib/module-os.path.html

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


Re: How to check if a directory is exist in python?

2006-03-19 Thread Vincent Wehren
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I check the documentation here, but it does not say how to check if a
| directory is exist in python?
| http://docs.python.org/lib/os-file-dir.html

Look at the exist or isdir  methods of the os.path module 
(http://docs.python.org/lib/module-os.path.html}

|
| And why mkdir fails if the directory already exists?

If you prefer a "more friendly" approach you may wanna take a look at Trent 
Mick's _mkdir which is located at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82465
|

Regards,
Vincent Wehren

| Thank you.
| 


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


Pycrypto - active ??

2006-03-19 Thread dirvine
Does anyone know if pycrypto is active at all. I have been browsing
groups etc. for some info and have found entries from 2003 (latest)
regarding some bits I was looking for in particular reference to
symmetrical encoding (AES) and auto padding and supply or not of iv to
set up method i.e

from Crypto.Cipher import AES
from Crypto.Hash import SHA256
import random
import zlib
s = SHA256.new()
s.update('secret')
key = s.digest()
x = AES.new(key, AES.MODE_CBC) #  should be (key,AES.MODE_CBC,iv)

iv should according to docs (which also look very old) should be a
random number equal to the size of data blocks (in CBC or EBC). Does
anyone know if by not supplying iv - is the data secure or not ??

Auto iv and auto padding would help this project a lot but unknown as
to whether they exist. I may be missing an important point here though
- so correct me where you will.

It would appear to be a great shame if pyCrypto has stalled or not
taken on board more seriously, there's great talk of implementing TLS,
SSL etc. in the lists but little support of this visible in code or
docs. The docs examples don't exist in code but getting them from ATTIC
in cvs shows they are not stable, possibly not secure and not
representative of the code now (and that's a couple of years ago)


as an aside I have found a way to pad and remove padding at decrypt is
quite simple, use zlib.compress ->  pad -> encrypt
then
decrypt -> zlib.decompress and its just your data minus padding.

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


Re: How to check if a directory is exist in python?

2006-03-19 Thread Vincent Wehren
"Vincent Wehren" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| <[EMAIL PROTECTED]> wrote in message
| news:[EMAIL PROTECTED]
||I check the documentation here, but it does not say how to check if a
|| directory is exist in python?
|| http://docs.python.org/lib/os-file-dir.html
|
| Look at the exist or isdir  methods of the os.path module

Ofcourse I mean "exists"...

| (http://docs.python.org/lib/module-os.path.html}
|
||
|| And why mkdir fails if the directory already exists?
|
| If you prefer a "more friendly" approach you may wanna take a look at 
Trent
| Mick's _mkdir which is located at
| http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82465
||
|
| Regards,
| Vincent Wehren
|
|| Thank you.
||
|
| 


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


Re: Getting .NET SDK to work with Python 2.4.2

2006-03-19 Thread Vincent Wehren

"Dave" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| So this means that I have to download .NET 1.1 SDK. Visual Studio 8
| comes with msvcrt.lib, but im assuming it's the wrong version.
|

Yes, I'd say so.
--
Vincent Wehren 


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


Re: How to check if a directory is exist in python?

2006-03-19 Thread Steve Holden
Vincent Wehren wrote:
> | <[EMAIL PROTECTED]> wrote in message
> | news:[EMAIL PROTECTED]
> ||I check the documentation here, but it does not say how to check if a
> || directory is exist in python?
> || http://docs.python.org/lib/os-file-dir.html
> |
> | Look at the exist or isdir  methods of the os.path module
> 
> Ofcourse I mean "exists"...
> 
You also mean "functions", not "methods". *Classes* have methods.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd www.holdenweb.com
Love me, love my blog holdenweb.blogspot.com

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


Re: Have you ever considered of mousing ambidextrously?

2006-03-19 Thread Benji York
Aahz wrote:
> Heh.  When possible, my work situation includes two computers, each with
> their own keyboard and mouse.  To put the keyboards as close together as
> possible, the mice go on the outside.

I prefer a similar setup with 2 duel monitor PCs (one Linux, one 
Windows), but use x2vnc to control both with one keyboard and mouse.

Unfortunately neither x2vnc or Synergy really fulfill my needs though, 
so I'm working on a replacement.  Actually I'm writing this email 
instead of working on it, back to the (Vim) mines.
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pycrypto - active ??

2006-03-19 Thread [EMAIL PROTECTED]
Well, the homepage of Pycrypto (http://www.amk.ca/python/code/crypto)
was modified las in December 2005 - quite recent imo. It is used e.g.
in the paramiko package (http://www.lag.net/paramiko/) for the most(?)
used ssh implementation in Python, so my guess it is active.

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


Re: cmp() on integers - is there guarantee of returning only +-1 or 0?

2006-03-19 Thread [EMAIL PROTECTED]
It is depending on the classes you try to compare, and on how the
comparison functions (see
http://docs.python.org/ref/customization.html) are implemented in
these, see example below:

py> class wrong(object):
... def __init__(self, x):
... self.x = x
... def __cmp__(self, other):
... if self.x < other.x:
... return -1
... else:
... return 1
...
py> class right(object):
... def __init__(self, x):
... self.x = x
... def __cmp__(self, other):
... if self.x < other.x:
... return -1
... elif self.x > other.x:
... return 1
... else:
... return 0
...
py> w1 = wrong(1)
py> w2 = wrong(1)
py> cmp(w1, w2)
1
py>
py> r1 = right(1)
py> r2 = right(1)
py> cmp(r1, r2)
0

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


Re: Xah's Edu Corner: What is Expressiveness in a Computer Language

2006-03-19 Thread Roedy Green
On 19 Mar 2006 13:03:18 -0800, "Xah Lee" <[EMAIL PROTECTED]> wrote,
quoted or indirectly quoted someone who said :

>One thing commonly misunderstood in computing industry is the notion of
>expressiveness. If a language has a vocabulary of (smile, laugh, grin,
>giggle, chuckle, guffaw, cackle), 

Expressive for a natural language refers to the language's ability to
generate precisely generate moods, and move people emotionally in a
minimum of words.

Expressiveness in computer languages refers to the language's ability
to persuade the computer to produce some result in a minimum of words.

Another measure might be how smoothly elements of the language map
onto elements of the problem domain.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unpythonic? Impossible??

2006-03-19 Thread Erik Max Francis
BrJohan wrote:

> I know how to use a class factory - and could work around using such a 
> mechanism. However I am interested to know if I could let the classes do the 
> work by themselves.

You can, but a class factory is going to be much clearer and probably 
more maintainable.  From the user's perspective, there's no difference 
from calling a class A to instantiate it, and calling a factory function 
called A that selects the appropriate class and returns an instance of it.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Never had very much to say / Laugh last, laugh longest
   -- Des'ree
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C-API: A beginner's problem

2006-03-19 Thread Georg Brandl
Fabian Steiner wrote:
> I recently started learning C since I want to be able to write Python 
> extension modules. In fact, there is no need for it, but I simply want 
> to try something new ...
> 
> I tried to implement the bubblesort algorithm in C and to use it in 
> python; bubblesort.c compiles fine, but whenever I want to import the 
> modul and call the function I get a segmentation fault. This is what the 
> code looks like:
> 
> static PyObject *py_bubblesort(PyObject *self, PyObject *args) {
>   PyObject *seq = NULL, *item, *newseq = NULL;
>   int seqlen, i;

long it;

>   if(!PyArg_ParseTuple(args, "O", &seq)) {
>   return NULL;
>   }
>   seq = PySequence_Fast(seq, "argument must be iterable");
>   if(!seq) {
>   return NULL;
>   }
>   seqlen = PySequence_Fast_GET_SIZE(seq);
>   int list[seqlen];
>   for (i = 0; i <= seqlen; i++) {

That is one iteration too much. Use

for (i = 0; i < seglen; i++)

>   item = PySequence_Fast_GET_ITEM(seq, i);

Now item is a PyObject*. You'll have to convert it to an integer now:

it = PyInt_AsLong(item);
if (it == -1 && PyErr_Occurred()) {
Py_DECREF(seq);
/* set a new exception here if you like */
return NULL;
}

>   list[i] = it;
>   }
>   bubblesort(list, seqlen);
>   newseq = PyList_New(seqlen);
>   if(!newseq) {

Do not forget to DECREF seq:
Py_DECREF(seq);

>   return NULL;
>   }
>   for(i = 0; i < seqlen; i++) {
>   PyList_SetItem(newseq, i, list[i]);

List items must be PyObject*s, not plain ints. Use:
PyList_SetItem(newseq, i, PyInt_FromLong(list[i]));
(This is sloppy error checking, but if PyInt_FromLong fails you're out of
memory anyways ;)

>   }

Again, seq is not needed anymore:
Py_DECREF(seq);

>   return newseq;
> 
> bubblesort(int list[], int seqlen) is doing the actual job and it is 
> working.
> 
> What did I do wrong? As I am quite new to C, I probably made many 
> mistakes, so please feel free to correct me.

There's quite a bit you can overlook, especially stale references to PyObjects.
I'm not even sure the code compiles or runs correctly with my corrections ;)

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


  1   2   >