Re: Projects anyone?

2007-01-18 Thread [EMAIL PROTECTED]
I have a project available if you are intrested.  It is a music package
that includes everything from tracker style editing to code generators
for fltk(generates csound and python code) and dot code generation..
There is a huge range of possible projects and a little debugging so
you can even have your choice of tasks or come up with one of your own

https://sourceforge.net/projects/dex-tracker




placid wrote:
> Hi all,
>
> I'm looking for anyone who is working on a project at the moment that
> needs help (volunteer). The last project i worked on personally was
> screen-scraping MySpace profiles (read more at the following link)
>
> http://placid.programming.projects.googlepages.com/screen-scrapingmyspaceprofiles
>
>
> but that didn't go all to well, so im kinda bored and need something to
> do, with Python. So any suggestions anyone? 
> 
> Cheers

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


Re: cannot import libxml2 python module on windoze using activePerl or Python IDLE

2007-01-18 Thread Andrew Marlow
On Wed, 17 Jan 2007 18:34:38 +, Dennis Lee Bieber wrote:

>> I am not sure how python packages get installed on windoze.
>> Please can anyone help?
> 
> http://www.google.com/search?hl=en&q=libxml2+python&btnG=Google+Search
> http://users.skynet.be/sbi/libxml-python/

Thanks very much!

-Andrew Marlow

-- 
There is an emerald here the size of a plover's egg!
Don't top-post  http://www.catb.org/~esr/jargon/html/T/top-post.html
Plain text mails only, please  http://www.expita.com/nomime.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about module resolution

2007-01-18 Thread Peter Otten
Emin wrote:

> On Jan 17, 11:20 am, Peter Otten <[EMAIL PROTECTED]> wrote:
>> Emin wrote:
>> > I often find myself wanting to have a child module get some parameters
>> > defined in a parent module. For example, imagine  I have the following
>> > directory structure and want something in baz.py to look at a value in
>> > config.py. I end up putting in things like import sys;
>> > sys.path.append('../..'). Is there a better way?
>>
>> > foo/
>> >  __init__.py
>> >  config.py
>> >  bar/
>> >   __init__.py
>> >   baz.py

>> from __future__ import absolute_import  
>> from .. import config

> I put the lines you suggested in baz.py, but got an error:
> 
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
 import baz
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "baz.py", line 3, in 
> from .. import config
> ValueError: Attempted relative import in non-package

If you put foo/bar in the path and then

import baz

how do you think that baz is to know that it's actually foo.bar.baz?
Make sure that the parent directory of foo is in sys.path (e. g. by starting
the interpreter in that directory) and then import baz using its official
name.

$ tree
.
`-- foo
|-- __init__.py
|-- bar
|   |-- __init__.py
|   `-- baz.py
`-- config.py

2 directories, 4 files

$ cat foo/config.py
print "importing config"

$ cat foo/bar/baz.py
from __future__ import absolute_import
from .. import config

$ python2.5
Python 2.5 (r25:51908, Oct  3 2006, 08:48:09)
[GCC 3.3.3 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo.bar.baz
importing config

Peter

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


urllib2 and transfer-encoding = chunked

2007-01-18 Thread jdvolz
I am having errors which appear to be linked to a previous bug in
urllib2 (and urllib) for v2.4 and v2.5 of Python.  Has this been fixed?
 Has anyone established a standard workaround?  I keep finding old
posts about it, that basically give up and say "well it's a known bug."
 Any help would be greatly appreciated.

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


Re: predefined empty base class ??

2007-01-18 Thread robert
Gabriel Genellina wrote:
> At Wednesday 17/1/2007 15:34, Dennis Lee Bieber wrote:
> 
>> > is there an predefined empty base class
>> > which I can instanziate to have an
>> > container i can copy attributes in?
>>
>> I think that's a two-liner...
>>
>> >>> class EmptyBase(object):
>> ... pass
> 
> Do you want a one liner?
> 
> class EmptyBase(object): pass
> 
> :)

Isn't "predefined" a zero liner :-;
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making a simple script standalone

2007-01-18 Thread robert
Gabriel Genellina wrote:
> At Wednesday 17/1/2007 16:05, Rikishi 42 wrote:
> 
>> >>What I want to do is to compile/bundle/prepare/whatever_term a simple
>> >>Python script for deployment on a Windows machine. Installing Python
>> >>itself on that machine, is not an option. Ideally I would like to 
>> obtain
>> >>a single executable file, but a script+runtime is acceptable.
>> >
>> > distutils + py2exe
>>
>> Tried that, just after asking here.
>> A bit messy (poor docs) and a very bloated result.
> 
> Consider that, at a bare minimum, you need to include python25.dll wich 
> is rather large, and transitive module imports can lead to a large 
> library.zip too.
> Different "bundlers" may be more or less convenient, have more or less 
> documentation, easier or harder to use, but they all make comparable 
> file sizes; no one is so dumb to include all the scripts reachable along 
> the PYTHONPATH, and on the other hand, if it included too few files your 
> script might fail when it can't import a needed module.
> See http://mail.python.org/pipermail/python-list/2005-August/336851.html 
> for a related issue.
> If you're going to try different alternatives, posting your findings at 
> the end would be a good thing.
> 

stay with py23 for "a script" (and more) and make <700kB 
independent distros - UPX and 7zip involved:

http://groups.google.com/group/comp.lang.python/msg/edf469a1b3dc3802
-- 
http://mail.python.org/mailman/listinfo/python-list


One more regular expressions question

2007-01-18 Thread Victor Polukcht
I have a couple of strings like:

Unassigned Number (1)32
No Route To Destination (3)  12
Normal call clearing (16)   2654
User busy (17) 630
No user respond (18)5
User alerting no answer (19) 16
Call rejected (21) 3
Destination out of order (27) 1
Invalid number format (28)32
Normal unspecified (31)   32
No channel available (34) 2
Temporary failure (41)  11
Switching equipment congestion (42)4
Resource unavailable unspecified (47)   2
Bearer capability not authorized (57) 73
Incomp. dest. / Non-existent CUG (88)  1
Recovery on timer expiry (102)  2
Interworking, unspecified (127)  5

I need to get:
Error code (value in brackets) - Value - Message.

My actual problem is i can't get how to include space, comma, slash.

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


Re: Class data members in C

2007-01-18 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Hendrik van Rooyen" <[EMAIL PROTECTED]> writes:
|> 
|> > Oh, one of the first two - I am not bonkers!  Changing a class after
|> > instance creation is guaranteed to cause confusion, if nothing else.
|> > 
|> *grin* - its also just about impossible to do, if you try to imagine
|> what you would have to do to all instances when you effectively
|> change the __init__ method.  And some people expect it to happen
|> automagically...

Oh, it's quite easy to do, with several different semantics.  I have even
used a couple of them.  All are seriously counter-intuitive :-)

I have never used one that successfully reran initialisation, though
I have seen people attempt it!  And tried it myself 

|> Sorry I can't be of more help. All of the docs I have read essentially
|> talk about changing instances.  From a practical point of view I would 
|> say: "Just redefine it".  But that is not very helpful. Specially if you are
|> mucking about in C, as your title suggests...

Thanks.  As someone else posted, the answer is PyDict_SetItemString
immediately after PyType_Ready.


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


Re: Would a Dutch speaker please check this wiki page please?

2007-01-18 Thread Martin P. Hellwig
Stef Mientki wrote:
> [EMAIL PROTECTED] wrote:
>> Got a note about a new page on the Python Wiki:
>>
>>> "Wade" == Wade McDaniel <[EMAIL PROTECTED]> writes:
>>
>> http://wiki.python.org/moin/Selcuk_Altun
>>
>> I suspect it's junk since it doesn't seem to mention Python and the 
>> website
>> it mentions doesn't seem to exist.  Still, just in case...
> The only (incorrect) Dutch sentence on the whole site is:
>   "Welkom op me site www.keriwar.nl",
> which should have been
>   "Welkom op mijn site www.keriwar.nl"
> but that could be explained, while his name "Selcuk Altun" is not 
> orginated from the Netherlands.
> I just expect that he is trying to setup a wiki,
> but that's too soon to give it a judgement.
> 
> cheers,
> Stef Mientki
>>
>> Thx,
>>
>> Skip

Could be Afrikaans too, but the page is gone now so I can't check.

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


DOTALL not working as expected

2007-01-18 Thread Stefan Palme

Hi all,

using the "re" module of Python (2.3 and 2.4), I tried the following:

  import re
  print re.sub('X.*?Y', 'Z', 'Xab\ncdY', re.DOTALL)

I wanted to replace
   Xab
   cdY
by a single "Z", but the "." in the pattern does not match the 
included "\n".

When using the pattern "X(.|\n)*?Y" (explicity including "\n"
in the set of "any character") I get the wanted result.

My fault or a bug in the module?

Thanks
-stefan-

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


Re: *POLL* How many sheeple believe in the 911 fairy tale and willing to accept an Orwellian doublespeak and enslavement world ?

2007-01-18 Thread schoenfeld . one

[EMAIL PROTECTED] wrote:
[...]

Ask yourself, how can all these people, supposed physicists, engineers,
software developers, people of supposed intelligence be incapable of
understanding that fire cannot make buildings free fall? How can they
not understand that a free falling WTC 7 means it was a demolished WTC
7? How is this possible?

The reality is that it is possible. That's why the money changers do
what they do, and do it without fear of reprisal.

Perhaps it is the fate of those who's forefathers conquered a nation to
one day wake up homeless in that nation - herded, branded, traded and
sold for the slaughter by the Zionist as they did the Negro. Perhaps
these Zionists, or whoever it is who is responsible for these acts, is
ultimately destined to the same fate.

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


Re: DOTALL not working as expected

2007-01-18 Thread Stefan Palme

Just noticed, that it works when *compiling* the pattern:

  import re
  p = re.compile('X.*?Y', re.DOTALL)
  print re.sub(p, 'Z', 'Xab\ncdY')

Still the question - my fault or a bug?

Best regards
-stefan-


On Thu, 18 Jan 2007 11:10:08 +0100, Stefan Palme wrote:
> 
> Hi all,
> 
> using the "re" module of Python (2.3 and 2.4), I tried the following:
> 
>   import re
>   print re.sub('X.*?Y', 'Z', 'Xab\ncdY', re.DOTALL)
> 
> I wanted to replace
>Xab
>cdY
> by a single "Z", but the "." in the pattern does not match the 
> included "\n".
> 
> When using the pattern "X(.|\n)*?Y" (explicity including "\n"
> in the set of "any character") I get the wanted result.
> 
> My fault or a bug in the module?
> 
> Thanks
> -stefan-

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


Re: One more regular expressions question

2007-01-18 Thread Roberto Bonvallet
Victor Polukcht wrote:
> My actual problem is i can't get how to include space, comma, slash.

Post here what you have written already, so we can tell you what the
problem is.

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


PyODBC Stored proc calling

2007-01-18 Thread king kikapu
Hi to all,

can anyone give me a jump-start about how to call Stored Procedures
from PyODBC ??
I want to execute a very simple testing Stored Procedure on an Sql
Server database.

I started using PyODBC and code like the following

cnxn = pyodbc.connect('DRIVER={SQL
Server};SERVER=hercules;DATABASE=pubs;UID=sa;PWD=pwd'')

for row in cnxn.execute("select au_fname from authors"):
print row.au_fname
cnxn.close()

and based on this, i can now write more complex ad-hoc sql string to
get/update data.
But how i can actually call Stored Procedures and passing parameters to
them ??

Let's say i have the following SP:

create procedure test_bed(@data varchar(100))
as
// do something here.


Any help ??

Thanks in advance

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


Re: Distributed computation of jobs

2007-01-18 Thread Paul Boddie
robert wrote:
>
> as many libs are restriced to certain OS'es, and/or need/rely on
> extension modules, few tags would probably improve: OS'es,
> pure-python, dependeniess

I've added some platform notes, although the library dependencies of
various MPI and PVM solutions are sort of obvious, but I'll get round
to adding those at some point unless you beat me to it. ;-)

Paul

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


Re: DOTALL not working as expected

2007-01-18 Thread Roberto Bonvallet
Stefan Palme wrote:
>> using the "re" module of Python (2.3 and 2.4), I tried the following:
>> 
>>   import re
>>   print re.sub('X.*?Y', 'Z', 'Xab\ncdY', re.DOTALL)
>> 
> Just noticed, that it works when *compiling* the pattern:
> 
>  import re
>  p = re.compile('X.*?Y', re.DOTALL)
>  print re.sub(p, 'Z', 'Xab\ncdY')
> 
> Still the question - my fault or a bug?

Your fault.  According to the documentation [1], the re.sub function takes
a count as a fourth argument, not the compilation flags.

[1] http://docs.python.org/lib/node46.html

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


Re: One more regular expressions question

2007-01-18 Thread Peter Otten
Victor Polukcht wrote:

> I have a couple of strings like:
> 
> Unassigned Number (1)32
> No Route To Destination (3)  12
> Normal call clearing (16)   2654
> User busy (17) 630
> No user respond (18)5
> User alerting no answer (19) 16
> Call rejected (21) 3
> Destination out of order (27) 1
> Invalid number format (28)32
> Normal unspecified (31)   32
> No channel available (34) 2
> Temporary failure (41)  11
> Switching equipment congestion (42)4
> Resource unavailable unspecified (47)   2
> Bearer capability not authorized (57) 73
> Incomp. dest. / Non-existent CUG (88)  1
> Recovery on timer expiry (102)  2
> Interworking, unspecified (127)  5
> 
> I need to get:
> Error code (value in brackets) - Value - Message.
> 
> My actual problem is i can't get how to include space, comma, slash.

The following solution is 100% regex-free :-)

>>> print lines
Unassigned Number (1)32
No Route To Destination (3)  12
Normal call clearing (16)   2654
User busy (17) 630
No user respond (18)5
User alerting no answer (19) 16
Call rejected (21) 3
Destination out of order (27) 1
Invalid number format (28)32
Normal unspecified (31)   32
No channel available (34) 2
Temporary failure (41)  11
Switching equipment congestion (42)4
Resource unavailable unspecified (47)   2
Bearer capability not authorized (57) 73
Incomp. dest. / Non-existent CUG (88)  1
Recovery on timer expiry (102)  2
Interworking, unspecified (127)  5

>>> [int(line.rsplit("(", 1)[1].split(")", 1)[0]) for line in
lines.splitlines()]
[1, 3, 16, 17, 18, 19, 21, 27, 28, 31, 34, 41, 42, 47, 57, 88, 102, 127]

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


Re: A note on heapq module

2007-01-18 Thread bearophileHUGS
Steven Bethard:
> Antoon Pardon:
> > For me, your class has the same drawback as the heappush, heappop
> > procedurers: no way to specify a comparision function.
>
> Agreed.  I'd love to see something like ``Heap(key=my_key_func)``.

It can be done, but the code becomes more complex and hairy:
http://rafb.net/p/iCCmDz16.html

(If someone spots a problem please tell me, thank you.)

Bye,
bearophile

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


Re: One more regular expressions question

2007-01-18 Thread Victor Polukcht
My pattern now is:

(?P[^(]+)(?P\d+)\)\s+(?P\d+)

And i expect to get:

var1 = "Unassigned Number "
var2 = "1"
var3 = "32"

I'm sure my regexp is incorrect, but can't understand where exactly.

Regex.debug shows that even the first block is incorrect.

Thanks in advance.

On Jan 18, 1:15 pm, Roberto Bonvallet <[EMAIL PROTECTED]>
wrote:
> Victor Polukcht wrote:
> > My actual problem is i can't get how to include space, comma, slash.Post 
> > here what you have written already, so we can tell you what the
> problem is.
> 
> --
> Roberto Bonvallet

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


Re: DOTALL not working as expected

2007-01-18 Thread Stefan Palme

arghh.
Thanks for removing my blindness :)
-stefan-

On Thu, 18 Jan 2007 10:38:35 +, Roberto Bonvallet wrote:
> Stefan Palme wrote:
>>> using the "re" module of Python (2.3 and 2.4), I tried the following:
>>> 
>>>   import re
>>>   print re.sub('X.*?Y', 'Z', 'Xab\ncdY', re.DOTALL)
>>> 
>> Just noticed, that it works when *compiling* the pattern:
>> 
>>  import re
>>  p = re.compile('X.*?Y', re.DOTALL)
>>  print re.sub(p, 'Z', 'Xab\ncdY')
>> 
>> Still the question - my fault or a bug?
> 
> Your fault.  According to the documentation [1], the re.sub function takes
> a count as a fourth argument, not the compilation flags.
> 
> [1] http://docs.python.org/lib/node46.html
> 
> Cheers,

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


Re: A note on heapq module

2007-01-18 Thread bearophileHUGS
Neil Cerutti:
> One more idea, cribbed from the linked list thread elsewhere: it
> might be nice if your Heap could optionally use an underlying
> collections.deque instead of a list.
> I don't know how excellent Python's deque is, but it's possible a
> deque would provide a faster heap than a contiguous array. C++'s
> std::deque is the default implementation of C++'s
> std::priority_queue for that reason (unless I'm confused again).

If you have some minutes you can do few speed tests and show us the
code and the timing results...

Bye,
bearophile

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


Re: arguments of a function/metaclass

2007-01-18 Thread rubbishemail

thank you!

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


Re: One more regular expressions question

2007-01-18 Thread Daniele Varrazzo
Victor Polukcht wrote:
> I have a couple of strings like:
>
> Unassigned Number (1)32
[...]
> Interworking, unspecified (127)  5
>
> I need to get:
> Error code (value in brackets) - Value - Message.
>
> My actual problem is i can't get how to include space, comma, slash.

Probably you have some escaping problem. The substitution:

  re.sub(r"^(.*)\s*\((\d+)\)\s+(\d+)", r'\2 - \3 - \1', row)

does the required job (where "row" is one of your lines)

To match a special character, such as "(", you need to escape it with a
"\", because it has a special meaning in the regexp syntax. Because "\"
is the escaping mechanism for Python strings too, you better use raw
strings to specify the pattern.

Other special character/groups matching patterns, such as "\s" to
specify whitespaces, are documented, together with everything else you
need, at http://docs.python.org/lib/re-syntax.html

HTH

Daniele

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


Re: One more regular expressions question

2007-01-18 Thread harvey . thomas
Victor Polukcht wrote:

> My pattern now is:
>
> (?P[^(]+)(?P\d+)\)\s+(?P\d+)
>
> And i expect to get:
>
> var1 = "Unassigned Number "
> var2 = "1"
> var3 = "32"
>
> I'm sure my regexp is incorrect, but can't understand where exactly.
>
> Regex.debug shows that even the first block is incorrect.
>
> Thanks in advance.
>
> On Jan 18, 1:15 pm, Roberto Bonvallet <[EMAIL PROTECTED]>
> wrote:
> > Victor Polukcht wrote:
> > > My actual problem is i can't get how to include space, comma, slash.Post 
> > > here what you have written already, so we can tell you what the
> > problem is.
> >
> > --
> > Roberto Bonvallet

You are missing \( after the first group. The RE should be:

'(?P[^(]+)\((?P\d+)\)\s+(?P\d+)'

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


classes: need for an explanation

2007-01-18 Thread 0k-
hello!

i started to write a game in python in which i want to implement
"dynamically attachable" attributes.
my intention is to generalise this and moreover these attributes can be
complex, so i'm creating classes to represent these attributes. but
somehow i cannot instantiate these attribute classes well...

here is the simple outline of my code:

class Attr(object):
name = ""
value = ""
def __init__(self, name, value):
self.name = name
self.value = value

# this is just an example, in the real game attrs. are more complex!
class TxtAttr(Attr):
name = "text"
def __init__(self, value):
self.value = value

class Thing(object):
props = {}
def __init__(self):
self.props["text"] = TxtAttr("something important")

t1 = Thing()
t2 = Thing()

t2.props["text"].value = "another string"

print "t1: %s\nt2: %s" % (t1.props["text"].value,
t2.props["text"].value)

the above code outputs:

t1: another string
t2: another string

so the problem i cannot get through is that both t1 and t2 have the
same attr class instance.
could somebody please explain me why? :)

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


Re: One more regular expressions question

2007-01-18 Thread Victor Polukcht
Great thanks.

You post helped me so much!

My resulting regexp is:
"(?P^(.*)\s*)\(((?P\d+))\)\s+((?P\d+))"

On Jan 18, 2:38 pm, "Daniele Varrazzo" <[EMAIL PROTECTED]>
wrote:
> Victor Polukcht wrote:
> > I have a couple of strings like:
>
> > Unassigned Number (1)32
> [...]
> > Interworking, unspecified (127)  5
>
> > I need to get:
> > Error code (value in brackets) - Value - Message.
>
> > My actual problem is i can't get how to include space, comma, 
> > slash.Probably you have some escaping problem. The substitution:
>
>   re.sub(r"^(.*)\s*\((\d+)\)\s+(\d+)", r'\2 - \3 - \1', row)
>
> does the required job (where "row" is one of your lines)
>
> To match a special character, such as "(", you need to escape it with a
> "\", because it has a special meaning in the regexp syntax. Because "\"
> is the escaping mechanism for Python strings too, you better use raw
> strings to specify the pattern.
>
> Other special character/groups matching patterns, such as "\s" to
> specify whitespaces, are documented, together with everything else you
> need, athttp://docs.python.org/lib/re-syntax.html
> 
> HTH
> 
> Daniele

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


Re: generate tuples from sequence

2007-01-18 Thread Duncan Booth
Peter Otten <[EMAIL PROTECTED]> wrote:
> But still, to help my lack of fantasy -- what would a sane zip()
> implementation look like that does not guarantee the above output?
> 
Hypothetically?

The code in zip which builds the result tuples looks (ignoring error 
handling) like:

// inside a loop building each result element...
PyObject *next = PyTuple_New(itemsize);

for (j = 0; j < itemsize; j++) {
PyObject *it = PyTuple_GET_ITEM(itlist, j);
PyObject *item = PyIter_Next(it);
PyTuple_SET_ITEM(next, j, item);
}

For fixed size tuples you can create them using PyTuple_Pack. So imagine 
some world where the following code works faster for small tuples:

   // Outside the loop building the result list:
   PyObject *a, *b, *c;
   if (itemsize >= 1 && itemsize <= 3) a = PyTuple_GET_ITEM(...);
   if (itemsize >= 2 && itemsize <= 3) b = PyTuple_GET_ITEM(...);
   if (itemsize == 3) c = PyTuple_GET_ITEM(...);
   ...

   // inside the result list loop:
   PyObject *next;
   if (itemsize==1) {
   next = PyTuple_Pack(1,
PyIter_Next(a));
   } else if (itemsize==2) {
   next = PyTuple_Pack(2,
PyIter_Next(a),
PyIter_Next(b));
   } else if (itemsize==2) {
   next = PyTuple_Pack(3,
PyIter_Next(a),
PyIter_Next(b),
PyIter_Next(c));
   } else {
   next = PyTuple_New(itemsize);

   for (j = 0; j < itemsize; j++) {
   PyObject *it = PyTuple_GET_ITEM(itlist, j);
   PyObject *item = PyIter_Next(it);
   PyTuple_SET_ITEM(next, j, item);
   }
   }

If compiled on a system where the stack grows downwards (as it often does) 
the C compiler is very likely to evaluate function arguments in reverse 
order.

(BTW, this also assumes that it's an implementation which uses exceptions 
or something for error handling otherwise you probably can't get it right, 
but maybe something like IronPython could end up with code like this.)

Or maybe if someone added PyTuple_Pack1, PyTuple_Pack2, PyTuple_Pack3 
functions which grab their memory off a separate free list for each tuple 
length. That might speed up the time to create the tuples as you might be 
able to just reset the content not rebuild the object each time. Again that 
could make code like the above run more quickly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: One more regular expressions question

2007-01-18 Thread Jussi Salmela
Victor Polukcht kirjoitti:
> Great thanks.
> 
> You post helped me so much!
> 
> My resulting regexp is:
> "(?P^(.*)\s*)\(((?P\d+))\)\s+((?P\d+))"
> 

If it doesn't have to be a regex:

#===
s = '''\
Unassigned Number (1)32
No Route To Destination (3)  12
Normal call clearing (16)   2654
User busy (17) 630
No user respond (18)5
User alerting no answer (19) 16
Call rejected (21) 3
Destination out of order (27) 1
Invalid number format (28)32
Normal unspecified (31)   32
No channel available (34) 2
Temporary failure (41)  11
Switching equipment congestion (42)4
Resource unavailable unspecified (47)   2
Bearer capability not authorized (57) 73
Incomp. dest. / Non-existent CUG (88)  1
Recovery on timer expiry (102)  2
Interworking, unspecified (127)  5
'''

for row in s.split('\n')[:-1]:
 var1, var2 = row.split('(')
 var2, var3 = var2.split()
 var2 = var2[:-1]
 print var2, var3, var1
#===

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


Re: classes: need for an explanation

2007-01-18 Thread 0k-
oops, i forgot to mention i'm using interpreter version 2.4.3

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


Re: classes: need for an explanation

2007-01-18 Thread Peter Otten
0k- wrote:

> class Thing(object):
> props = {}
> def __init__(self):
> self.props["text"] = TxtAttr("something important")
> 
> t1 = Thing()
> t2 = Thing()
> 
> t2.props["text"].value = "another string"
> 
> print "t1: %s\nt2: %s" % (t1.props["text"].value,
> t2.props["text"].value)
> 
> the above code outputs:
> 
> t1: another string
> t2: another string
> 
> so the problem i cannot get through is that both t1 and t2 have the
> same attr class instance.
> could somebody please explain me why? :)

Putting an assignment into the class body makes the name a /class/ attribute
which is shared by all instances of the class:

>>> class Thing:
... props = {} # this is a class attribute
...
>>> t1, t2 = Thing(), Thing()
>>> t1.props is t2.props
True

The solution is to move the attribute creation into the initializer:

>>> class Thing:
... def __init__(self):
... self.props = {} # an instance attribute
...
>>> t1, t2 = Thing(), Thing()
>>> t1.props is t2.props
False

Peter

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


Re: classes: need for an explanation

2007-01-18 Thread 0k-
thanks for the quick reply, Peter! :)

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


closing a "forever" Server Socket

2007-01-18 Thread alessandro
Hi all,

This is my framework for create TCP server listening forever on a port
and supporting threads:


import SocketServer

port = 
ip = "192.168.0.4"
server_address = (ip, port)

class ThreadingTCPServer(SocketServer.ThreadingMixIn,
SocketServer.TCPServer): pass

class Handler(SocketServer.BaseRequestHandler):
def handle(self):
# my handler

print "Listening for events at " + ip + ":" + str(port)
monitor_server = ThreadingTCPServer(server_address, Handler)

try:
monitor_server.serve_forever()
except KeyboardInterrupt:
monitor_server.socket.close()
print "Bye."


This server will not run as a daemon and for quitting you have to send
the SIGINT signal with Ctrl-C. It will rise the KeyboardInterrupt
exception, during its handling I simply close the socket and print a
message.

I want to ask if someone knows a better way for closing a "forever
server" or if there is a lack in my design.

Thank you!

Alessandro

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


Shed Skin Python-to-C++ Compiler

2007-01-18 Thread Mark Dufour
hi all,

I have just released Shed Skin 0.0.18. besides many fixes and
optimizations, this release should work on OSX and 64-bit systems
(thanks john, larry, gustavo and denis!)

more interestingly, I collected 25 'largish' programs (at a total of
more than 6,000 lines!) that work fine with Shed Skin. these can be
downloaded from the Shed Skin homepage:

http://mark.dufour.googlepages.com

please let me know if you try out the latest release, and encounter
any problems or have any wishes.


thanks,
mark.
-- 
"One of my most productive days was throwing away 1000 lines of code"
- Ken Thompson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: classes: need for an explanation

2007-01-18 Thread Steven D'Aprano
On Thu, 18 Jan 2007 03:58:22 -0800, 0k- wrote:

> hello!
> 
> i started to write a game in python in which i want to implement
> "dynamically attachable" attributes.

All attributes in Python are dynamically attachable.

>>> class Parrot:
... pass
...
>>> p = Parrot()
>>> hasattr(p, "plumage")
False
>>> p.plumage = "beautiful red"
>>> p.plumage
'beautiful red'


[snip]

> class Thing(object):
> props = {}
> def __init__(self):
> self.props["text"] = TxtAttr("something important")
> 
> t1 = Thing()
> t2 = Thing()
> 
> t2.props["text"].value = "another string"


Have you considered a simpler class like this?

class Thing(object):
def __init__(self, value="something important"):
self.text = TxtAttr(value)

t2 = Thing("another string")

Then, instead of writing t2.props["text"].value (four lookups) you would
just write t2.text (two lookups).



-- 
Steve.

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


Re: generate tuples from sequence

2007-01-18 Thread Peter Otten
Duncan Booth wrote:

> Peter Otten <[EMAIL PROTECTED]> wrote:
>> But still, to help my lack of fantasy -- what would a sane zip()
>> implementation look like that does not guarantee the above output?
>> 
> Hypothetically?
> 
> The code in zip which builds the result tuples looks (ignoring error
> handling) like:
> 
> // inside a loop building each result element...
> PyObject *next = PyTuple_New(itemsize);
> 
> for (j = 0; j < itemsize; j++) {
> PyObject *it = PyTuple_GET_ITEM(itlist, j);
> PyObject *item = PyIter_Next(it);
> PyTuple_SET_ITEM(next, j, item);
> }
> 
> For fixed size tuples you can create them using PyTuple_Pack. So imagine
> some world where the following code works faster for small tuples:
> 
>// Outside the loop building the result list:
>PyObject *a, *b, *c;
>if (itemsize >= 1 && itemsize <= 3) a = PyTuple_GET_ITEM(...);
>if (itemsize >= 2 && itemsize <= 3) b = PyTuple_GET_ITEM(...);
>if (itemsize == 3) c = PyTuple_GET_ITEM(...);
>...
> 
>// inside the result list loop:
>PyObject *next;
>if (itemsize==1) {
>next = PyTuple_Pack(1,
> PyIter_Next(a));
>} else if (itemsize==2) {
>next = PyTuple_Pack(2,
> PyIter_Next(a),
> PyIter_Next(b));
>} else if (itemsize==2) {
>next = PyTuple_Pack(3,
> PyIter_Next(a),
> PyIter_Next(b),
> PyIter_Next(c));
>} else {
>next = PyTuple_New(itemsize);
> 
>for (j = 0; j < itemsize; j++) {
>PyObject *it = PyTuple_GET_ITEM(itlist, j);
>PyObject *item = PyIter_Next(it);
>PyTuple_SET_ITEM(next, j, item);
>}
>}
> 
> If compiled on a system where the stack grows downwards (as it often does)
> the C compiler is very likely to evaluate function arguments in reverse
> order.
> 
> (BTW, this also assumes that it's an implementation which uses exceptions
> or something for error handling otherwise you probably can't get it right,
> but maybe something like IronPython could end up with code like this.)
> 
> Or maybe if someone added PyTuple_Pack1, PyTuple_Pack2, PyTuple_Pack3
> functions which grab their memory off a separate free list for each tuple
> length. That might speed up the time to create the tuples as you might be
> able to just reset the content not rebuild the object each time. Again
> that could make code like the above run more quickly.

Special-casing small tuples meets my sanity criterion :-)

Let's see if I understand the above: In C a call

f(g(), g())

may result in machine code equivalent to either

x = g()
y = g()
f(x, y)

or

y = g()
x = g()
f(x, y)

Is that it?

Peter

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


Is it possible to fasten the import of cgi?

2007-01-18 Thread Cecil Westerhof
I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I
can not time the time used to import time, but os and sys do not take more
as a millisecond. My script itself takes 3 or 4 milliseconds. But importing
cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
there a way to make this more fast? The import off cgi makes the script at
least 20 times as slow. Something like mod-python is not a possibility. I
could use it on my test machine, but not at the osting provider.

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


Re: How can I create a linked list in Python?

2007-01-18 Thread Jorgen Grahn
On Wed, 17 Jan 2007 10:11:40 +0100, Marc 'BlackJack' Rintsch <[EMAIL 
PROTECTED]> wrote:
> In <[EMAIL PROTECTED]>, bearophileHUGS
> wrote:
>
>> In CPython they are dynamic arrays, they aren't lists. Try adding
>> elements at the beginning of a list compared to adding elements at the
>> beginning or in the middle of a python "list" and you will see the
>> efficiency differences.
>
> Python has a list type without the "s, it's a real list.  Don't confuse
> the *ADT list* with *linked lists* which are just one implementation of
> the ADT list.

I think the terminology is already so confused that you cannot say "list"
unless context implies that you mean e.g. a Python list. For example, SML (a
language favored by people interested in types and type systems) uses the
term "list", but a SML "list" really acts like a stack.

FWIW, I oppose the idea (paraphrased from further up the thread) that linked
lists and other data structures are obsolete and dying concepts, obsoleted
by Python and other modern languages.

99% of the time. a Python list is the right tool for the job, but that's
only because we have CPU cycles to spare and the 'n' in our 'O(n)' is
limited. You cannot call yourself a computer scientist without understanding
things like linked lists.  No other data structure has the same
characteristics (good and bad) as that one. Or those two, really.

I mean, what would Knuth say? ;-)

/Jorgen

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


Re: One more regular expressions question

2007-01-18 Thread Daniele Varrazzo
Victor Polukcht wrote:
> Great thanks.
>
> You post helped me so much!
>
> My resulting regexp is:
> "(?P^(.*)\s*)\(((?P\d+))\)\s+((?P\d+))"

Notice that this way you are including trailing whitespaces in the var1
group. You may want to put the "\s*" outside the parenthesis.

mmm... in this case you should make the ".*" in the first group
non-greedy. r"^(?P.*?)\s*\(((?P\d+))\)\s+((?P\d+))"
does the job.

Bye

Daniele

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


Re: Is it possible to fasten the import of cgi?

2007-01-18 Thread Daniele Varrazzo
Cecil Westerhof wrote:
> I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I
> can not time the time used to import time, but os and sys do not take more
> as a millisecond. My script itself takes 3 or 4 milliseconds. But importing
> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
> there a way to make this more fast? The import off cgi makes the script at
> least 20 times as slow. Something like mod-python is not a possibility. I
> could use it on my test machine, but not at the osting provider.

Does the hosting provider support fastcgi? It would avoid starting the
interpreter at each request too.

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


Re: Is it possible to fasten the import of cgi?

2007-01-18 Thread Cecil Westerhof
Daniele Varrazzo wrote:

> Cecil Westerhof wrote:
>> I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse
>> I can not time the time used to import time, but os and sys do not take
>> more as a millisecond. My script itself takes 3 or 4 milliseconds. But
>> importing cgi takes 95 milliseconds. (This is on my test system a PII 300
>> MHz. Is there a way to make this more fast? The import off cgi makes the
>> script at least 20 times as slow. Something like mod-python is not a
>> possibility. I could use it on my test machine, but not at the osting
>> provider.
> 
> Does the hosting provider support fastcgi? It would avoid starting the
> interpreter at each request too.

I am afraid not. It is very bare bone. Also they do not really support
python. (When they had a problem, perl and bash scripts worked within a
day, python scripts had to wait for one and a halve week.)

I am thinking about switching my provider. What are important things to keep
in mind when selecting another one?

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


python embedding and threads

2007-01-18 Thread Sven Rech
Hi,

I'm the author of an application written in C, which should now be 
extended with a python plugin system.
It already works very good, but I now have a problem:
Threading functionality within the python modules, that my C app loads 
and calls, doesn't work. This means, the threads do not run (the same 
python code works correct if I just start it with the normal python 
interpreter).


Is there something I must be aware of, if I want to use (python) threads 
with embedded python? (for example call a special function or something 
like that)

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


what can be used in a signal handler

2007-01-18 Thread hg
Hi,

I posted an equivalent question earlier ... but am still not sure:

I currently (under Linux) have a program that uses Queue.put (raw_input(''))
in a signal handler and Queue.get() in the main/only thread.

It works but I want to know if it is legal / what type of synchro API I have
the right to use in a signal handler.

Regards,

hg

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


Re: generate tuples from sequence

2007-01-18 Thread Duncan Booth
Peter Otten <[EMAIL PROTECTED]> wrote:

> Let's see if I understand the above: In C a call
> 
> f(g(), g())
> 
> may result in machine code equivalent to either
> 
> x = g()
> y = g()
> f(x, y)
> 
> or
> 
> y = g()
> x = g()
> f(x, y)
> 
> Is that it?
> 

Yes, or changing one of the calls to h() and compiling with 
"cl -Fat.asm -Ox -c t.c":

-- t.c 
extern int f(int a, int b);
extern int g();
extern int h();

int main(int argc, char **argv) {
return f(g(), h());
}
---

The output file:
--- t.asm -
; Listing generated by Microsoft (R) Optimizing Compiler Version 13.10.3077 

TITLE   t.c
.386P
include listing.inc
if @Version gt 510
.model FLAT
else
_TEXT   SEGMENT PARA USE32 PUBLIC 'CODE'
_TEXT   ENDS
_DATA   SEGMENT DWORD USE32 PUBLIC 'DATA'
_DATA   ENDS
CONST   SEGMENT DWORD USE32 PUBLIC 'CONST'
CONST   ENDS
_BSSSEGMENT DWORD USE32 PUBLIC 'BSS'
_BSSENDS
$$SYMBOLS   SEGMENT BYTE USE32 'DEBSYM'
$$SYMBOLS   ENDS
_TLSSEGMENT DWORD USE32 PUBLIC 'TLS'
_TLSENDS
FLATGROUP _DATA, CONST, _BSS
ASSUME  CS: FLAT, DS: FLAT, SS: FLAT
endif

INCLUDELIB LIBC
INCLUDELIB OLDNAMES

PUBLIC  _main
EXTRN   _f:NEAR
EXTRN   _g:NEAR
EXTRN   _h:NEAR
; Function compile flags: /Ogty
_TEXT   SEGMENT
_argc$ = 8  ; size = 4
_argv$ = 12 ; size = 4
_main   PROC NEAR
; File c:\temp\t.c
; Line 6
call_h
pusheax
call_g
pusheax
call_f
add esp, 8
; Line 7
ret 0
_main   ENDP
_TEXT   ENDS
END
-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what can be used in a signal handler

2007-01-18 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
hg <[EMAIL PROTECTED]> writes:
|> 
|> I posted an equivalent question earlier ... but am still not sure:
|> 
|> I currently (under Linux) have a program that uses Queue.put (raw_input(''))
|> in a signal handler and Queue.get() in the main/only thread.
|> 
|> It works but I want to know if it is legal / what type of synchro API I have
|> the right to use in a signal handler.

Strictly, no and none.

C and POSIX's specifications of signal handling is a complete mess.
ALL handling of ALL real signals is undefined behaviour, though few
programmers realise that and POSIX depends on it.  As that would make
all Unices (and Microsoft systems) unusable, you can reasonably assume
that there is some signal handling that will work.

But what?  Which is where you came in.

The situation is that most things that seem to work do actually work,
in some environments and under some circumstances.  You can never be
sure when they will stop working, however, and all bets are off when
you port signal handling code to a new system.  And, really but REALLY,
do not mix it with very high levels of optimisation or rely on it
being in any way thread safe.

I can't tell you whether the code of Queue is intended to work if an
active Queue.get is interrupted by a signal which then does a Queue.put,
but that is the sort of circumstance where things get very hairy.  Even
if Python has code to enable that case, it won't be 100% reliable on all
systems.

Sorry.  But that is the situation :-(


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


Catching wx events

2007-01-18 Thread Cruelemort
Hello all,

I am new to this group (and new to Python) and was hoping someone would
be able to help me with something, it is not so much a problem it is
more of a general interest query about something i have a solution too
but am not sure it is the correct one.

I have a class that contains a string ID and a name, and a list
containing a few objects of this type, i need to loop through this list
and create a button for each object (with the name as the label) i have
done this with the following code -

for chan in self._channellist:
channelbutton = wx.Button(self, id=-1,
label=chan.getName())

channelbutton.Bind(wx.EVT_BUTTON,self._channelChanged)

My question is this - in the _channelChanged method, how do i know
which button has been pressed when i enter the channel changed method,
and so how do i retrieve the appropriate object depending on which
button has been pressed?

I have potentially solved this problem using the UserData property in a
sizer, i have added all the buttons to a sizer for display purposes and
so SizerItem objects have been created, i can then set the original
object to the UserData object by putting the following line of code in
the loop

sizeritem =
self.topsizer.Add(channelbutton,0,wx.ALIGN_RIGHT, userData=chan)

This way i can retrieve the item in the _channelChanged method with the
following -

def _channelChanged(self, event):
eventobj = event.GetEventObject()
chan = self.topsizer.GetItem(eventobj).GetUserData()


This works fine but by looking at the API it would appear the UserData
property is not really designed for this use ("userData - Allows an
extra object to be attached to the sizer item, for use in derived
classes when sizing information is more complex than the proportion and
flag will allow for").

Another option would be to derive my own Button class and include the
object in there.

Any advice on the best way to solve this problem would be appreciated.

Many thanks

Ian

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


Re: A note on heapq module

2007-01-18 Thread Neil Cerutti
On 2007-01-18, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Neil Cerutti:
>> One more idea, cribbed from the linked list thread elsewhere:
>> it might be nice if your Heap could optionally use an
>> underlying collections.deque instead of a list. I don't know
>> how excellent Python's deque is, but it's possible a deque
>> would provide a faster heap than a contiguous array. C++'s
>> std::deque is the default implementation of C++'s
>> std::priority_queue for that reason (unless I'm confused
>> again).
>
> If you have some minutes you can do few speed tests and show us
> the code and the timing results...

I'll see what I can come up with. I'll have to test using the
native Python implementation, which should work with deque,
rather than the optimized C implementation, which doesn't. 

Unfortunately the inability to take advantage of the C
implementation of heapq might swamp any possible advantage of
using deque instead of list in a Heap class.

-- 
Neil Cerutti

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: Would a Dutch speaker please check this wiki page please?

2007-01-18 Thread skip

Martin> Could be Afrikaans too, but the page is gone now so I can't
Martin> check.

Actually, you can... ;-) Even though it's a nonexistent page, its history
still exists.  Poke the "Get Info" link and view the first revision of the
file.

Skip

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


Re: Is it possible to fasten the import of cgi?

2007-01-18 Thread Gabriel Genellina
"Cecil Westerhof" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I
> can not time the time used to import time, but os and sys do not take more
> as a millisecond. My script itself takes 3 or 4 milliseconds. But 
> importing
> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
> there a way to make this more fast? The import off cgi makes the script at
> least 20 times as slow. Something like mod-python is not a possibility. I
> could use it on my test machine, but not at the osting provider.
Surely os was imported earlier, and was already loaded. sys is a builtin 
module. But I think your problem is not how much time takes importing cgi, 
but how much time takes launching a new python process on each request.

-- 
Gabriel Genellina 


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


Re: One more regular expressions question

2007-01-18 Thread Neil Cerutti
On 2007-01-18, Victor Polukcht <[EMAIL PROTECTED]> wrote:
> My pattern now is:
>
> (?P[^(]+)(?P\d+)\)\s+(?P\d+)
>
> And i expect to get:
>
> var1 = "Unassigned Number "
> var2 = "1"
> var3 = "32"
>
> I'm sure my regexp is incorrect, but can't understand where
> exactly.

Break it up using verbose notation to help yourself. Also, use
more helpful names. With names like var1 and var2 you might as
well not used named groups.

r = re.compile(r"""(?x)
(?P [^(]+ )
(?P \d+ )
\)
\s+
(?P \d+ )""")

This way it's clearer that there's a \) with no matching \(.

-- 
Neil Cerutti
This team is one execution away from being a very good basketball team. --Doc
Rivers

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: urllib2 and transfer-encoding = chunked

2007-01-18 Thread Gabriel Genellina
<[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]
>I am having errors which appear to be linked to a previous bug in
> urllib2 (and urllib) for v2.4 and v2.5 of Python.  Has this been fixed?
> Has anyone established a standard workaround?  I keep finding old
> posts about it, that basically give up and say "well it's a known bug."
> Any help would be greatly appreciated.

Perhaps if you said what the supposed error is...

-- 
Gabriel Genellina 


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


PythonTidy 1.10

2007-01-18 Thread Chuck Rhode
PythonTidy cleans up, regularizes, and reformats the text of Python
scripts.

It is released under the GNU General Public License.  

Python scripts are usually so good looking that no beautification is
required.  However, from time to time, it may be necessary to alter
the style to conform to changing standards.  This script converts
programs in a consistent way.  It abstracts the pretty presentation of
the symbolic code from the humdrum process of writing it and getting
it to work.

This is an upgrade.  There was a big problem with earlier versions:
Canonical values were substituted for strings and numbers.  For
example, decimal integers were substituted for hexadecimal, and
escaped strings for raw strings.  Authors of Python scripts usually
use peculiar notations for peculiar purposes, and doing away with the
peculiarity negatively impacts the readability of the code.

This version preserves the original constants (parsed by *tokenize*)
in a literal pool indexed by the value they evaluate to.  The
canonical values (output by *compiler*) are then translated back (when
possible) to the original constants by looking them up in the literal
pool.

-- 
http://www.lacusveris.com/PythonTidy/PythonTidy-1.10.python";>PythonTidy
1.10 - Cleans up, regularizes, and reformats the text of Python
scripts. (18-Jan-07)

.. Chuck Rhode, Sheboygan, WI, USA
.. mailto:[EMAIL PROTECTED]
.. Weather:  http://LacusVeris.com/WX
.. 20° — Wind WNW 13 mph

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

Re: import vs. subdirectory search

2007-01-18 Thread Gabriel Genellina
"John Nagle" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

>I'm running Python 2.3.4 from a CGI script on a shared hosting Linux 
> system.
> The CGI program is being executed from Apache, as "nobody".  I have some
> local modules installed in "~myname/lib/python"; these include
> "MySQLdb" and "M2Crypto".
>
>Since this is running as "nobody", I append
>
> /home/myname/lib/python
>
> to sys.path.
>
>Within the CGI programs,
>
> import MySQLdb # works fine
> import M2Crypto # works fine
> import SSL # "No module named SSL"
>
> The problem is that SSL is in a subdirectory of the M2Crypto directory,
> and that's not being searched.
And should *not* be searched, unless the importing module is itself in the 
M2Crypto directory.

> I can execute "import M2Crypto.SSL",
> but that doesn't have the same effect; it puts SSL in a different
> place in the namespace.  I'm trying to avoid that; it causes obscure
> aliasing problems.
You *could* do: from M2Crypto import SSL, but I think this is not your 
problem.

>On Python 2.4 under Windows 2000, importing from a subdirectory
> appears to work.  Is that a Python 2.3.4 thing, or a Linux thing,
> or something else?
No, it should not work as you describe it. Either you have another SSL 
module in another place, or sys.path includes the M2Crypto directory.
On your 2.4 Windows, try this:
import sys
import SSL
print SSL.__file__
print sys.path
and see what happens



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


Re: Asyncore select statement problem

2007-01-18 Thread Gabriel Genellina
"JamesHoward" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

>I have a problem with python's asyncore module throwing a bad file
> descriptor error.  The code might be difficult to copy here, but the
> problem is essentially:
>
> The server wants to sever the connection of an open Asyncore socket.
> Calling the socket.close() nor the socket.shutdown(2) calls seem to
> work.  The only way I can close the connection without creating the
> error below is to have the client close the connection.

You have to use the dispatcher's close() method, else, the asyncore map 
won't be updated, keeping a reference to the closed socket.

-- 
Gabriel Genellina 


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


Re: Catching wx events

2007-01-18 Thread Chris Mellon
On 18 Jan 2007 06:12:17 -0800, Cruelemort <[EMAIL PROTECTED]> wrote:
> Hello all,
>
> I am new to this group (and new to Python) and was hoping someone would
> be able to help me with something, it is not so much a problem it is
> more of a general interest query about something i have a solution too
> but am not sure it is the correct one.
>
> I have a class that contains a string ID and a name, and a list
> containing a few objects of this type, i need to loop through this list
> and create a button for each object (with the name as the label) i have
> done this with the following code -
>
> for chan in self._channellist:
> channelbutton = wx.Button(self, id=-1,
> label=chan.getName())
>
> channelbutton.Bind(wx.EVT_BUTTON,self._channelChanged)
>
> My question is this - in the _channelChanged method, how do i know
> which button has been pressed when i enter the channel changed method,
> and so how do i retrieve the appropriate object depending on which
> button has been pressed?
>
> I have potentially solved this problem using the UserData property in a
> sizer, i have added all the buttons to a sizer for display purposes and
> so SizerItem objects have been created, i can then set the original
> object to the UserData object by putting the following line of code in
> the loop
>
> sizeritem =
> self.topsizer.Add(channelbutton,0,wx.ALIGN_RIGHT, userData=chan)
>
> This way i can retrieve the item in the _channelChanged method with the
> following -
>
> def _channelChanged(self, event):
> eventobj = event.GetEventObject()
> chan = self.topsizer.GetItem(eventobj).GetUserData()
>
>
> This works fine but by looking at the API it would appear the UserData
> property is not really designed for this use ("userData - Allows an
> extra object to be attached to the sizer item, for use in derived
> classes when sizing information is more complex than the proportion and
> flag will allow for").
>
> Another option would be to derive my own Button class and include the
> object in there.
>
> Any advice on the best way to solve this problem would be appreciated.
>

Exactly how I would do it depends on the rest of the application. I
would probably derive my own button - never be afraid to subclass.

You could also generate the buttons IDs up front, and maintain a
mapping between the IDs and the channels, like so:

self.mapper = {}
for channel in self.channels:
id = wx.NewId()
self.mapper[id] = channel
channelbutton = wx.Button(self, id=id, label=channel.getName())


def channelChanged(self, event):
channel = self.mapper[event.Id]


You could also use closures (lambdas or via a factory function) to
bind the channel at the time you create the button:

for channel in self.channels:
channelbutton = wx.Button(self, label=channel.getName())
self.Bind(wx.EVT_BUTTON, lambda event:
self.channelChanged(channel), source=channelbutton)

def channelChanged(self, channel):
print "Channel changed to ", channel.getName()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would a Dutch speaker please check this wiki page please?

2007-01-18 Thread Martin P. Hellwig
Stef Mientki wrote:
> [EMAIL PROTECTED] wrote:
>> Got a note about a new page on the Python Wiki:
>>
>>> "Wade" == Wade McDaniel <[EMAIL PROTECTED]> writes:
>>
>> http://wiki.python.org/moin/Selcuk_Altun
>>
>> I suspect it's junk since it doesn't seem to mention Python and the 
>> website
>> it mentions doesn't seem to exist.  Still, just in case...
> The only (incorrect) Dutch sentence on the whole site is:
>   "Welkom op me site www.keriwar.nl",
> which should have been
>   "Welkom op mijn site www.keriwar.nl"
Well actually in the next sentence "De site is online als je vragen hebt 
lees eerst te F.A.Q." is incorrect too, "te F.A.Q." is grammatical and 
logical incorrect, should be "de F.A.Q.".
Indeed it's not Afrikaans but just incorrect use of Dutch and not 
related to python.

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


Re: Is it possible to fasten the import of cgi?

2007-01-18 Thread Cecil Westerhof
Gabriel Genellina wrote:

> "Cecil Westerhof" <[EMAIL PROTECTED]> escribió en el mensaje
> news:[EMAIL PROTECTED]
> 
>>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse
>>I
>> can not time the time used to import time, but os and sys do not take
>> more as a millisecond. My script itself takes 3 or 4 milliseconds. But
>> importing
>> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
>> there a way to make this more fast? The import off cgi makes the script
>> at least 20 times as slow. Something like mod-python is not a
>> possibility. I could use it on my test machine, but not at the osting
>> provider.
> Surely os was imported earlier, and was already loaded. sys is a builtin
> module. But I think your problem is not how much time takes importing cgi,
> but how much time takes launching a new python process on each request.

Nope, it was certainly cgi. When I fetch time after importing and after the
script finishes, the difference is 4 milliseconds. If I import the modules
apart from cgi after I fetch the first time, there is added about 1
millisecond to the difference. When I also import cgi after taking the
time, the difference grows with 95 milliseconds. So for one reason ore
another, cgi is very expensive.

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

variable scope

2007-01-18 Thread gonzlobo
Greetings,
I've been using Python to successfully parse files. When the entire
program was smaller, the variable firstMsg worked fine, but now
doesn't because it's used in function PID_MinMax. I know it's a result
of variables and their scope.

I declare the variable 'firstMsg = 0' in the main loop, pass it to the
function 'PID_MinMax(firstMsg, PID)'. When the function increments the
variable, it doesn't pass it back to the main program. What am I doing
wrong?


 major snippage) ---
firstMsg = 0
skipHeader = 13

pPIDs = ['0321'] # hundreds more
pLen = len(pPIDs)
pMsgNum = pLen * [0]
pMax = pLen * [0]
pMin = pLen * [10]
pLast = pLen * [0]


def PID_MinMax(firstMsg, PID):
idx = pPIDs.index(PID)
pMsgNum[idx] += 1
# Need to have 2 samples to determine Delta
if firstMsg != 0:
tDelta = tCurrent - pLast[idx]
if tDelta > pMax[idx]:
pMax[idx] = tDelta
if tDelta < pMin[idx]:
pMin[idx] = tDelta
elif firstMsg == 0:
firstMsg = 1
pLast[idx] = tCurrent
print pMin, pMax
return firstMsg


## main ##
bf_file = file('bf_data/sByteflightLog_wISS.txt', 'r')
for line in bf_file:
# skip header
if skipHeader != 0:
skipHeader -= 1
# skip footer
elif line == '\n':
break
else:
 raw_msg = line.split()
 tCurrent = int(raw_msg[0], 16) * 0.0001
 PID = raw_msg[2]

 if PID in pPIDs:
 PID_MinMax(firstMsg, PID)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would a Dutch speaker please check this wiki page please?

2007-01-18 Thread Paul Rubin
"Martin P. Hellwig" <[EMAIL PROTECTED]> writes:
> Indeed it's not Afrikaans but just incorrect use of Dutch and not
> related to python.

It was apparently posted by someone with a .be address, so I'll guess
it was written a Belgian French speaker who knows some Dutch.  The
"me" vs "mijn" error sounds like something a French speaker might have
done.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The proper use of QSignalMapper

2007-01-18 Thread David Boddie
borntonetwork wrote:
> Thanks, David, for you help.
>
> When I change the slot function to what you show in your second
> example, I get the same results: nothing.

This may be due to something I missed in your code. When you
connect the signal from the signal mapper to your class, you
need to specify the signal as a C++ signature as well:

self.connect(self.signalMapper, QtCore.SIGNAL(
 "mapped(int)"),
 self.deleteProductIngredient)

The second example should now work.

Looking at the first example, which uses SLOT() rather than specifying
a Python method, the following might be due to the way you call
connect, though it is surprising:

> When I change it to what you
> have in your first example, I get the following:
>
> Object::connect: No such slot QApplication::map()
> Object::connect:  (sender name:   'chkProductIngredientsDelete_1')
> Object::connect:  (receiver name: 'main.py')

[...]

It looks like you should try something like this:

 self.connect(w, QtCore.SIGNAL("stateChanged(int)"),
  self.signalMapper,
  QtCore.SLOT("map()"))

I can't understand why calling self.app.connect() would cause the
connection to be attempted between self.signalMapper and self.app.

Maybe someone on the PyQt/PyKDE mailing list would be able to
explain the behaviour you're seeing:

  http://mats.imk.fraunhofer.de/mailman/listinfo/pykde

David

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


Module name to filename and back?

2007-01-18 Thread Ron Adam

Is there a function to find a filename from a dotted module (or package) name 
without importing it?

The imp function find_module() doesn't work with dotted file names.  And it 
looks like it may import the file as it raises an ImportError error exception 
if 
  it can't find the module. (Shouldn't it raise an IOError instead?)

What I'm looking for is to be able to get the full module name when I have a 
filename.  And get the full filename when I have the module name.  And do both 
of these without importing the module.

modulename <==> filename
filename <==> modulename

Ron


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


Re: variable scope

2007-01-18 Thread Bruno Desthuilliers
gonzlobo a écrit :
> Greetings,
> I've been using Python to successfully parse files. When the entire
> program was smaller, the variable firstMsg worked fine, but now
> doesn't because it's used in function PID_MinMax. I know it's a result
> of variables and their scope.
> 
> I declare the variable 'firstMsg = 0' in the main loop, pass it to the
> function 'PID_MinMax(firstMsg, PID)'. When the function increments the
> variable, it doesn't pass it back to the main program. What am I doing
> wrong?
> 
> 
>  major snippage) ---
> firstMsg = 0
(snip)
> def PID_MinMax(firstMsg, PID):
(snip)
>if firstMsg != 0:
  if firstMsg:
>tDelta = tCurrent - pLast[idx]
>if tDelta > pMax[idx]:
>pMax[idx] = tDelta
>if tDelta < pMin[idx]:
>pMin[idx] = tDelta
>elif firstMsg == 0:
  else:
>firstMsg = 1
>pLast[idx] = tCurrent
>print pMin, pMax
>return firstMsg

> ## main ##
(snip)
> if PID in pPIDs:
> PID_MinMax(firstMsg, PID)
   firstMsg = PID_MinMax(firstMsg, PID)

You're returning firstMsg from PID_MinMax, but discarding the value...
-- 
http://mail.python.org/mailman/listinfo/python-list


How to read and write huge binary files

2007-01-18 Thread Lad
What is a good  way to read binary data from HUGE  file and write  it
to another file?
Thanks for help
La.

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


How to find out if another process is using a file

2007-01-18 Thread Tom Wright
I'm writing a program which reads a series of data files as they are dumped
into a directory by another process.  At the moment, it gets sporadic bugs
when it tries to read files which are only partially written.

I'm looking for a function which will tell me if a file is opened in
write-mode by another process - if it is, my program will ignore it for now
and come back to it later.  This needs to work on linux and windows.  Mac
OS would be a bonus too.  An os-independent solution would be good, but I
could write os-specific options and have it pick the appropriate one.

Is there any way of doing this? I've drawn a blank with google so far.

A nasty hack would be to use the file modification time, and wait until
that's a few seconds in the past, but is there a nice solution?


-- 
I'm at CAMbridge, not SPAMbridge
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 and transfer-encoding = chunked

2007-01-18 Thread jdvolz
Haha!  My mistake.

The error is that when a web server is chunking a web page only the
first chunk appears to be acquired by the urllib2.urlopen call.  If you
check the headers, there is no 'Content-length' (as expected) and
instead there is 'transfer-encoding' = 'chunked'.  I am getting about
the first 30Kb, and then nothing else.

I don't get a ValueError like described at the following post:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/e3f87a65c4c7e875/8a3ea9ca84b28669?lnk=gst&q=chunked&rnum=1#8a3ea9ca84b28669

Here's the code that I think is failing, it's basically textbook Python
for accessing a url:

file = urllib2.urlopen(url)
contenttype = file.info().type
if contenttype and contenttype.find('text') > -1:
return file.read()
#
# I am checking the content type because I don't want to download
.jpegs and the like
#

I have typed similar commands into the interpreter, which also produces
only about the first 30KB of the url.

Sorry for the confusion.

Gabriel Genellina wrote:
> <[EMAIL PROTECTED]> escribió en el mensaje
> news:[EMAIL PROTECTED]
> >I am having errors which appear to be linked to a previous bug in
> > urllib2 (and urllib) for v2.4 and v2.5 of Python.  Has this been fixed?
> > Has anyone established a standard workaround?  I keep finding old
> > posts about it, that basically give up and say "well it's a known bug."
> > Any help would be greatly appreciated.
>
> Perhaps if you said what the supposed error is...
> 
> -- 
> Gabriel Genellina

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


nsis and command-line argument

2007-01-18 Thread manouchk
Hi,

is there a standart way to prepare a single exe with nsis that pass the
command line to an exe created by py2exe on windows?

py2exe allows to prepare an exe that get the command-line but needs
some lib file so that it is not so elegant to ditribute. I tried a
simple setup.nsis script to prepare a single file exe with works fine
except that it does get the command-line.

Is there a way do get the command line with the setup.nsis script?
or any other simple method ?

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


Re: How to find out if another process is using a file

2007-01-18 Thread js
How about using lock?
Let writing process locks the files before writing, and unlock after
the job's done.

I think it'd work  file in most environment.

On 1/19/07, Tom Wright <[EMAIL PROTECTED]> wrote:
> I'm writing a program which reads a series of data files as they are dumped
> into a directory by another process.  At the moment, it gets sporadic bugs
> when it tries to read files which are only partially written.
>
> I'm looking for a function which will tell me if a file is opened in
> write-mode by another process - if it is, my program will ignore it for now
> and come back to it later.  This needs to work on linux and windows.  Mac
> OS would be a bonus too.  An os-independent solution would be good, but I
> could write os-specific options and have it pick the appropriate one.
>
> Is there any way of doing this? I've drawn a blank with google so far.
>
> A nasty hack would be to use the file modification time, and wait until
> that's a few seconds in the past, but is there a nice solution?
>
>
> --
> I'm at CAMbridge, not SPAMbridge
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: connection to server not accepted (but no error) only after several hours

2007-01-18 Thread seb
Hi Dennis,

I think I have some new informations.
My system is "blocked" now but the following change make it work again
!!!
I will test it for tonight to be sure of the improvements.

I changed :
   service.bind(("", self.PORT))
to
service.bind((socket.gethostname(), self.PORT))

The strange thing is that using the "" it works for a few hours.

Regards.
Sebastien.


Dennis Lee Bieber a écrit :
> On 17 Jan 2007 00:08:52 -0800, "seb" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
> >
> > 1) I have enabled one time server that can be run as a service (R C C
> > time server) and this service is responding correctly, when at the same
> > time (before I kill it ) the python time server is not responding.
> >
>
>   What behavior do you see if you don't run them as background
> services, but rather from a regular console login?
>
> > 2) I have also tried two python time server downloaded from effbot
> > site. Both are not responding after the "non response from the time
> > server I rn" even for the first interrogation once they are started.
> > (Of course I have killed my time server when I run a new one).
> > Same behaviour no response given but no error neither.
> >
>   If you've now got a total of three programs that are not reporting
> error conditions, I'd suspect there is something else wrong in the
> system...
>
> > It is only python programs that are listening from the port 37 that are
> > blocked at a certain time.
> > How is it possible (without firewall enabled) ?
> >
>   What response do you get from the clients attempting to connect to
> this server? (I'd expect a either a flat out "denied" or, for a
> stealthed firewall, a timeout with no response).
>
>
>   You also have a race condition in your log-file...
>
> > a.start()
> > a.set_log_file("log_nw.txt")
> > a.reset_log_file()
>
>   It is possible that the thread gets a few connections between the
> .start() and the .set_log_file() and logs them to the default file name.
> Also, it is possible for connections to be logged between the
> .set_log_file() and the .reset_log_file() (where you wipe out the
> contents of the log file).
>
>   I'd suggest putting the .start() call third in that list. That way
> you create the thread object, but it is not running. Change the log file
> name, wipe out any old contents, and THEN start the thread running.
>
>   My only other comment would be to add a few wolf-fences... Print
> statements (if running in a console), or more logging messages (you
> might want to make a method out of that internal logging so all you code
> is, say
>
>   self.slog("message")
>
> and "slog" does that time stamping, and file open/close...
>
>   By logging each main step (accept, send, close) you might find where
> it stops.
> --
>   WulfraedDennis Lee Bieber   KD6MOG
>   [EMAIL PROTECTED]   [EMAIL PROTECTED]
>   HTTP://wlfraed.home.netcom.com/
>   (Bestiaria Support Staff:   [EMAIL PROTECTED])
>   HTTP://www.bestiaria.com/

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

Re: How to read and write huge binary files

2007-01-18 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Lad wrote:

> What is a good  way to read binary data from HUGE  file and write  it
> to another file?

What about `shutil.copy()`?

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A note on heapq module

2007-01-18 Thread Neil Cerutti
On 2007-01-18, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Neil Cerutti:
>> One more idea, cribbed from the linked list thread elsewhere:
>> it might be nice if your Heap could optionally use an
>> underlying collections.deque instead of a list. I don't know
>> how excellent Python's deque is, but it's possible a deque
>> would provide a faster heap than a contiguous array. C++'s
>> std::deque is the default implementation of C++'s
>> std::priority_queue for that reason (unless I'm confused
>> again).
>
> If you have some minutes you can do few speed tests and show us
> the code and the timing results...

collections.deque is the loser.

Here's the output of the program from my last run:

list: 5.81679827554
deque: 6.40347742423
C heapq: 2.24028186815

Here's the program. You can customize it somewhat to attempt to
model a real program. It builds up a heap of random integers to
some size, performs random pushes and pops for a while, and then
pops the heap down until it's empty.

import random
import timeit

OPCOUNT = 5000
HEAP_SIZE = 100

# Create a random sequence of pushes and pops.
pushes = 0
ops = []
for i in xrange(OPCOUNT):
x = random.randint(0, 1)
if x == 0 or pushes < HEAP_SIZE:
pushes += 1
ops.append(0)
else: 
pushes -= 1
ops.append(1)
# Pop off the rest
for i in xrange(pushes):
ops.append(1)

def test(mod, cont):
for op in ops:
if op:
mod.heappop(cont)
else:
mod.heappush(cont, random.randint(0, 150))

# heapqd is the pure Python heapq module without the C implementation.
t1 = timeit.Timer("test(heapqd, list())",
"from __main__ import test; import heapqd")
t2 = timeit.Timer("test(heapqd, deque())", 
"from __main__ import test; "\
"from collections import deque; "\
"import heapqd")
t3 = timeit.Timer("test(heapq, list())",
"from __main__ import test; import heapq")
print "list:", t1.timeit(100)
print "deque:", t2.timeit(100)
print "C heapq:", t3.timeit(100)

-- 
Neil Cerutti
The Pastor would appreciate it if the ladies of the congregation would lend
him their electric girdles for the pancake breakfast next Sunday morning.
--Church Bulletin Blooper

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: Catching wx events

2007-01-18 Thread Cruelemort

Chris Mellon wrote:

> On 18 Jan 2007 06:12:17 -0800, Cruelemort <[EMAIL PROTECTED]> wrote:
> > Hello all,
> >
> > I am new to this group (and new to Python) and was hoping someone would
> > be able to help me with something, it is not so much a problem it is
> > more of a general interest query about something i have a solution too
> > but am not sure it is the correct one.
> >
> > I have a class that contains a string ID and a name, and a list
> > containing a few objects of this type, i need to loop through this list
> > and create a button for each object (with the name as the label) i have
> > done this with the following code -
> >
> > for chan in self._channellist:
> > channelbutton = wx.Button(self, id=-1,
> > label=chan.getName())
> >
> > channelbutton.Bind(wx.EVT_BUTTON,self._channelChanged)
> >
> > My question is this - in the _channelChanged method, how do i know
> > which button has been pressed when i enter the channel changed method,
> > and so how do i retrieve the appropriate object depending on which
> > button has been pressed?
> >
> > I have potentially solved this problem using the UserData property in a
> > sizer, i have added all the buttons to a sizer for display purposes and
> > so SizerItem objects have been created, i can then set the original
> > object to the UserData object by putting the following line of code in
> > the loop
> >
> > sizeritem =
> > self.topsizer.Add(channelbutton,0,wx.ALIGN_RIGHT, userData=chan)
> >
> > This way i can retrieve the item in the _channelChanged method with the
> > following -
> >
> > def _channelChanged(self, event):
> > eventobj = event.GetEventObject()
> > chan = self.topsizer.GetItem(eventobj).GetUserData()
> >
> >
> > This works fine but by looking at the API it would appear the UserData
> > property is not really designed for this use ("userData - Allows an
> > extra object to be attached to the sizer item, for use in derived
> > classes when sizing information is more complex than the proportion and
> > flag will allow for").
> >
> > Another option would be to derive my own Button class and include the
> > object in there.
> >
> > Any advice on the best way to solve this problem would be appreciated.
> >
>
> Exactly how I would do it depends on the rest of the application. I
> would probably derive my own button - never be afraid to subclass.
>
> You could also generate the buttons IDs up front, and maintain a
> mapping between the IDs and the channels, like so:
>
> self.mapper = {}
> for channel in self.channels:
> id = wx.NewId()
> self.mapper[id] = channel
> channelbutton = wx.Button(self, id=id, label=channel.getName())
>
>
> def channelChanged(self, event):
> channel = self.mapper[event.Id]
>
>
> You could also use closures (lambdas or via a factory function) to
> bind the channel at the time you create the button:
>
> for channel in self.channels:
> channelbutton = wx.Button(self, label=channel.getName())
> self.Bind(wx.EVT_BUTTON, lambda event:
> self.channelChanged(channel), source=channelbutton)
>
> def channelChanged(self, channel):
> print "Channel changed to ", channel.getName()

Two good ideas, i used the mapping system, works and seems like a
slightly more elegant way of doing things.

Many thanks!

Ian

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


Re: Would a Dutch speaker please check this wiki page please?

2007-01-18 Thread Roel Schroeven
Paul Rubin schreef:
> "Martin P. Hellwig" <[EMAIL PROTECTED]> writes:
>> Indeed it's not Afrikaans but just incorrect use of Dutch and not
>> related to python.
> 
> It was apparently posted by someone with a .be address, so I'll guess
> it was written a Belgian French speaker who knows some Dutch.  The
> "me" vs "mijn" error sounds like something a French speaker might have
> done.

To me (as a Belgian Dutch speaker) it sounds more like someone writing 
phonetically (probably because of a low education or low interest in 
writing correctly) and being from the Netherlands (since the 
pronunciation of 'mijn' sounds more like 'me' there then in Flanders).

It's not unlike the use of "I should of" instead of "I should've" or "I 
should have" in English, though much less common. At least I think and 
hope it's much less common, but actually I don't read all that much 
forums, newsgroups etc. in Dutch.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: Is it possible to fasten the import of cgi?

2007-01-18 Thread Gabriel Genellina
"Cecil Westerhof" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]
> Gabriel Genellina wrote:
>
>> "Cecil Westerhof" <[EMAIL PROTECTED]> escribió en el mensaje
>> news:[EMAIL PROTECTED]
>>
>>>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse
>>>I
>>> can not time the time used to import time, but os and sys do not take
>>> more as a millisecond. My script itself takes 3 or 4 milliseconds. But
>>> importing
>>> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
>>> there a way to make this more fast? The import off cgi makes the script
>>> at least 20 times as slow. Something like mod-python is not a
>>> possibility. I could use it on my test machine, but not at the osting
>>> provider.
>> Surely os was imported earlier, and was already loaded. sys is a builtin
>> module. But I think your problem is not how much time takes importing 
>> cgi,
>> but how much time takes launching a new python process on each request.
>
> Nope, it was certainly cgi. When I fetch time after importing and after 
> the
> script finishes, the difference is 4 milliseconds. If I import the modules
> apart from cgi after I fetch the first time, there is added about 1
> millisecond to the difference. When I also import cgi after taking the
> time, the difference grows with 95 milliseconds. So for one reason ore
> another, cgi is very expensive.

I'll try to explain better: the cgi *protocol* (I'm not talking about the 
cgi *module*) requires a *new* python process to be created on *each* 
request. Try to measure the time it takes to launch Python, that is, the 
time from when you type `python ENTER` on your shell and the interpreter 
prompt appears. That time is wasted for *every* cgi request, and I bet it is 
much greater than the 95 ms you measure importing a module (be it cgi or 
whatever). You'll gain much more responsiveness if you can switch to another 
protocol, be it FastCGI, WSGI, mod_python or another.

Anyway, comparing the import time between os, sys, and cgi is not very 
meaningful. sys is a builtin module, so "import sys" does very little. os is 
likely to be already imported by the time your script begins, so "import os" 
just verifies that os is already in sys.modules. "import cgi" is the only 
example when Python actually has to load something, so it's not a surprise 
if it takes longer.

-- 
Gabriel Genellina 


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

Re: How to read and write huge binary files

2007-01-18 Thread Gabriel Genellina
"Lad" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> What is a good  way to read binary data from HUGE  file and write  it
> to another file?
Without processing the data read? shutil.copy2 or similar
Else, a lot of applications can follow the pattern read-process-write: read 
a logical block, process, write the output; where "logical block" depends on 
the application: a record, a frame, a chunk...

-- 
Gabriel Genellina 


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


Traversing the properties of a Class

2007-01-18 Thread EdG
I'm using Python version 2.4 and I created a class with some properties
like:

def GetCallAmount(self):
return somedata

def GetCallCurrency(self):
return  somemoredata

moredefs..etc.

CallAmount   = property(GetCallAmount,None,None,None)
CallCurrency = property(GetCallCurrency, None, None, None)

moreproperies..etc.

For debugging purposes, I would like to traverse the class listing out
all the properties.

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


Re: How to find out if another process is using a file

2007-01-18 Thread Gabriel Genellina
"Tom Wright" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> I'm writing a program which reads a series of data files as they are 
> dumped
> into a directory by another process.  At the moment, it gets sporadic bugs
> when it tries to read files which are only partially written.
>
> I'm looking for a function which will tell me if a file is opened in
> write-mode by another process - if it is, my program will ignore it for 
> now
> and come back to it later.  This needs to work on linux and windows.  Mac
> OS would be a bonus too.  An os-independent solution would be good, but I
> could write os-specific options and have it pick the appropriate one.

Use os.open with the O_EXCL flag; will fail if the other process has the 
file still open (and will fail if another process is reading the file, too, 
not just if someone is writing).

-- 
Gabriel Genellina 


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


Re: How to find out if another process is using a file

2007-01-18 Thread Jean-Paul Calderone
On Thu, 18 Jan 2007 14:34:52 -0300, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
>"Tom Wright" <[EMAIL PROTECTED]> escribió en el mensaje
>news:[EMAIL PROTECTED]
>
>> I'm writing a program which reads a series of data files as they are
>> dumped
>> into a directory by another process.  At the moment, it gets sporadic bugs
>> when it tries to read files which are only partially written.
>>
>> I'm looking for a function which will tell me if a file is opened in
>> write-mode by another process - if it is, my program will ignore it for
>> now
>> and come back to it later.  This needs to work on linux and windows.  Mac
>> OS would be a bonus too.  An os-independent solution would be good, but I
>> could write os-specific options and have it pick the appropriate one.
>
>Use os.open with the O_EXCL flag; will fail if the other process has the
>file still open (and will fail if another process is reading the file, too,
>not just if someone is writing).

On what platform is this true?

A better solution is to name or place files which are begin written in a which 
is recognizable and only rename or move them to their final location when they 
have been completely written.

For example, name files ".new" as they are being written.  When they are fully 
written, drop the ".new" suffix.  On the reader side, ignore any file with a 
name ending in ".new".

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

spidering script

2007-01-18 Thread David Waizer
Hello..

I'm  looking for a script (perl, python, sh...)or program (such as wget) 
that will help me get a list of ALL the links on a website.

For example ./magicscript.pl www.yahoo.com and outputs it to a file, it 
would be kind of like a spidering software..

Any suggestions would be appreciated.

David 


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


Re: closing a "forever" Server Socket

2007-01-18 Thread Matimus
> I want to ask if someone knows a better way for closing a "forever
> server" or if there is a lack in my design.

Generally you don't create a 'forever server'. You create an 'until I
say stop' server. I would do this by looking at the 'serve_forever'
method, and implementing my own 'serve_until_?' method that is similar,
but will stop if a flag is set. Then you have to create a method for
setting that flag. It could be as simple as a keypress, or you could
add a quit method to your dispatcher that sets the flag when a certain
address is visited. That second method probably needs some added
security, otherwise anybody can just visit 'your.server.com/quit' and
shut it down.

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


Memory Management in Embedded Python

2007-01-18 Thread Huayang Xia
Hi there,

I have a piece of code like this:

  void funct(PyObject* pyobj)
  {
 char   str[128];
 strncpy(str, "just a test string", sizeof(str));
 PyObject* pydata = PyObject_CallMethod(pyobj, "method_x",
"s", str);
 Py_DECREF(pydata);
  }

After the function is exited, the str is not there anymore. Will this
affect python operation. How does python use the str? It's copied or it
just uses the pointer?

Thanks in advance.

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


Re: Memory Management in Embedded Python

2007-01-18 Thread Martin v. Löwis
Huayang Xia schrieb:
> I have a piece of code like this:
> 
>   void funct(PyObject* pyobj)
>   {
>  char   str[128];
>  strncpy(str, "just a test string", sizeof(str));
>  PyObject* pydata = PyObject_CallMethod(pyobj, "method_x",
> "s", str);
>  Py_DECREF(pydata);
>   }
> 
> After the function is exited, the str is not there anymore. Will this
> affect python operation. How does python use the str? It's copied or it
> just uses the pointer?

The interpreter creates a string object, and passes that to method_x.
Creating a string object does indeed create a copy. The string object
will be refcounted, so it exists as long as there is a reference to it.
Likely (unless the method_x implementation somehow stores the string),
it gets deallocated before PyObject_Call returns.

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


Re: Traversing the properties of a Class

2007-01-18 Thread Daniel Nogradi
> I'm using Python version 2.4 and I created a class with some properties
> like:
>
> def GetCallAmount(self):
> return somedata
>
> def GetCallCurrency(self):
> return  somemoredata
>
> moredefs..etc.
>
> CallAmount   = property(GetCallAmount,None,None,None)
> CallCurrency = property(GetCallCurrency, None, None, None)
>
> moreproperies..etc.
>
> For debugging purposes, I would like to traverse the class listing out
> all the properties.


for attr in dir( yourclass ):
if repr( yourclass.__dict__[ attr ] ).startswith( 'http://mail.python.org/mailman/listinfo/python-list


Re: spidering script

2007-01-18 Thread Jonathan Curran
On Thursday 18 January 2007 11:57, David Waizer wrote:
> Hello..
>
> I'm  looking for a script (perl, python, sh...)or program (such as wget)
> that will help me get a list of ALL the links on a website.
>
> For example ./magicscript.pl www.yahoo.com and outputs it to a file, it
> would be kind of like a spidering software..
>
> Any suggestions would be appreciated.
>
> David

David, this is a touchy topic but whatever :P Look into sgmllib, and you can 
filter on the "A" tag. The book 'Dive Into Python' covers it quite nicely: 
http://www.diveintopython.org/html_processing/index.html

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


Re: Traversing the properties of a Class

2007-01-18 Thread Neil Cerutti
On 2007-01-18, EdG <[EMAIL PROTECTED]> wrote:
> For debugging purposes, I would like to traverse the class
> listing out all the properties.

This is the first thing that came to mind.

def show_properties(cls):
  for attr in dir(cls):
if isinstance(getattr(cls, attr), property):
  print attr

-- 
Neil Cerutti

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: Traversing the properties of a Class

2007-01-18 Thread EdG
Thanks.

Neil Cerutti wrote:
> On 2007-01-18, EdG <[EMAIL PROTECTED]> wrote:
> > For debugging purposes, I would like to traverse the class
> > listing out all the properties.
>
> This is the first thing that came to mind.
>
> def show_properties(cls):
>   for attr in dir(cls):
> if isinstance(getattr(cls, attr), property):
>   print attr
>
> --
> Neil Cerutti
> 
> -- 
> Posted via a free Usenet account from http://www.teranews.com

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


Re: Traversing the properties of a Class

2007-01-18 Thread EdG
Thanks.

Daniel Nogradi wrote:
> > I'm using Python version 2.4 and I created a class with some properties
> > like:
> >
> > def GetCallAmount(self):
> > return somedata
> >
> > def GetCallCurrency(self):
> > return  somemoredata
> >
> > moredefs..etc.
> >
> > CallAmount   = property(GetCallAmount,None,None,None)
> > CallCurrency = property(GetCallCurrency, None, None, None)
> >
> > moreproperies..etc.
> >
> > For debugging purposes, I would like to traverse the class listing out
> > all the properties.
>
>
> for attr in dir( yourclass ):
> if repr( yourclass.__dict__[ attr ] ).startswith( ' print 'This looks like a property although can be something
> else too: ' + attr
> 
> :)

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


Re: How can I create a linked list in Python?

2007-01-18 Thread sturlamolden

Paul Rubin wrote:

> But that's what Lisp does too.

Ok, I may have to reread Paul Graham's book on ANSI Common Lisp then.

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


Re: spidering script

2007-01-18 Thread dubs
Check out the quick start section in the documentation at Beautiful
Soup http://www.crummy.com/software/BeautifulSoup/


Wes


Jonathan Curran wrote:
> On Thursday 18 January 2007 11:57, David Waizer wrote:
> > Hello..
> >
> > I'm  looking for a script (perl, python, sh...)or program (such as wget)
> > that will help me get a list of ALL the links on a website.
> >
> > For example ./magicscript.pl www.yahoo.com and outputs it to a file, it
> > would be kind of like a spidering software..
> >
> > Any suggestions would be appreciated.
> >
> > David
>
> David, this is a touchy topic but whatever :P Look into sgmllib, and you can
> filter on the "A" tag. The book 'Dive Into Python' covers it quite nicely:
> http://www.diveintopython.org/html_processing/index.html
> 
> Jonathan

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


Re: Python Web Frameworks

2007-01-18 Thread Ximo Nadal
Shortash wrote:
> Hi Gurus,
> 
> I want to build a Python web app but im not sure which one to go for. I
> prefer something like asp.Net , which would allow me to fully seperate
> the presentation layer from the logic. Please advise?
> 
> thanks,
> 
> "Shortash'
> 
Hi,

Look at  there are same of them.

Now I'm studing karrigell, it's very interesting.

bye,

-- 
Ximo Nadal <[EMAIL PROTECTED]>
Powered by Debian GNU/Linux 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find out if another process is using a file

2007-01-18 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:

> "Tom Wright" <[EMAIL PROTECTED]> escribió en el mensaje 
> news:[EMAIL PROTECTED]
> 
> > I'm writing a program which reads a series of data files as they are 
> > dumped
> > into a directory by another process.  At the moment, it gets sporadic bugs
> > when it tries to read files which are only partially written.
> >
> > I'm looking for a function which will tell me if a file is opened in
> > write-mode by another process - if it is, my program will ignore it for 
> > now
> > and come back to it later.  This needs to work on linux and windows.  Mac
> > OS would be a bonus too.  An os-independent solution would be good, but I
> > could write os-specific options and have it pick the appropriate one.
> 
> Use os.open with the O_EXCL flag; will fail if the other process has the 
> file still open (and will fail if another process is reading the file, too, 
> not just if someone is writing).

O_EXCL fails if the file exists at all - whether closed or open.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Traversing the properties of a Class

2007-01-18 Thread Bruno Desthuilliers
EdG a écrit :
> I'm using Python version 2.4 and I created a class with some properties
> like:
> 
> def GetCallAmount(self):
> return somedata


The recommended naming convention is all_lower,ie:
def get_call_amount(self):


And FWIW, there are idioms to avoid polluting the class namespace, like:

class Account(object):
 @apply
 def amount():
def fget(self):
return something
def fset(self, value):
do_something_with(value)
return property(**locals())

> For debugging purposes, I would like to traverse the class listing out
> all the properties.

cf Neil's answer.

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


Re: PyMeld for html templates?

2007-01-18 Thread Bruno Desthuilliers
Sean Schertell a écrit :
> I'm trying to decide which template system to get married to. I think  
> I've narrowed it down to PyMeld, Cheetah, or Jinja  but leaning  heavily 
> toward PyMeld because I love the idea that your templates are  *totally* 
> clean and that get manipulated from behind the scenes. This  seems to be 
> elegantly inline with the Sacred Creed of separation of  logic from 
> presentation.

"separating logic from presentation" is often misunderstood. It should 
really read "separating application logic from presentation logic", not 
"separating presentation logic from html code".

> Of course I'm going to try them all

The don't forget to have a look at Genshi and Mako too.

My 2 cents...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to find out if another process is using a file

2007-01-18 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
Donn Cave <[EMAIL PROTECTED]> writes:
|> In article <[EMAIL PROTECTED]>,
|>  "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
|> > "Tom Wright" <[EMAIL PROTECTED]> escribió en el mensaje 
|> > news:[EMAIL PROTECTED]
|> > 
|> > > I'm writing a program which reads a series of data files as they are 
|> > > dumped
|> > > into a directory by another process.  At the moment, it gets sporadic 
bugs
|> > > when it tries to read files which are only partially written.
|> > >
|> > > I'm looking for a function which will tell me if a file is opened in
|> > > write-mode by another process - if it is, my program will ignore it for 
|> > > now
|> > > and come back to it later.  This needs to work on linux and windows.  Mac
|> > > OS would be a bonus too.  An os-independent solution would be good, but I
|> > > could write os-specific options and have it pick the appropriate one.
|> > 
|> > Use os.open with the O_EXCL flag; will fail if the other process has the 
|> > file still open (and will fail if another process is reading the file, 
too, 
|> > not just if someone is writing).
|> 
|> O_EXCL fails if the file exists at all - whether closed or open.

Yes.  In theory.  In practice, it usually works on normal files, provided
that all opens are local.  Under some circumstances, it will even work
for NFS mounted files, as far as I recall.

MVS (now zOS) and other mainframe systems had what the poster wants, but
modern systems don't.  I shall not recommend that the poster asks IBM
for a copy of zOS, for reasons that will be well-known to anyone who used
MVS (which are NOT the ones claimed by the Unix brigade, which are mostly
bogus) :-)

Under Linux, you can do something with fuser, and I am pretty certain that
modern Macintoshes (i.e. BSD) will have an equivalent.  It can't be made
reliable (unlike under MVS), but might reduce the number of problems.


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

Zope 3 Boot Camp and Sprint registration open

2007-01-18 Thread Chris Calloway
The Triangle (NC) Zope and Python Users Group invites you to register 
for Camp 5 and the BBQ Sprint:

http://trizpug.org/boot-camp/camp5/

This is a Zope 3 boot camp followed by a Plone 3 sprint. The boot camp 
is taught by Philipp von Weitershausen, author of Web Component 
Development with Zope 3. The training has previously only been offered 
in Europe and is now available in North America for the first time. The 
sprint includes several sponsored and invited sprinters.

TriZPUG hopes you will participate in Camp 5 in Chapel Hill, NC.

Camp 5: Saturday March 10 - Tuesday March 13, 2007
BBQ Sprint: Wednesday March 14 - Saturday March 17, 2007

-- 
Sincerely,

Chris Calloway
http://www.seacoos.org
office: 332 Chapman Hall   phone: (919) 962-4323
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I create a linked list in Python?

2007-01-18 Thread Neil Cerutti
On 2007-01-18, sturlamolden <[EMAIL PROTECTED]> wrote:
>
> Paul Rubin wrote:
>
>> But that's what Lisp does too.
>
> Ok, I may have to reread Paul Graham's book on ANSI Common Lisp
> then.

Here's something silly I whipped up to play with.

r""" Lisp style singly-linked lists called llist. 

"""

def consp(o):
return isinstance(o, Cons)

def car(c):
""" Return the car of a lisp-list. Undefined for nil. """
if null(c):
raise AttributeError("nil has no cdr")
return c.car

def cdr(c):
""" Return the cdr of a lisp=list. """
if null(c):
return nil
return c.cdr

def cons(o, c):
""" Build a new cons cell from an object and a Cons. """
return Cons(o, c)

def null(c):
return c is nil

def rplaca(c, o):
c.car = o
return c

def rplacd(c, o):
c.cdr = o
return c

def llist(li):
""" Build a llist from a list. """
c = nil
for a in reversed(li):
if isinstance(a, list):
c = cons(llist(a), c)
else:
c = cons(a, c)
return c

class Cons(object):
def __init__(self, car, cdr):
self.car = car
self.cdr = cdr
def __repr__(self):
def helper(li, s):
if null(li):
return s + ")"
else:
return helper(cdr(li), s + " %s" % repr(car(li)))
return helper(self.cdr, "(" + repr(self.car))

class Nil(Cons):
def __init__(self):
Cons.__init__(self, None, None)
def __repr__(self):
return '()'

nil = Nil()

print cons(5, nil)
print cons(5, cons(3, nil))
print cons(cons(5, (cons(7, nil))), cons(cons(5, cons(3, nil)), nil))
print nil
print llist([1, ['a', 'b', 'c'], 2, 3])

There's lots more more stuff to add, but the fun wore out. I'd
like if it the cdr of nil could actually be nil, instead of None
with a special case in cdr, but I couldn't figure out a neat way
to do it.

-- 
Neil Cerutti
I've had a wonderful evening, but this wasn't it. --Groucho Marx

-- 
Posted via a free Usenet account from http://www.teranews.com

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


Re: Traversing the properties of a Class

2007-01-18 Thread EdG
This works great.  I have one more question.  Now that I have the name
of the property, how do I get it's value?

I want to print  '%s = %s' % (attr,theattributesvalue)

Thanks.

Neil Cerutti wrote:
> On 2007-01-18, EdG <[EMAIL PROTECTED]> wrote:
> > For debugging purposes, I would like to traverse the class
> > listing out all the properties.
>
> This is the first thing that came to mind.
>
> def show_properties(cls):
>   for attr in dir(cls):
> if isinstance(getattr(cls, attr), property):
>   print attr
>
> --
> Neil Cerutti
> 
> -- 
> Posted via a free Usenet account from http://www.teranews.com

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


Re: [Python-Dev] Deletion order when leaving a scope?

2007-01-18 Thread Terry Reedy

"Paul McGuire" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| "Calvin Spealman" <[EMAIL PROTECTED]> wrote in message
| news:[EMAIL PROTECTED]
| > Absolutely an irrelevent side effect, especially when you take into
| > consideration the 4 and counting alternative implementations of the
| > language.
| >
| > None the less, I can explain why it is as it is, keeping in mind its
| > not like that on purpose, its just how it is. Locals are optimized
| > into an array for fast lookup. Every name assigned to in a function is
| > known as a local in that function and this internal array holds its
| > reference. It is simply a product of the array indexes and deletion
| > order being the same, 0 to N.
| >
|
| Oh good!  Now I can write code that relies on this behavior!

According to a followup on python-dev, you can't.  The above is the normal 
behavior (for CPython) but it can be modified by imports and 
cross-references.

Or did you forget a smiley?

tjr



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


Re: More M2Crypto issues

2007-01-18 Thread John Nagle
Upgraded to Python 2.5 on the Linux system, rebuild M2Crypto,
and it stil fails, but the last line of the error message changed to:

ValueError: invalid literal for long() with base 10: '_40f91a08_p_SSL_CTX'

Others have encountered this problem, from a Google search.

Is "long" supposed to operate on C objects?

John Nagle

John Nagle wrote:
>   I've been running M2Crypto successfully using Python 2.4 on Windows 2000,
> and now I'm trying to get it to work on Python 2.3.4 on Linux.
> 
>   Attempting to initialize a context results in
> 
> Traceback (most recent call last):
>   File "/www/htdocs/sitetruth.com/cgi/ratingdetails.cgi", line 46, in ?
> DetailsPageBuilder.detailspage(kdbfile,ktemplatefile,url)# check 
> and display domain or URL as web page
>   File "./sitetruth/DetailsPageBuilder.py", line 70, in detailspage
> sitecert = InfoSSL2.Certificate(siteinfo, kverifylocations, verbose)
>   File "./sitetruth/InfoSSL2.py", line 147, in __init__
> self.ctx = createsslcontext(trustedcafile, verbose)# Generate 
> general SSL context
>   File "./sitetruth/InfoSSL2.py", line 40, in createsslcontext
> ctx = SSL.Context('sslv3')# Create 
> context with SSL params
>   File "/home/sitetruth/lib/python/M2Crypto/SSL/Context.py", line 43, in 
> __init__
> map()[long(self.ctx)] = self
> ValueError: invalid literal for long(): _480e1008_p_SSL_CTX
> 
>which, when I look at the code and try some test cases, seems
> legitimate.  The cacheing code is trying to convert a reference to an
> object (a C object, in fact) into a "long".  Python 2.4 on Windows
> will do that.  Python 2.3.4 on Linux converts it to a string first,
> gets "_480e1008_p_SSL_CTX", and then tries to convert that to an
> integer, which fails.
> 
>M2Crypto is supposed to work with Python 2.3, so this should work.
> 
> John Nagle
-- 
http://mail.python.org/mailman/listinfo/python-list


distutils data file difficulties

2007-01-18 Thread Brian L. Troutwine
I am new to the use of distutils and am having difficulty getting
distutils recognize and install data files. Here are the relevant parts
of my source directory:

ExampleTree/
|-- __init__.py
|-- data
|   |-- Example1.txt
|   |-- Example2.txt
|   `-- __init__.py
|-- subPackage1
|   |-- (...)
`-- subPackage2
|-- (...)

I would like to install Example1.txt and Example2.txt under data/ upon
installation. I cannot seem to write a proper setup.py to accomplish
this. Here are the relevant bits of my setup.py:

#!/usr/bin/env python

from distutils.core import setup

setup(name="ExampleTree",
(...),
packages=['ExampleTree', ExampleTree/data',
'ExampleTree/subPackage1',
''ExampleTree/subPackage2'],
package_dir={'data' : 'ExampleTree/data'},
package_data={'data': ['Example1.txt', 'Example2.txt']},
)

What am I doing incorrectly?

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


Re: Traversing the properties of a Class

2007-01-18 Thread Bruno Desthuilliers
EdG a écrit :
(top-post corrected)
> 
> Neil Cerutti wrote:
> 
>>On 2007-01-18, EdG <[EMAIL PROTECTED]> wrote:
>>
>>>For debugging purposes, I would like to traverse the class
>>>listing out all the properties.
>>
>>This is the first thing that came to mind.
>>
>>def show_properties(cls):
>>  for attr in dir(cls):
>>if isinstance(getattr(cls, attr), property):
>>  print attr
>>

 > This works great.  I have one more question.  Now that I have the name
 > of the property, how do I get it's value?
 >
 > I want to print  '%s = %s' % (attr,theattributesvalue)


Then you need to have the instance...

def list_properties(cls):
   return [
 name for name in dir(cls)
 if isinstance(getattr(cls, name), property)
   ]

def print_properties(obj):
   for name in list_properties(obj.__class__):
 print "%s : %s" % (name, str(getattr(obj, name)))

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


Tiling and Spacefilling

2007-01-18 Thread [EMAIL PROTECTED]
[ slightly improved over Math Forum draft ]

Probably a fault line or cultural divide between acutely
differing schools of thought, is in this area of tiling
or mosaic making. Some schools consider this a stupid
waste of time, others a core topic, whereas a 3rd group
stays more neutral on the issue, and a tiny 4th group has
no idea what I'm talking about.

I'm in the second group (core topic) as tiling is to
spacefilling as figurate are to polyhedral numbers.
We may start in a plane, in deference to some millenia
of pre-NASA reflex conditioning, but we're still on a
runway, accelerating, and before long (way sooner than
in traditional curricula), we'll be airborne, moving
up into higher D. Tetrahedra are most definitely a
feature of K-5. If NCTM doesn't grasp that, it's
missing the boat.

Back to tiling: we have the classifications, the Escher
lithographs (which follow into Part Two), and the tie ins
to Mesopotamian religions, the three biggies especially,
and their respective sacred geometries. I know "sacred
geometry" is taboo in traditional mathematics, but this
is ~M!, Katrina Network type stuff, closer to George Bush
Sr.'s "voodoo economics" (except managed more by geeks
(Bush was more of a jock, not that we can't share power)).

Rolling forward, we get to the Kepler-Penrose aperiodic
tiling studies, various heuristics, again finding echoes
in Part Two (in what some Russians call stereometry),
where we likely look at Hargittai & Hargittai (Hungarian),
plus Chakovian coordinates (quadrays, simplicials,
whatever nomenclature).

I've already made the case for Polyhedra numerous times.
Thanks to breakthroughs in architecture in the 20th
century, we're obligated to teach about the hexapent in
some way shape or form. Katrina Network is strong on
this, but you'll find other sources. Top of my list
would be J. Baldwin's 'Bucky Works' (packed with ~M!).

For a more prefrequency approach, I recommend Cromwell's
'Polyhedra', and its cartoon proof of Euler's V + F =
E + 2 based on the interdigitating trees of Von Staudt's.

And of course we're not about to bleep over Fuller's
volumes tables, nor MITEs, nor the Jitterbug Trans-
formation -- all pure gold as far as we're concerned.

So to recap... Given I'm of a school which regards
tiling as core, I'm putting my shoulder behind two big
initiatives in computer science these days: CP4E and
HP4E.

CP4E was hatched by Guido, BDFL of Python Nation, and
DARPA, and carried forward billiantly (at least one
doctoral dissertation already on file, about our early
beginnings as a think tank slash on-line community [1]).

HP4E was hatched by yours trully, though mostly as a
marketing gimmick in homage to CP4E and Wanderer Glenn
Stockton's global matrix campaign. I certainly take
advantage of Python a lot, using its generators (a recent
feature) to spit out successive terms in figurate and
polyhedral number sequences, e.g. 1, 3, 6, 10... and
1, 12, 42, 92... (see my Focal Points for more details,
plus my CP4E website, one of many curriculum "hot springs"
in our cyberspace-based Python Nation [2][3]).

Kirby

[1] John Miller's PhD dissertation, Promoting Computer
Literacy Through Programming Python (1.37 MB), looks at
the issues around teaching with Python, and explores some
of the threads taken up on edu-sig.
http://www.python.org/community/sigs/current/edu-sig/

[2] Focal Points:
http://mybizmo.blogspot.com/2006/09/focal-points.html

[3] CP4E website: http://www.4dsolutions.net/ocn/cp4e.html

===

For more on ~M!:
http://worldgame.blogspot.com/2007/01/m.html

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


  1   2   >