Re: problem with split

2006-10-07 Thread [EMAIL PROTECTED]
I am not sure if I am having trouble with the test program or the
routine..  (I had the brackets in the wrong place on the other)

IDLE 1.1.3   No Subprocess 
>>>
['1', 'String pad']
>>>

I get this but I have at least three lines and the

v = []
v = csoundroutines.csdInstrumentList('bay-at-night.csd')
print v




[EMAIL PROTECTED] wrote:
> I think I am very close the return line is tripping me up.  (this is
> the first list that I have tried to program in python)
>
> return (s.group[1], s.group[2])
>
> Traceback (most recent call last):
>   File "C:\Python24\Lib\site-packages\boa-constructor\test of
> snake\test_of_csoundroutines_list.py", line 5, in ?
> v = csoundroutines.csdInstrumentList('bay-at-night.csd')
>   File "C:\Python24\Lib\site-packages\boa-constructor\test of
> snake\csoundroutines.py", line 43, in csdInstrumentList
> return (s.group[1], s.group[2])
> TypeError: unsubscriptable object
>
>
>
>
>
>
>
>
>
>
> hanumizzle wrote:
> > On 6 Oct 2006 23:09:08 -0700, MonkeeSage <[EMAIL PROTECTED]> wrote:
> > >
> > >
> > > On Oct 6, 11:33 pm, hanumizzle <[EMAIL PROTECTED]> wrote:
> > > > import re
> > > >
> > > > 
> > > >
> > > > if line.startswith('instr'):
> > > >   p = re.compile(r'(\d+)\s+;(.*)$')
> > > >   m = p.search(line)
> > > >
> > > > return (m.group(1), m.group(2))
> > >
> > > You probably don't want startswith, in case there are initial spaces in
> > > the line.
> >
> > Pardon me; I am not very familiar with file format in question.
> >
> > > Also, since the regexp is single use, you can just use the
> > > re.search class method, which will compile the regexp implicitly.
> >
> > Cool.
> >
> > > May
> > > also want to strip the second grouped match, in case of trailing
> > > spaces.
> > 
> > Cosmetic, but good idea.
> > 
> > -- Theerasak

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


Re: humble coin head or tail game script I wrote

2006-10-07 Thread Steve Holden
Camellia wrote:
> Oh I get it and ashamed, thank you for explaining it to me:)
> 
> so I sould:
> ini_guess=random.randrange(2)
> 
> for item in  list:
> if item=='h':
> ...
> if item ==t':
> ...
> 
Welcome to programming. You have learned, as many thousands have learned 
before you, how easy it is to assume correct behaviour in something that 
is, in fact, wrong. Those with an aptitude for the task accept with 
humility (no need for shame, though, as inexperience is a valid excuse) 
that they will continue to make errors they do not see.

Your response to the corrections you received implies you have a future 
as a programmer!

You might also want to do some reading about test-driven development, 
which can save some time hunting obscure bugs.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Subclassing built-in classes

2006-10-07 Thread Gabriel Genellina

At Friday 6/10/2006 06:58, Maric Michaud wrote:


As the first post said "...couldn't python (in theory)...", I was discussing
if it would be possible for python (in some future version) to manage the
literals so that they use the constructors in the __builtin__ module, I
didn't say it works actually (I'm aware it's not the case).


The idea looks crazy for me... You suggest that code like this:

x = 12 + 6.0 - len('ABCD'

would be evaluated at run time as it were:

x = int('12') + float('6.0') - len(str('ABCD'))

Certainly would slow down the whole execution time *a*lot*, with no 
benefit for almost nobody, if *every* reference to *any* literal in 
the code calls a python function at run time.
And unless you return *exactly* the same object as now, almost all 
code would break!

Do you have any useful usage for this?


--
Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: dictionary containing a list

2006-10-07 Thread Steve Holden
John Machin wrote:
> Ben wrote:
> 
>>Hello...
>>
>>I have set up a dictionary into whose values I am putting a list. I
>>loop around and around filling my list each time with new values, then
>>dumping this list into the dictionary. Or so I thought...
>>
>>It would appear that what I am dumping into the dictionary value is
>>only a pointer to the original list, so after all my iterations all I
>>have is a dictionary whose every value is equal to that of the list the
>>final time I looped around :-(
>>
>>Is there a way to acheive what I was attempting ? I have done something
>>almost identical with classes  in a list before, and in that case a new
>>instance was created for each list entry...
>>
>>
>>I hope this makes some sense, and doesn't seem to head bangingly
>>simple...
>>
> 
> 
> Do you consult your physician over a video link while wearing a ninja
> costume down an unlit coal mine at midnight?
> 
> Please consider the possibility that your description of what you think
> your code might be doing is not enough for diagnosis.
> 
> You may need to supply:
> (1) a listing of your code
> (2) a small amount of input data
>e.g. [(1, 'foo'), (42, 'bar'), (1, 'zot')]
> (3) the output you expect from that input:
>e.g. {1: ['foo', 'zot'], 42: ['bar']}
> 
One of the fascinating things about c.l.py is that sometimes a questin 
will be posted that makes almost no sense to me, and somebody else will 
casually read the OP's mind, home in on the issue and provide a useful 
and relevant answer.

In this case it seems transparent to me, though probably not to you, 
that Ben's problem is rootd in the following behaviour, well-known in 
python but frequently confusing to noobs:

  >>> a = [1, 2, 3]
  >>> firstlist = a
  >>> a.append('another element')
  >>> firstlist
[1, 2, 3, 'another element']
  >>>

Ben probably needs to look at creating copies using the list() type:

  >>> a = [1, 2, 3]
  >>> firstlist = list(a)
  >>> a.append('another element')
  >>> firstlist
[1, 2, 3]
  >>>

or perhaps, in omore complex circumstances, using the copy module.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: How to execute a python script in .NET application

2006-10-07 Thread Steve Holden
Chandra wrote:
> Hi,
> 
> Is there a way to execute a python script(file) in ASP.NET application
> (programmatically)??
> 
Probably use IronPython, I should think.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Subclassing built-in classes

2006-10-07 Thread hanumizzle
On 10/7/06, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> At Friday 6/10/2006 06:58, Maric Michaud wrote:
>
> >As the first post said "...couldn't python (in theory)...", I was discussing
> >if it would be possible for python (in some future version) to manage the
> >literals so that they use the constructors in the __builtin__ module, I
> >didn't say it works actually (I'm aware it's not the case).
>
> The idea looks crazy for me... You suggest that code like this:
>
>  x = 12 + 6.0 - len('ABCD'
>
> would be evaluated at run time as it were:
>
>  x = int('12') + float('6.0') - len(str('ABCD'))
>
> Certainly would slow down the whole execution time *a*lot*, with no
> benefit for almost nobody, if *every* reference to *any* literal in
> the code calls a python function at run time.
> And unless you return *exactly* the same object as now, almost all
> code would break!
> Do you have any useful usage for this?

Sometimes I've had weird ideas that I thought might be useful, but
they turned out to be doo doo. On other occasions, the SWAG paid off
(e.g., vesa driver runs faster than accelerated via driver for
compositing in Xorg) It's all a matter of proposing and disposing, and
mistakes happen.

Somehow, I missed Python's round() function and came up with
convoluted solution involving decimal. Gee duh, Theerasak

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


Re: Python to use a non open source bug tracker?

2006-10-07 Thread Giovanni Bajo
[EMAIL PROTECTED] wrote:

> Giovanni> Are bug-tracker configuration issues so critical that
> having Giovanni> to wait 48-72hrs to have them fixed is
> absolutely unacceptable Giovanni> for Python development?
>
> Yes, I think that would put a crimp in things.  The downtimes we see
> for the SourceForge tracker tend to be of much shorter duration than
> that (typically a few hours) and cause usually minor problems when
> they occur.  For the tracker to be down for 2-3 days would make the

I was actually thinking of 48-72hrs to do regulard admin work like installing
latest security patch or actrivate a new account.

> developers temporarily blind to all outstanding bug reports and
> patches during that time and prevent non-developers from submitting
> new bugs, patches and comments.  Those people might well forget about
> their desired submission altogether and not return to submit them
> once the tracker was back up.

I understand your concerns, but I have to remember you that most bug reports
submitted by users go totally ignored for several years, or, better, forever. I
do not have a correct statistic for this, but I'm confident that at least 80%
of the RFE or patches filed every week is totally ignored, and probably at
least 50% of the bugs too. I think there is a much bigger problem here wrt QOS.

So, you might prefer 6-10 people to activate a new tracker account faster than
light. I'd rather have 3-days delay in administrative issues because our single
administrator is sleeping or whatever, and then have 2-3 people doing regular
bug processing.
-- 
Giovanni Bajo


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


Re: n-body problem at shootout.alioth.debian.org

2006-10-07 Thread Giovanni Bajo
Peter Maas wrote:

> I have noticed that in the language shootout at
> shootout.alioth.debian.org the Python program for the n-body problem
> is about 50% slower than the Perl program. This is an unusual big
> difference. I tried to make the Python program faster but without
> success. Has anybody an explanation for the difference? It's pure
> math so I expected Perl and Python to have about the same speed.

Did you try using an old-style class instead of a new-style class?
-- 
Giovanni Bajo


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


Re: humble coin head or tail game script I wrote

2006-10-07 Thread Ant

> # Get a list which contains 10 values from the user
> # let them predict Head Or Tail in ten times coin thrown
> # and then prdict the list by a fixed rule
>
>
> list = []
>
> print 'Predict Head or Tail in ten times coin thrown\nJust input \'h\'
> or \'t\' please\n'
>
> count = 0
> while True:
> count += 1
> print '\nNo.', count, ', h or t? '
> pre_user = raw_input()
> while pre_user != 'h' and pre_user != 't':
> print '\njust enter \'h\' or \'t\' please'
> print '\nNo.', count, ', h or t? '
> pre_user = raw_input()
> list.append(pre_user)
> if count == 10:
> break

You can simplify this considerably:

user_input = []  # list is a keyword so makes a bad variable name.

while len(user_input) < 10:
print '\nNo.', len(user_input) + 1, ', h or t? '
pre_user = raw_input()
if pre_user not in ["h","t"]:   # Note you can also use not
in "ht"
print '\njust enter \'h\' or \'t\' please'
continue
user_input.append(pre_user)

print user_input

HTH.

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


Re: dictionary containing a list

2006-10-07 Thread Fredrik Lundh
Steve Holden wrote:

> One of the fascinating things about c.l.py is that sometimes a questin 
> will be posted that makes almost no sense to me, and somebody else will 
> casually read the OP's mind, home in on the issue and provide a useful 
> and relevant answer.

if the assertions made by some about the documentation's unsuit-
ability for some are in fact true, that's probably some kind of
natural selection in action.



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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread Gabriel Genellina

At Saturday 7/10/2006 02:15, MonkeeSage wrote:


On Oct 6, 8:23 pm, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> if 2 in [1,2,3]: print "Use the same (in) operator"
> elif 'E' in ('E','r','i','k'): print "Works for any sequence"
> elif 'o' in 'hello': print "Even strings"

This isn't really analogous is it? For "somedict.has_key(k)" or "k in
somedict", you don't need to know the value of somedict[k] ahead of
time. So you can avoid KeyError by asking if the key exists first
before trying to get the value.


The meaning comes from the most common usage. For a list, you want to 
know if an object is contained in the list (not if an index is in 
range!). For a dictionary, you usually want to know if it maps 
anything to a given key (not if any key maps to that value!). These 
are the most common operations, and that's why they have the simple 
sintax "a in b". [BTW, usage of operator "in" as "key in dict" is 
rather new to Python; has_key() were the only way to test for key 
existence some time ago].



Wouldn't that be more like this for
lists (and other sequences):

def has_index(seq, index):
  try:
seq[index]
return True
  except IndexError:
return False

I've often wondered why there is no built-in method like that for
sequence objects.


Because it's not needed at all: valid sequence indexes are *exactly* 
range(len(seq)). This is the basic point of being a sequence: when 
indexes are not contiguous, in fact you have a mapping, not a sequence.



And also why not the equivalent of dict.get for other
sequences:

def get(seq, index, default=None):
  if has_index(seq, index):
return seq[index]
  else:
return default

Seems useful...


Sometimes, maybe... But since you can write it efficientely in a few 
lines when needed, I don't see the need to put it into the core language.



--
Gabriel Genellina
Softlab SRL 






__
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas


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

Re: Dumping the state of a deadlocked process

2006-10-07 Thread Hendrik van Rooyen
 <[EMAIL PROTECTED]> wrote:
> Hi all
>
> I'm currently having some issues with a process getting deadlocked. The
> problem is that the only way I can seem to find information about where
> it deadlocks is by making a wild guess, insert a pdb.set_trace() before
> this point, and then step until it locks up, hoping that I've guessed
> right.
>
> The frustrating part is that most of the time my guesses are wrong.

Welcome to the wonderful world of crash and burn

>
> It would be really nice if I could send the python process some signal
> which would cause it to print the current stacktrace and exit
> immediately. That way I would quickly be able to pinpoint where in the
> code the deadlock happens. Java has a somewhat similar feature where
> you can send a running VM process a SIGQUIT, to which it will respond
> by dumping all current threads and lots of other information on stdout.
>
> Is this possible somehow?

Have you tried to sprinkle your code with print statements of the "We get here
No: 7" kind - you can get quite a good idea of what is going on if you do, and
if there are threads running - the results are often surprisingly insightful...

- Hendrik

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


Re: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. AndySingleton

2006-10-07 Thread Hendrik van Rooyen
"Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

8<---
> ... - I don't wanna get 
> into the details of my underwear :P
> 
> Diez

Why not? - what are you hiding?

- Hendrik


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


Re: dictionary containing a list

2006-10-07 Thread John Machin

Steve Holden wrote:
> John Machin wrote:
> > Ben wrote:
> >
> >>Hello...
> >>
> >>I have set up a dictionary into whose values I am putting a list. I
> >>loop around and around filling my list each time with new values, then
> >>dumping this list into the dictionary. Or so I thought...
> >>
> >>It would appear that what I am dumping into the dictionary value is
> >>only a pointer to the original list, so after all my iterations all I
> >>have is a dictionary whose every value is equal to that of the list the
> >>final time I looped around :-(
> >>
> >>Is there a way to acheive what I was attempting ? I have done something
> >>almost identical with classes  in a list before, and in that case a new
> >>instance was created for each list entry...
> >>
> >>
> >>I hope this makes some sense, and doesn't seem to head bangingly
> >>simple...
> >>
> >
> >
> > Do you consult your physician over a video link while wearing a ninja
> > costume down an unlit coal mine at midnight?
> >
> > Please consider the possibility that your description of what you think
> > your code might be doing is not enough for diagnosis.
> >
> > You may need to supply:
> > (1) a listing of your code
> > (2) a small amount of input data
> >e.g. [(1, 'foo'), (42, 'bar'), (1, 'zot')]
> > (3) the output you expect from that input:
> >e.g. {1: ['foo', 'zot'], 42: ['bar']}
> >
> One of the fascinating things about c.l.py is that sometimes a questin
> will be posted that makes almost no sense to me, and somebody else will
> casually read the OP's mind, home in on the issue and provide a useful
> and relevant answer.
>
> In this case it seems transparent to me, though probably not to you,
> that Ben's problem is rootd in the following behaviour, well-known in
> python but frequently confusing to noobs:
>
>   >>> a = [1, 2, 3]
>   >>> firstlist = a
>   >>> a.append('another element')
>   >>> firstlist
> [1, 2, 3, 'another element']
>   >>>
>

It's quite transparent to me that his symptom is caused by the one list
being used throughout the exercise, instead of one per different dict
key. What you have described is one possibility.

Here's another possibility: Making the charitable assumption that he
has an outer loop and an inner loop, maybe (as I think another poster
has already suggested) all he needs to do is move "mylist = []" inside
the outer loop. Note that he doesn't say explicitly whether the one
list that he gets is the *correct* list for the last key, or whether
it's the catenation of all the correct lists, or something else.

Yet another: Noobs do all sorts of funny things. He could be operating
on a "clean the bucket out after each use instead making a new one"
paradigm:

| >>> d= {}
| >>> L = []
| >>> L.append(1)
| >>> L.append(2)
| >>> d['a'] = L
| >>> d
| {'a': [1, 2]}
| >>> del L[:]
| >>> d
| {'a': []}
| >>> L.append(3)
| >>> L.append(4)
| >>> d['b'] = L
| >>> d
| {'a': [3, 4], 'b': [3, 4]}

Cheers,
John

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


Re: humble coin head or tail game script I wrote

2006-10-07 Thread Camellia
Steve Holden thank you for your kind words, they pumped me up:)
I don't really know much about TDD however I googled it and found this:
http://www.agiledata.org/essays/tdd.html
Which is obvious too complicated. However I'll read through it anyway.
Thank you for your advice:)

Ant thank you for pointing that out, I made the little code too
complicated.
Well, actually this is the simplified version, the first one I did was
like:
list_1 = raw_input()
list_2 = raw_input()
...
list_10 = raw_input()
and then I found I'm doing the computer's work...

Thanks for all the kind people here
Peace
Kelvin


Steve Holden wrote:
> Camellia wrote:
> > Oh I get it and ashamed, thank you for explaining it to me:)
> >
> > so I sould:
> > ini_guess=random.randrange(2)
> > 
> > for item in  list:
> > if item=='h':
> > ...
> > if item ==t':
> > ...
> >
> Welcome to programming. You have learned, as many thousands have learned
> before you, how easy it is to assume correct behaviour in something that
> is, in fact, wrong. Those with an aptitude for the task accept with
> humility (no need for shame, though, as inexperience is a valid excuse)
> that they will continue to make errors they do not see.
>
> Your response to the corrections you received implies you have a future
> as a programmer!
>
> You might also want to do some reading about test-driven development,
> which can save some time hunting obscure bugs.
>
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb   http://holdenweb.blogspot.com
> Recent Ramblings http://del.icio.us/steve.holden

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


Re: Dumping the state of a deadlocked process

2006-10-07 Thread andre . naess

MrJean1 wrote:
> Did you try using the signal module?  If not, a basic example is here
>  which may need to be
> extended.

I looks useful. I gave it a try, and the only weakness it has is that
when my process locks, it locks so badly that it doesn't respond to
CTRL-C, or any other signal. But by sending it a SIGQUIT which causes
it to dump the current state, and then kill it, I get the dump I need.

This is actually not a multi-threaded app. It's an application which
uses a SQL DB. The problem I was having was that I had a cursor which
started a transaction, and then never finished. Then some other cursor
came along and tried to perform a delete table, and they both locked
up. The cursor isn't ending it's transaction, and the transaction
prevents the delete table from being executed. Luckily Postgresql
allows me to list current activity, otherwise I would have been
scratching my head still.

Using logging or print statements to debug this sort of things is
highly unsatisfactory. I think the way Java uses SIGQUIT is pretty
neat, are there any reasons why Python can't adopt something similar?

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


Re: humble coin head or tail game script I wrote

2006-10-07 Thread Camellia
OK so this is the result after I taking everything I'm teached in this
thread:


print 'Predict Head or Tail in ten times coin thrown\nJust input \'h\'
or \'t\' please\n'

count = 0
user_input = []

while len(user_input) < 10:
print '\nNo.', len(user_input)+1, ', h or t?'
pre_user = raw_input()
if pre_user not in ['t', 'h']:
print '\njust enter \'h\' or \'t\' please'
continue
user_input.append(pre_user)
count += 1

correct = 0
import random
ini_guess = random.randrange(2)
list_guess = ['t', 'h']
ini_guess = list_guess[ini_guess]
# generate random initial guess
for item in user_input:
if item == 'h':
if ini_guess == item:
correct += 1
else:
ini_guess = 'h'
if item == 't':
if ini_guess == item:
correct += 1
else:
ini_guess = 't'

print '\n\nI got', correct, 'out of 10 correct.'

raw_input('press enter to exit')



Thanks for all the people who helped me:)

Peace
Kelvin

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


Re: n-body problem at shootout.alioth.debian.org

2006-10-07 Thread bearophileHUGS
Paddy:
> You might also put the outer loop calling function advance so many
> times, into the advance function:

Remember that the autors of the Shootout refuse some changes to the
code (like this one), to allow a fair comparison. The rules are strict.

I have improved the Psyco version:
http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=nbody&lang=all

If I find the time I'll try to speed up the Python version too
following some of the suggestions of this thread. Note that on that
site there are 4 different comparisons.

The interesting question is how the Lua JIT can be that fast, it's
often faster than Psyco:
http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=luajit&lang2=psyco

http://luajit.luaforge.net/

Bye,
bearophile

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


Re: problem with split

2006-10-07 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> I think I am very close the return line is tripping me up.  (this is
> the first list that I have tried to program in python)
> 
> return (s.group[1], s.group[2])
> 
> Traceback (most recent call last):
>   File "C:\Python24\Lib\site-packages\boa-constructor\test of
> snake\test_of_csoundroutines_list.py", line 5, in ?
> v = csoundroutines.csdInstrumentList('bay-at-night.csd')
>   File "C:\Python24\Lib\site-packages\boa-constructor\test of
> snake\csoundroutines.py", line 43, in csdInstrumentList
> return (s.group[1], s.group[2])
> TypeError: unsubscriptable object
> 

.group() is a *method of the patch object not a data attribute, so you 
have to *call* it, not treat it like a list or dict. Try something like

return (s.group(1), s.group(2))

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: extract certain values from file with re

2006-10-07 Thread Fabian Braennstroem
Hi to all,

thanks a lot! I am pretty sure your ideas help :-)



Greetings!
 Fabian

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


Re: How to execute a python script in .NET application

2006-10-07 Thread Gerard Flanagan

Chandra wrote:

> Hi,
>
> Is there a way to execute a python script(file) in ASP.NET application
> (programmatically)??
>
> Regards,
> Chandra


I thought IIS would prevent this, but the following works for me at
home (ASP.NET 1.1). A production setup may be a different matter.

using System.Diagnostics

public class WebForm1 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label Label1;

private void Page_Load(object sender, System.EventArgs e)
{
ProcessStartInfo startInfo;
Process process;
string directory = 
@"c:\python\python24\Lib\site-packages";
string script = "test.py";

startInfo = new ProcessStartInfo("python");
startInfo.WorkingDirectory = directory;
startInfo.Arguments = script;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;

process = new Process();
process.StartInfo = startInfo;
process.Start();

string s;
while ((s = process.StandardOutput.ReadLine()) != null)
{
Label1.Text += s;
} 
}
}

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


Re: Dumping the state of a deadlocked process

2006-10-07 Thread Ziga Seilnacht
[EMAIL PROTECTED] wrote:
> Hi all
>
> I'm currently having some issues with a process getting deadlocked. The
> problem is that the only way I can seem to find information about where
> it deadlocks is by making a wild guess, insert a pdb.set_trace() before
> this point, and then step until it locks up, hoping that I've guessed
> right.
>
> The frustrating part is that most of the time my guesses are wrong.
>
> It would be really nice if I could send the python process some signal
> which would cause it to print the current stacktrace and exit
> immediately. That way I would quickly be able to pinpoint where in the
> code the deadlock happens. Java has a somewhat similar feature where
> you can send a running VM process a SIGQUIT, to which it will respond
> by dumping all current threads and lots of other information on stdout.
>
> Is this possible somehow?

Check out the sys._current_frames() function, new in Python 2.5:
http://docs.python.org/lib/module-sys.html#l2h-5122

Hope this helps,
Ziga

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


Re: Python to use a non open source bug tracker?

2006-10-07 Thread Steve Holden
Giovanni Bajo wrote:
[...]
> 
> I understand your concerns, but I have to remember you that most bug reports
> submitted by users go totally ignored for several years, or, better, forever. 
> I
> do not have a correct statistic for this, but I'm confident that at least 80%
> of the RFE or patches filed every week is totally ignored, and probably at
> least 50% of the bugs too. I think there is a much bigger problem here wrt 
> QOS.
> 
> So, you might prefer 6-10 people to activate a new tracker account faster than
> light. I'd rather have 3-days delay in administrative issues because our 
> single
> administrator is sleeping or whatever, and then have 2-3 people doing regular
> bug processing.

... and if wishes were horses then beggars would ride.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: HOST - Assembla Inc. Breakout - Copyright Violation by Mr. AndySingleton

2006-10-07 Thread Steve Holden
Hendrik van Rooyen wrote:
> "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> 
> 8<---
> 
>>... - I don't wanna get 
>>into the details of my underwear :P
>>
>>Diez
> 
> 
> Why not? - what are you hiding?
> 
:)

We *especially* don't want to get into the details of what's *under* his 
underwear.

speaking-purely-for-myself-ly y'rs  - steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Scientific computing and data visualization.

2006-10-07 Thread Fabian Braennstroem
Hi,

* Carl Friedrich Bolz <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>> A commonly used data analysis framework is root (http://root.cern.ch).
>> It offers a object oriented C++ framework with all kind of things one
>> needs for plotting and data visualization. It comes along with PyRoot,
>> an interface making the root objects available to Python.
>> Take a look at the root manual for examples, it also contains a section
>> describing the use of PyRoot.
>
> I can definitively second that. ROOT is a bit hard to learn but very,
> very powerful and PyRoot is really a pleasure to work with.

It sounds interesting. Right now, I use matplotlib for
2D plotting and vtk for 3D. Do you have any experience and
can give some recommendations?

Greetings!
 Fabian

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


Re: n-body problem at shootout.alioth.debian.org

2006-10-07 Thread Peter Maas
[EMAIL PROTECTED] wrote:
>> You might also put the outer loop calling function advance so many
>> times, into the advance function:
> 
> Remember that the autors of the Shootout refuse some changes to the
> code (like this one), to allow a fair comparison. The rules are strict.

I'm only aware of the rule that the language has to be used "as-is", e.g.
you must not encapsulate time-critical parts in a C extension and announce
the result as "fast Python".

To put the outer loop inside a function is a degree of freedom which is
available in every language so should be allowed in a shoot-out. The global
arrays in the Perl program are on the same track.

-- 
Regards/Gruesse,

Peter Maas, Aachen
E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: News on versions modules for Python-2.5?

2006-10-07 Thread John J. Lee
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Méta-MCI wrote:
> > And who can confirm that these modules are independent of Python version?
> >
> > ReportLab
> 
> I can't confirm it's 100% independent, but I have been using reportlab
> on Windows and Linux with Python 2.5.

If anything in the ReportLab open source toolkit doesn't work with
Python 2.5, it's a bug.  (and as I say, I don't remember any bug
reports about problems using it with Python 2.5 yet)

I'm not really sure what "100% independent of Python version" means,
but guessing that in practice, what the OP was interested in was
"supported under, and works fine with, Pythons 2.4 and 2.5", and the
answer to that is a definite "yes" :-)


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

Re: Names changed to protect the guilty

2006-10-07 Thread Neil Cerutti
On 2006-10-07, MonkeeSage <[EMAIL PROTECTED]> wrote:
>
> On Oct 6, 8:34 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> And in the original case, I'd agree that "if X.has_key():" is
>> quite clear, already yielding a boolian value, and so doesn't
>> need to be tested for if it's False. But I wouldn't like to
>> test for an empty list or for None implicitly.
>
> I agree that predicates are explicit in themselves, if they are
> named intuitively like "has_key". I assumed that the OP was
> upset about "is False" not that an explicit check was done on a
> predicate method.

And that's something that I'd never have written, and wouldn't
have recognized as a bug until this thread. I can hear the gears
clicking in there now. Thanks to you and other that explained
this bug properly.

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


Re: Names changed to protect the guilty

2006-10-07 Thread Steven D'Aprano
On Fri, 06 Oct 2006 18:29:34 -0700, John Machin wrote:

> 
> MonkeeSage wrote:
>> On Oct 6, 8:02 pm, "MonkeeSage" <[EMAIL PROTECTED]> wrote:
>> > it is clearer to you to make the condition explicit ("blah not False"),
>>
>> "blah not False" -> "blah is False"
> 
> Whichever way your team wants to interpret it, d00d.
> 
> Please consider whether you should be writing "(blah is False) is
> True", that would be more explicit.

Puh-lease! Get it right!

It should be "((blah is False) is True) is True".



-- 
Steve.

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


Re: Names changed to protect the guilty

2006-10-07 Thread John Machin

Steven D'Aprano wrote:
> On Fri, 06 Oct 2006 18:29:34 -0700, John Machin wrote:
>
> >
> > MonkeeSage wrote:
> >> On Oct 6, 8:02 pm, "MonkeeSage" <[EMAIL PROTECTED]> wrote:
> >> > it is clearer to you to make the condition explicit ("blah not False"),
> >>
> >> "blah not False" -> "blah is False"
> >
> > Whichever way your team wants to interpret it, d00d.
> >
> > Please consider whether you should be writing "(blah is False) is
> > True", that would be more explicit.
>
> Puh-lease! Get it right!
>
> It should be "((blah is False) is True) is True".
>

Yes, but it stops after one more iteration. "What I tell you three
times is true" -- the Bellman, "The Hunting of the Snark", by Lewis
Carroll.

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


Re: error handling in user input: is this natural or just laborious

2006-10-07 Thread Steven D'Aprano
On Fri, 06 Oct 2006 17:19:01 -0700, sam wrote:

> gosh, a lot of work to get some input. i must be missing something,
> though this is a lot better than what i had before...

Welcome to the real world of programming. Writing your algorithms is,
generally, the easy part. Handling data input and output and the user
interface is often much more work.

I would suggest you factor out logically separate parts of your code
something like this:

done = False
good_input = False
while not done:
while not good_input:
a, b, c, d = get_user_input() # or whatever values you need
good_input = validate_user_input(a, b, c, d)
done = do_something_with_input(a, b, c, d)


See how easy it is to understand the high level logic of the code,
without getting bogged down in gory details? Now all you have to do is
write functions get_user_input() etc.

E.g. I might write something like this:

class RangeError(ValueError):
pass

def validate_user_input(a, b, c, d):
# assumes all of a, b, c, d are percentages
data = {'a': a, 'b':b, 'c': c, 'd': d}
for name, value in data:
try:
float(value)
if not (0.0 <= value <= 100.0):
raise RangeError
except RangeError:  # this must come first
 print name, "is out of range."
 return False
except ValueError:
 print name, "is not a percentage."
 return False
return True

-- 
Steve.

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


Re: Filter class

2006-10-07 Thread TheSaint
On 17:02, sabato 30 settembre 2006 TheSaint wrote:

> Hello NG,
> 
> Curious to know whether exists a filter class.
> I'm doing some rough mail filtering on my own criteria, but I'm very new on
> programming and I like to find some clue on passing a config file of rules
> which will be regex by Python.
> 
> TIA

I went to study some long and I developed a small program, herebelow.
But I'd appreciate if it vill come some suggestion for a pythonic cosmetic
fashion :)

Thank to everybody.

+
#! /usr/bin/env python
 Test the mailserver to clean unwanted mail"""

from poplib import POP3
import ConfigParser , sys , os , re
MULTILINE = 8

def call_POP(args):
if len(args) != 4: return
for cnt in range(len(args)):
if args[cnt] =='' or args[cnt] == None : return
a = POP3(args[0])
a.user(args[1])
print 'Server %s reply %s' %(args[0], a.pass_(args[2]))
(numMsgs, totalSize) = a.stat()
msg9 = ''
for i in range(1, numMsgs +1):
for hdrline in a.top(i,0)[1]:
for argmn in args[3]:
if not re.search(argmn[1], hdrline): continue
lsenty = 0
if argmn[0].startswith('a') and not argmn[0].startswith('d'):
continue
#list only the messages that aren't matching
if lsenty == i: continue # no duplicate messages
fwrt.write('Msg No %03d\nTEST  "%s" \n %s\n' \
  %(i,argmn[1], hdrline))
lsenty = i
fwrt.write('\n\n')
a.quit()

def get_mydir(file):
if os.name == 'posix':
adir = os.path.split(file)[0]
afil = os.path.split(file)[1]
if adir == '': adir = os.getcwd()
for pth in ('~/', '$HOME/'):
if pth in adir: adir = os.environ['HOME']
file = adir + '/' + afil
if not os.path.exists(file):
print 'Configuration file not found'
return 0
return file

if len(sys.argv) != 3:
print 'Incorrect  Number of arguments!'
sys.exit(0)
infil = get_mydir(sys.argv[1])
if not infil: sys.exit(0)
opnfil = sys.argv[2]
fwrt = open(opnfil,'w')

cfg = ConfigParser.ConfigParser()
cfg.read(infil)
infil = ''
fltr = 'Filters'
if  fltr in cfg.sections():
infil = cfg.items(fltr)
for section in cfg.sections():
if section.lower() in ('setting', 'filters'): continue
adir = 0
afil = {}
for pth in ('server', 'user', 'pass'):
afil[adir] = cfg.get(section, pth)
adir += 1
afil[adir] = infil
print 'Now trying to connect to ' + section
call_POP(afil)
fwrt.close()

+

Also the config File enclosed (some detail is obscured for obvious purposes).

==
[Jaring]
PASS = xxx
USER = w
SERVER = e

[Vodafone]
SERVER = popmm
USER = godddllr
PASS = rrettt

[TMnet]
SERVER = fgotee
USER = gggrrdfng
PASS = rrro

[YahooIt]
SERVER = ffpogakfbmb
USER = fglkfrtrtthajl
PASS = fg8uarewaehueh

[Setting]
#All section is not impemented. It's supposed to give either a filepath or
# none
LOG = no
# obviously how much we want to know about the process
VERBOSE = 3
# Some case we won't need errors from python and let the matter die as is
SWALLOW_ERR = yes
# some implementation of threading to have the way to log on
# all the server in parallel
PARALLEL = yes

[Filters]
# A = Allow (anything which starts with "a" is filtered as allowed)
# to keep as good.

A01 = ^From: .*\.cz
A02 = ^(To|Cc): .*w
A03 = ^(To|Cc): .*godddllr@
A04 = ^(To|Cc): .*fglkfrtrtthajl@
A05 = ^(To|Cc): .*122951205u@
A06 = ^From: .*\.my

# D = Deny (anything which starts with "a" is filtered as denied) and will
# fill the list for deletion.

D01 = ^From: .*\.com\.my
D02 = \*\*\*SPAM\*\*\*
==

Let me say that is an experimental program for learning purpose, yet. More
things should be implemented like :
1 Real deletion for those email listed in the report file.
2 a single group pattern for the regex search
3 Logging errors and all functions mentioned in the "Setting" section.
4 last but not least a GUI.

The idea was born when i was looking for the "mailfilter" package for Arch
Linux. Actually has been retired. Then I tought " It would be good if a
platform indipendent program will do the same job or a bit more".

Testing on win32 platform is good help.
So, if somebody like to join, very welcome for all of the possible chances,
please try to contact me at _fulvio AT tm DOT net DOT my_.

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


Kde Taskbar

2006-10-07 Thread DarkBlue
Hello

In linux I use kmail as my email client under KDE,
if a message comes in the Kontact button in the
taskbar changes to blue.
How can I have the same behaviour in a python app ?

I have a python script which runs nicely under linux
now every so often I want to be notified by some event,
in this case that a record has been added to a database
and I want to have the application button in the taskbar
to change color

Thanks for any pointers , I am out of my depth here

Db


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


Re: Names changed to protect the guilty

2006-10-07 Thread John Roth

Aahz wrote:
> The following line of lightly munged code was found in a publicly
> available Python library...
>
> if schema.elements.has_key(key) is False:
>
> Sorry, just had to vent.
> --
> Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

Uh, guys. IMO, the clearest way of writing this is:

if key not in schema.elements:
whatever...

Unless, of course, your code has to run in a
Python release earlier than 2.2. But then you
wouldn't be testing for the False object anyway.



John Roth

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


Re: error handling in user input: is this natural or just laborious

2006-10-07 Thread bruno de chez modulix en face

sam a écrit :

(snip)
> i'm still in the early stages, and am trying to code something simple
> and interactive to get the percentages of the portfolio in the five
> different investment categories. i thought i'd get in with the error
> handling early so if someone types in something wrong (like a word), or
> the numbers don't add up to 100%, the error would be caught immediately
> and the user sent back to the start of the loop.
(snip)

You may want to have a look at the formencode package. While mostly
used in web apps, it's perfectly usable for all kind of
python<->outside world data conversion/validation.

HTH

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


curses problem reading cursor keys

2006-10-07 Thread Simon Morgan
Hi,

I'm having trouble with the following code. The problem is that the value
read by getch() when I hit the up or down keys doesn't match curses.KEY_UP
or curses.KEY_DOWN respectively. Other keys, such as 'z' in my example
code, work fine.

I only seem to have this problem when dealing with newly created windows
and not with the standard/default/root one created by curses.wrapper() and
passed to main().

I'd also appreciate any pointers to good tutorials on curses, I've read
the one by awk and esr but found it rather brief and lacking in detail.

Thanks.

import curses

def main(scr):
status = curses.newwin(1, curses.COLS, 0, 0) status.bkgd('0')
status.refresh()

list = curses.newwin(curses.LINES, curses.COLS, 1, 0) list.bkgd('X')
list.refresh()

y = 0
while True:
c = list.getch()
if c in (curses.KEY_UP, curses.KEY_DOWN, ord('z')):
list.addstr("Match!")
elif c == ord('q'):
break

curses.wrapper(main)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Names changed to protect the guilty

2006-10-07 Thread John Machin

John Roth wrote:
> Aahz wrote:
> > The following line of lightly munged code was found in a publicly
> > available Python library...
> >
> > if schema.elements.has_key(key) is False:
> >
> > Sorry, just had to vent.
> > --
> > Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/
>
> Uh, guys. IMO, the clearest way of writing this is:
>
> if key not in schema.elements:
> whatever...
>

Uh, guys, what? You are the 3rd to make that point. Therefore it must
be true.

> Unless, of course, your code has to run in a
> Python release earlier than 2.2. But then you
> wouldn't be testing for the False object anyway.
> 
> 
> 
> John Roth

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


Re: Python to use a non open source bug tracker?

2006-10-07 Thread Robert Hicks

Giovanni Bajo wrote:
> Paul Rubin wrote:
>
> >> You fail to recognize that Python is *already* using a non-free
> >> software for bug tracking, as do thousands of other projects.
> >
> > I don't think that reflects an explicit decision.  SF started out as
> > free software and the software became nonfree after people were
> > already using it.
>
> Moreover, this looked like a very good chance to have this nuisance sorted 
> out.
> Too bad some people don't value free software enough.

Nuisance? I never heard a peep from anyone until this thread on c.l.p.!
This is just a rediculous thing to be arguing over, really it is.

Robert

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


Re: Python to use a non open source bug tracker?

2006-10-07 Thread Robert Hicks

Steve Holden wrote:

> Perhaps what I *should* have written was "Sadly *many* people spend too
> much time bitching and moaning about those that roll their sleeves up,
> and not enough rolling their own sleeves up and pitching in".
>
> Sniping from the sidelines is far easier than hard work towards a goal.
>

Hey, that is how this whole thread started! Good observation.

Robert

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


Re: Python to use a non open source bug tracker?

2006-10-07 Thread Robert Hicks

Giovanni Bajo wrote:

> You might also be understimating how negative could be the reaction from the
> open-source community to such a move.
> --
> Giovanni Bajo

That is simply rediculous. Step away from the kool-aid.

Robert

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


Re: Kde Taskbar

2006-10-07 Thread Diez B. Roggisch
DarkBlue schrieb:
> Hello
> 
> In linux I use kmail as my email client under KDE,
> if a message comes in the Kontact button in the
> taskbar changes to blue.
> How can I have the same behaviour in a python app ?
> 
> I have a python script which runs nicely under linux
> now every so often I want to be notified by some event,
> in this case that a record has been added to a database
> and I want to have the application button in the taskbar
> to change color
> 
> Thanks for any pointers , I am out of my depth here

pykde afaik supports systray-iconified apps. And you could use the 
dcop-mechanisms that are available as command line tools as well I 
guess, and invoke knotify.

Hope this gives you some pointers - I'm currently on my mac so I can't 
provide an actual example.

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


Re: building strings from variables

2006-10-07 Thread Gal Diskin
Matthew Warren wrote:
> > -Original Message-
> > From:
> > [EMAIL PROTECTED]
> > [mailto:[EMAIL PROTECTED]
> > rg] On Behalf Of Gal Diskin
> > Sent: 05 October 2006 16:01
> > To: [email protected]
> > Subject: building strings from variables
> >
> > Following a discussion with an associate at work about various ways to
> > build strings from variables in python, I'd like to hear your opinions
> > and preferred methods. The methods we discussed are:
> > 1.  some_string = "cd %s ; %s  %d %s %s" % ( working_dir, ssh_cmd,
> > some_count, some_param1, some_param2)
> >
> > 2. import string
> > template = string.Template("cd $dir ; $cmd $count $param1
> > $param2")
> > some_string = template.substitute(dict(dir=working_dir,
> >
> > cmd=ssh_cmd,
> >
> > count=some_count,
> >
> > pararm1=some_param1,
> >
> > param2=some_param2))
> > here you can use a couple of nice tricks by using class.__dict__ and
> > globals() \ locals() dictionaries.
> >
> > 3. some_string = "cd "+working_dir+" ; "+ssh_cmd+ "
> > "+str(some_count)+" "+some_param1+" "+some_param2
> > (all these are supposed to produce the same strings)
> >
> > Which methods do you know of \ prefer \ think is better because...?
> > I will appreciate any opinions about the matter.
>
> :D
>
> I think, it would depend really on what your aims are (readable code,
> fast string generation...), and how the vars you want to build the
> string from are respresented in your code (is it natural to use a dict
> etc..)
>
> I kicked off a conversation similar to this earlier today, and that was
> my conclusion after helpful debate & advice.
>
> Matt.
>
>
> This email is confidential and may be privileged. If you are not the intended 
> recipient please notify the sender immediately and delete the email from your 
> computer.
>
> You should not copy the email, use it for any purpose or disclose its 
> contents to any other person.
> Please note that any views or opinions presented in this email may be 
> personal to the author and do not necessarily represent the views or opinions 
> of Digica.
> It is the responsibility of the recipient to check this email for the 
> presence of viruses. Digica accepts no liability for any damage caused by any 
> virus transmitted by this email.
>
> UK: Phoenix House, Colliers Way, Nottingham, NG8 6AT UK
> Reception Tel: + 44 (0) 115 977 1177
> Support Centre: 0845 607 7070
> Fax: + 44 (0) 115 977 7000
> http://www.digica.com
>
> SOUTH AFRICA: Building 3, Parc du Cap, Mispel Road, Bellville, 7535, South 
> Africa
> Tel: + 27 (0) 21 957 4900
> Fax: + 27 (0) 21 948 3135
> http://www.digica.com

Matt,
Thanks for replying. I tried looking up your discussion and I'm unsure
if I found the right post. Would you mind linking to it?

--
Gal Diskin
[EMAIL PROTECTED]
[EMAIL PROTECTED]
Work: +972-4-865-1637
Cell:   +972-54-7594166

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


Re: building strings from variables

2006-10-07 Thread Gal Diskin
First of all - thanks for all the replies. (Sorry for my slowness in
answering, but I wrote this message from work, just before leaving for
the weekend.)

I found a couple of posts that might be of interest:
Regarding speed I found a similar discussion in this newsgroup with
interesting results:
http://groups.google.com/group/comp.lang.python/browse_frm/thread/86aa0dd9dc0ed9cd/502a252f2c5ed778
Wesley, you might be interested to find that join is not necessarily
faster according to this thread. Jordan you might also be interested to
see their benchmarking.
The following post may also be of interest:
http://groups.google.com/group/comp.lang.python/msg/5ca4321e1d493fe9
(I haven't found the time to check this one myself so it comes with
limited warranty)

Regarding readability and "better" code my preferred methods are the 2
methods I haven't mentioned introduced by Rainy (%(varname)s ..." %
globals()) and by Scott David Daniels (' '.join[...]). Thanks, I
already knew join, but failed to include it for some reason but I
wasn't aware you could use dictionaries like this as well.

Thanks Jordan for making the effort to do the benchmarking. I think I
got similar results on several machines - according to my personal
benchmarking (based on short strings, and therefore relevant only to
such), the fastest method is "%s %d %s" % (p1, p2, p3) . However, all
other methods get close results (i.e. not above 1.5x runtime) except
for template.replace which is much slower by rate of about 15x. When it
comes to choosing between using template.replace or "%(varname)s ..." %
globals() my preference is for the latter without a doubt.

--
Gal Diskin
[EMAIL PROTECTED]
[EMAIL PROTECTED]
Work: +972-4-865-1637
Cell:   +972-54-7594166

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


Re: Python to use a non open source bug tracker?

2006-10-07 Thread James Graham
Steve Holden wrote:
> Giovanni Bajo wrote:
> [...]
>>
>> I understand your concerns, but I have to remember you that most bug 
>> reports
>> submitted by users go totally ignored for several years, or, better, 
>> forever. I
>> do not have a correct statistic for this, but I'm confident that at 
>> least 80%
>> of the RFE or patches filed every week is totally ignored, and 
>> probably at
>> least 50% of the bugs too. I think there is a much bigger problem here 
>> wrt QOS.
>>
>> So, you might prefer 6-10 people to activate a new tracker account 
>> faster than
>> light. I'd rather have 3-days delay in administrative issues because 
>> our single
>> administrator is sleeping or whatever, and then have 2-3 people doing 
>> regular
>> bug processing.
> 
> ... and if wishes were horses then beggars would ride.

FWIW, this situation (few administrators compared to the number of 
community members involved in triage) is basically the situation for the 
Mozilla project's bug database (which is a bugzilla install, of course), 
This was the case even before the corporation was founded so it's not a 
funding issue. My impression has always been that people who kept the 
bug database clean (moving things to the right component, hunting out 
duplicates, verifying fixes, and so on) are seen as vital and accorded 
appropriate respect by the Mozilla development community.

I don't think I have any specific point to make except, perhaps, that by 
making the right noises, it is quite possible to get a useful number of 
people helping with bug processing work.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Names changed to protect the guilty

2006-10-07 Thread Aahz
In article <[EMAIL PROTECTED]>,
John Machin <[EMAIL PROTECTED]> wrote:
>Aahz wrote:
>> In article <[EMAIL PROTECTED]>,
>> MonkeeSage <[EMAIL PROTECTED]> wrote:
>>>On Oct 6, 6:27 pm, [EMAIL PROTECTED] (Aahz) wrote:

 The following line of lightly munged code was found in a publicly
 available Python library...
>>>
>>>Yes, this violates the Holy, Inspired, Infallible Style Guide (pbuh),
>>>which was written by the very finger of God when the world was still in
>>>chaotic darkness.
>>
>> Did you actually analyze the line of code?  Particularly WRT the way it
>> operates in different versions of Python?
>
>A comment on the "style" issue, before we get into the real WTF
>analysis: any function/method whose name begins with "has" or "is"
>returns an honest-to-goodness actual bool (or what passed for one in
>former times). IMHO, any comparison with [] being regarded as false and
>[0] being regarded as true is irrelevant, and writing "has_something()
>== False" or "has_something() is False" is utterly ludicrous.

Exactly.  Another way of putting this: it's so wrong, it isn't even
wrong.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you don't know what your program is supposed to do, you'd better not
start writing it."  --Dijkstra
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Kde Taskbar

2006-10-07 Thread David Boddie
On Saturday 07 October 2006 14:59, DarkBlue wrote:

> In linux I use kmail as my email client under KDE,
> if a message comes in the Kontact button in the
> taskbar changes to blue.
> How can I have the same behaviour in a python app ?

You need to activate the window associated with the application.

> I have a python script which runs nicely under linux
> now every so often I want to be notified by some event,
> in this case that a record has been added to a database
> and I want to have the application button in the taskbar
> to change color

If the script is running in a console, you'll need to activate
the window containing the console. I tried doing this by accessing
konsole's DCOP interface, but couldn't find a suitable method to
call. If you know which konsole your script is running in, you might
find that you can raise the window with

  dcop konsole- konsole-mainwindow#1 raise

where  is the process ID of the konsole. This might have the
effect of causing its taskbar button to change color. You can find
information about the konsole from the KONSOLE_* environment
variables.

It would be good if konsole had a DCOP method that enabled you to
activate its window, or if kicker exported an interface for the
taskbar, or even if kwin had some way of letting you activate a
window given its ID. Unfortunately, I couldn't find methods for
any of these, so you would have to think about using PyKDE to get
at this functionality.

It would be good if someone could prove me wrong on any of this. ;-)

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


Re: Kde Taskbar

2006-10-07 Thread DarkBlue
Diez B. Roggisch wrote:

> 
> pykde afaik supports systray-iconified apps. And you could use the
> dcop-mechanisms that are available as command line tools as well I
> guess, and invoke knotify.
> 
> Hope this gives you some pointers - I'm currently on my mac so I can't
> provide an actual example.
> 
> Diez
Thank you ,
a quick look at pykde tells me that 
this will need some research 

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


Re: Kde Taskbar

2006-10-07 Thread DarkBlue
David Boddie wrote:

> On Saturday 07 October 2006 14:59, DarkBlue wrote:
> 
>> In linux I use kmail as my email client under KDE,
>> if a message comes in the Kontact button in the
>> taskbar changes to blue.
>> How can I have the same behaviour in a python app ?
> 
> You need to activate the window associated with the application.
> 
>> I have a python script which runs nicely under linux
>> now every so often I want to be notified by some event,
>> in this case that a record has been added to a database
>> and I want to have the application button in the taskbar
>> to change color
> 
> If the script is running in a console, you'll need to activate
> the window containing the console. I tried doing this by accessing
> konsole's DCOP interface, but couldn't find a suitable method to
> call. If you know which konsole your script is running in, you might
> find that you can raise the window with
> 
>   dcop konsole- konsole-mainwindow#1 raise
> 
> where  is the process ID of the konsole. This might have the
> effect of causing its taskbar button to change color. You can find
> information about the konsole from the KONSOLE_* environment
> variables.
> 
> It would be good if konsole had a DCOP method that enabled you to
> activate its window, or if kicker exported an interface for the
> taskbar, or even if kwin had some way of letting you activate a
> window given its ID. Unfortunately, I couldn't find methods for
> any of these, so you would have to think about using PyKDE to get
> at this functionality.
> 
> It would be good if someone could prove me wrong on any of this. ;-)
> 
> David

My python app actually is a pythoncard app
which I hope will make things easier.

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


Help with first script please. files, directories, autocomplete

2006-10-07 Thread simonharrison
Hello everyone. Hopefully someone can point me in the right direction
here. I'm wanting to write a script to open microsoft word and adobe
pdf documents . Here is a little background:

At the company where I work (an inspection firm) all reports of
inspections are saved as word files. A particular file may contain many
reports named like this; 12345A-F.doc. This file contains six reports.
Most inspections also require a technique which is saved as a pdf. The
pdf filename is the identification of the part being inspected.

My command line script will work like this: The user is asked whether
they are searching for a technique or a report

> Find (c)ertificate or (t)echnique

if they press 'c' they are then asked to enter certificate number.
Using the code below, no enter is needed

import msvcrt
print "Find (t)echnique or (c)ertificate: "
ch = msvcrt.getch()
if ch == 't':
  print "Enter technique number: "
elif ch == 'c':
  print "Enter certificate number: "
else:
  print 'command not understood.'
raw_input()

Obviously I will need to wrap this into a function. What I need to know
how to do is save the two directories where the files are stored. if
'c' is selected I want to use that as the directory to search. same for
techniques. What is the best way to do this? I would also like to have
the text autocomplete after maybe three characters, is this possible?
Am I correct in thinking all files would have to be stored in a list
for this to work?

As you can tell I am new to programming. I don't want someone to write
this script for me, just give me some pointers to get going (maybe a
tutorial on the net). Unless someone really wants to write it of
course!

Many thanks and sorry for the long post.

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


Re: Help with first script please. files, directories, autocomplete

2006-10-07 Thread simonharrison
Forgot to mention I'm using python 2.5 on windows xp.

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


Re: Python to use a non open source bug tracker?

2006-10-07 Thread Giovanni Bajo
Steve Holden wrote:

>> I understand your concerns, but I have to remember you that most bug
>> reports submitted by users go totally ignored for several years, or,
>> better, forever. I do not have a correct statistic for this, but I'm
>> confident that at least 80% of the RFE or patches filed every week
>> is totally ignored, and probably at least 50% of the bugs too. I
>> think there is a much bigger problem here wrt QOS.
>>
>> So, you might prefer 6-10 people to activate a new tracker account
>> faster than light. I'd rather have 3-days delay in administrative
>> issues because our single administrator is sleeping or whatever, and
>> then have 2-3 people doing regular bug processing.
>
> ... and if wishes were horses then beggars would ride.

Are you ever going to try and make a point which is not "you are not entitled
to have opinions because you do not act"? Your sarcasm is getting annoying. And
since I'm not trolling nor flaming, I think I deserve a little bit more of
respect.
-- 
Giovanni Bajo


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


Re: Multiple calls to logging.config.fileConfig

2006-10-07 Thread Vinay Sajip
logging.config.fileConfig() does not do incremental configuration - it
replaces the existing configuration with the configuration in the file
passed to fileConfig. While this might not be too useful for your
current needs, the present behaviour is by design...fileConfig is meant
to choose between one of a number of configurations (e.g. development,
test, production) and not for incremental configuration.

Regards,

Vinay Sajip

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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread MonkeeSage


On Oct 7, 3:27 am, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> The meaning comes from the most common usage.

I wasn't suggesting that the "in" keyword have a different sematic for
sequence types. I was just saying that regarding the question whether
there is anything similar to "dict.has_key / k in dict" for lists, the
"in" keyword is not semantically analogous.

> Because it's not needed at all: valid sequence indexes are *exactly*
> range(len(seq)). This is the basic point of being a sequence: when
> indexes are not contiguous, in fact you have a mapping, not a sequence.

True. But valid dictionary keys are exactly d.keys(). The has_key
method is just sugar.

> Sometimes, maybe... But since you can write it efficientely in a few
> lines when needed, I don't see the need to put it into the core language.

Couldn't the same be said for dictionaries? I could write for
sequences:

if index < len(seq) and seq[index]: ...

But I could also write for dictionaries:

if key in dic.keys() and dic[key]: ...

I just wonder why the syntactic sugar was added for dicts, but not for
sequence types.

Regards,
Jordan

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


Re: Is there an alternative to os.walk?

2006-10-07 Thread Bruce
waylan wrote:
> Bruce wrote:
> > Hi all,
> > I have a question about traversing file systems, and could use some
> > help. Because of directories with many files in them, os.walk appears
> > to be rather slow. I`m thinking there is a potential for speed-up since
> > I don`t need os.walk to report filenames of all the files in every
> > directory it visits. Is there some clever way to use os.walk or another
> > tool that would provide functionality like os.walk except for the
> > listing of the filenames?
>
> You might want to check out the path module [1] (not os.path). The
> following is from the docs:
>
> > The method path.walk() returns an iterator which steps recursively
> > through a whole directory tree. path.walkdirs() and path.walkfiles()
> > are the same, but they yield only the directories and only the files,
> > respectively.
>
> Oh, and you can thank Paul Bissex for pointing me to path [2].
>

> [1]: http://www.jorendorff.com/articles/python/path/
> [2]: http://e-scribe.com/news/289

A little late but.. thanks for the replies, was very useful. Here`s
what I do in this case:

def search(a_dir):
   valid_dirs = []
   walker = os.walk(a_dir)
   while 1:
   try:
   dirpath, dirnames, filenames = walker.next()
   except StopIteration:
   break
   if dirtest(dirpath,filenames):
   valid_dirs.append(dirpath)
   return valid_dirs

def dirtest(a_dir):
   testfiles = ['a','b','c']
   for f in testfiles:
   if not os.path.exists(os.path.join(a_dir,f)):
   return 0
   return 1

I think you`re right - it`s not os.walk that makes this slow, it`s the
dirtest method that takes so much more time when there are many files
in a directory. Also, thanks for pointing me to the path module, was
interesting.

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


Re: Names changed to protect the guilty

2006-10-07 Thread Scott David Daniels
John Machin wrote:
> ...  any function/method whose name begins with "has" or "is"
> returns an honest-to-goodness actual bool (or what passed for
> one in former times).

True for 75% of the builtins:
>>> import __builtin__
>>> sorted(nm for nm in dir(__builtin__)
if nm.startswith('is') or nm.startswith('has'))
['hasattr', 'hash', 'isinstance', 'issubclass']
>>> [hasattr(type,'mro'), hash(123), isinstance(type, type),
 issubclass(type, type)]
[True, 123, True, True]

:-)

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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread Fredrik Lundh
MonkeeSage wrote:

> True. But valid dictionary keys are exactly d.keys(). The has_key
> method is just sugar.

for what?  are you sure you're using "sugar" as it is usually used when 
talking about computer languages?



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


Re: Python to use a non open source bug tracker?

2006-10-07 Thread Tim Peters
[Giovanni Bajo]
> I understand your concerns, but I have to remember you that most bug reports
> submitted by users go totally ignored for several years, or, better, forever. 
> I
> do not have a correct statistic for this,

Indeed you do not.

> but I'm confident that at least 80% of the RFE or patches filed every week
> is totally ignored, and probably at least 50% of the bugs too.

None are /totally ignored/ -- indeed, at least I see every one as it
comes in.  You might want to change your claim to that no work
obviously visible to you is done on them.  That would be better.  But,
in fact, most bugs and patches are eventually closed, and many that
stay open involve such obscure platform-dependent mysteries that
nobody with sufficient platform expertise to resolve them appears to
exist.  For example, if you'd prefer, I'll assign all bugs and patches
involving threads on HP-UX to you from now on ;-)

These are the actual stats as of a few minutes ago:

Bugs:  938 open of 7169 total ~= 87% closed
Patches:  429 open of 3846 total ~= 89% closed
Feature Requests:  240 open of 479 total ~= 50% closed

> I think there is a much bigger problem here wrt QOS.

Well, you're confident that 80% of patches are ignored.  In reality,
89% of all patches ever submitted have been pursued to final
resolution.  Call me a stickler for detail, but something just doesn't
jibe there to my eyes ;-)

There's an easy way to improve these percentages dramatically,
although they're not bad as-is:  run thru them and close every one
that isn't entirely clear.  For example, reject every feature request,
close every patch that changes visible behavior not /clearly/ fixing a
bona fide bug, and close every "bug report" that's really a feature
request or random "but Perl/Ruby/PHP doesn't do it this way" complaint
in disguise.

The Python developers tend to keep a report open if there's a scant
non-zero chance that somebody, someday, might appear who's motivated
enough to make something of it.  If the goal was instead to make the
percentages "look good", they could easily and justifiably be
dramatically "improved" before today ends.

For example, the oldest patch open today is a speculative
implementation of rational numbers for Python.  This is really a
feature request in disguise, and has very little chance-- but not /no/
chance --of ever being accepted.  The oldest bug open today is from 6
years ago, and looks like an easy-to-answer /question/ about the
semantics of regular expressions in Python 1.6.  I could take time to
close that one now, but is that a /good/  use of time?  Yes, but, at
the moment, even finishing this reply seems to be a /better/ use of my
time -- and after that, I'm going to get something to eat ;-)

Note that I don't mean to claim that turnaround time on bugs and
patches is ideal.  To the contrary, if it's /my/ bug or patch I'm
looking at it, turnaround time sucks, and if you're looking at yours,
likewise for you.  That's what happens when there are thousands of
"you"s and a handful of "them"s, all of the latter volunteering "spare
time".

OTOH, turnaround time on Python bugs classified as critical is superb.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dumping the state of a deadlocked process

2006-10-07 Thread fumanchu
Dennis Lee Bieber wrote:
> On 6 Oct 2006 12:59:31 -0700, [EMAIL PROTECTED] declaimed the
> following in comp.lang.python:
>
> > I'm currently having some issues with a process getting deadlocked. The
> > problem is that the only way I can seem to find information about where
> > it deadlocks is by making a wild guess, insert a pdb.set_trace() before
> > this point, and then step until it locks up, hoping that I've guessed
> > right.
> >
>   I presume the process is using threads? If it is truly deadlocked,
> then you must have some mutual calls to lock objects somewhere... It
> would seem that rather than just randomly inserting debug statements you
> should surround each call to a lock with statements.
>
>   print "Locking xyz"
>   xyz.acquire()   #or whatever the syntax is
>   print "Locked xyz"
>
>
>
>   print "Releasing xyz"
>   xyz.release()
>   print "Released xyz"
>
>
>   You'd need something like that around any potentially blocking
> operation -- queue operations, subprocess operations, socket
> operations... Rather than print statements you may wish to implement it
> via the logging module.

If you don't mind a potentially large log file, use the pyconquer
module I maintain here: http://projects.amor.org/misc/wiki/PyConquer
which uses settrace to do the logging in a much more readable and
manageable way than printlining. Try an initial run using the default
settings to narrow down the culprit, and then a run with C events
turned on if the first run wasn't enough. It should help out even if
your program is not multi-threaded, but it realy shines with threads.
:)


Robert Brewer
System Architect
Amor Ministries
[EMAIL PROTECTED]

P.S. Oh, and ignore the times in the output for now; that's still work
in progress.

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


Re: error handling in user input: is this natural or just laborious

2006-10-07 Thread sam
a huge amount to think about there. special thanks to james for taking
the time to make such   detailed responses. the problem is that even
though nested loops and the like place a heavy analytical burden on the
programmer (i.e. me) as he tries to remember what does what,
conceptualizing a program as a collection of classes and functions tied
together with a minimal amount of code brings to bear what is, at the
moment, an even greater burden.

my gut feeling is that, over time (as james said was true in his own
case), and with practice, the relative weights of these two burdens
change so that the procedural approach becomes easier to adopt, and its
benefits of readability and maintainability easier to enjoy. fingers
crossed...

i will continue coding the monte carlo machine until it does what i
want in more or less clumsy fashion, and might put it up here if it
feels like it would be of interest.

thanks again,

sam

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


Re: curses problem reading cursor keys

2006-10-07 Thread Simon Morgan
On Sat, 07 Oct 2006 13:12:33 +, Simon Morgan wrote:

> import curses
> 
> def main(scr):
> status = curses.newwin(1, curses.COLS, 0, 0) status.bkgd('0')
> status.refresh()
> 
> list = curses.newwin(curses.LINES, curses.COLS, 1, 0) list.bkgd('X')
> list.refresh()

If I use scr.subwin() instead of curses.newwin()...

> y = 0
> while True:
> c = list.getch()

and scr.getch() instead of list.getch(), things seem to work. I'd still
really like to know what's going on though.

> if c in (curses.KEY_UP, curses.KEY_DOWN, ord('z')):
> list.addstr("Match!")
> elif c == ord('q'):
> break
> 
> curses.wrapper(main)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python to use a non open source bug tracker?

2006-10-07 Thread Aahz
In article <[EMAIL PROTECTED]>,
Giovanni Bajo <[EMAIL PROTECTED]> wrote:
>
>Are you ever going to try and make a point which is not "you are not
>entitled to have opinions because you do not act"? Your sarcasm is
>getting annoying. And since I'm not trolling nor flaming, I think I
>deserve a little bit more of respect.

IMO, regardless of whether you are trolling or flaming, you are certainly
being disrespectful.  Why should we treat you with any more respect than
you give others?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you don't know what your program is supposed to do, you'd better not
start writing it."  --Dijkstra
-- 
http://mail.python.org/mailman/listinfo/python-list


Job announcement Vienna&Graz Austria

2006-10-07 Thread le_wolk
Python and Java Developers for reseach project hired!
More information below...


Information Diffusion across Interactive Online Media
http://www.idiom.at/

Four full-time research positions are now available at Graz University
of
Technology and Vienna University of Economics and Business
Administration.
As of November 2006, we aim to hire four young researchers in the
following areas (Application deadline = October 15):

** Visualizing Semantic and Geographic Data
** Social Software and Content Management Systems
** Semantic Technologies and Ontology Engineering
** Software Development and Information Retrieval

Further details and the full text of the announcements (in German) are
available at http://www.idiom.at/.

Project Description

Recent advances in collaborative Web technology are governed by network
effects and harnessing collective intelligence through customer-self
service and algorithmic data management. As a result, information
spreads
rapidly across Web sites, blogs, Wiki applications, and direct
communication channels between members of online communities who
utilize
these services. The IDIOM (Information Diffusion across Interactive
Online
Media) project will support and investigate electronic interactivity by
means of a generic, service-oriented architecture. This architecture
will
include ontology-based tools to build and maintain contextualized
information spaces, a framework for analyzing content diffusion and
interaction patterns within these spaces, and interface technology
enabling users to switch between semantic and geospatial topologies.

--
Mag. Gerhard Wohlgenannt | [EMAIL PROTECTED]
Projekt AVALON/WU Wien, Aug. 2-6 | Tel: ++43 1 31336 5228
--

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


Re: Help with first script please. files, directories, autocomplete

2006-10-07 Thread Rainy

[EMAIL PROTECTED] wrote:
> Hello everyone. Hopefully someone can point me in the right direction
> here. I'm wanting to write a script to open microsoft word and adobe
> pdf documents . Here is a little background:
>
> At the company where I work (an inspection firm) all reports of
> inspections are saved as word files. A particular file may contain many
> reports named like this; 12345A-F.doc. This file contains six reports.
> Most inspections also require a technique which is saved as a pdf. The
> pdf filename is the identification of the part being inspected.
>
> My command line script will work like this: The user is asked whether
> they are searching for a technique or a report
>
> > Find (c)ertificate or (t)echnique
>
> if they press 'c' they are then asked to enter certificate number.
> Using the code below, no enter is needed
>
> import msvcrt
> print "Find (t)echnique or (c)ertificate: "
> ch = msvcrt.getch()
> if ch == 't':
>   print "Enter technique number: "
> elif ch == 'c':
>   print "Enter certificate number: "
> else:
>   print 'command not understood.'
> raw_input()
>
> Obviously I will need to wrap this into a function. What I need to know
> how to do is save the two directories where the files are stored. if
> 'c' is selected I want to use that as the directory to search. same for
> techniques. What is the best way to do this? I would also like to have
> the text autocomplete after maybe three characters, is this possible?
> Am I correct in thinking all files would have to be stored in a list
> for this to work?
>
> As you can tell I am new to programming. I don't want someone to write
> this script for me, just give me some pointers to get going (maybe a
> tutorial on the net). Unless someone really wants to write it of
> course!
>
> Many thanks and sorry for the long post.

You can store the dir name as a variable:

>>> d = 'c:\home'
>>> from os import *
>>> listdir(d)
['.Config.pm.swp', '.run.bat.swp', 'AHK scripts', 'Archive',
'Config.pm', 'Docs', 'Images', 'Links', 'Music', 'Projects', 'Python
programs', 'run.bat', 'Share', 'Torrent']

As you see files are already in a list if you use listdir function.

You can autocomplete by getting each character, running through the
list and comparing using startswith() function:

>>> l = listdir(d)
>>> m = [m for m in l if m.startswith('A')]
>>> m
['AHK scripts', 'Archive']

Then you can check how many matches you got. If you get one, print it
and ask for Enter to finalize the choice.

You might want to read tutorial on python.org. You also might want to
buy a python book, or read any number of other tutorials online if you
don't want to spend money right now. Your questions are kind of basic,
I don't want to discourage you but as you go along you will run into
many other things and it's not practical to ask every time and wait for
the answer (although people here are glad to help). 

 -Rainy

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


Re: curses problem reading cursor keys

2006-10-07 Thread Rainy

Simon Morgan wrote:
> On Sat, 07 Oct 2006 13:12:33 +, Simon Morgan wrote:
>
> > import curses
> >
> > def main(scr):
> > status = curses.newwin(1, curses.COLS, 0, 0) status.bkgd('0')
> > status.refresh()
> >
> > list = curses.newwin(curses.LINES, curses.COLS, 1, 0) list.bkgd('X')
> > list.refresh()
>
> If I use scr.subwin() instead of curses.newwin()...
>
> > y = 0
> > while True:
> > c = list.getch()
>
> and scr.getch() instead of list.getch(), things seem to work. I'd still
> really like to know what's going on though.
>
> > if c in (curses.KEY_UP, curses.KEY_DOWN, ord('z')):
> > list.addstr("Match!")
> > elif c == ord('q'):
> > break
> >
> > curses.wrapper(main)

I don't have a linux here now but I vaguely remember running into this.
I think what I did was just writing down what code you do get when
pressing down and up, etc, and using that code. By the way I looked
around back then and didn't find any thorough tutorials on curses,
either.

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


Re: How to execute a python script in .NET application

2006-10-07 Thread MC
Hi!

dotNET can use (call) COM-servers

In pywin, there are exemple of COM-server, in Python, who can run 
(on-the-fly) Python code.

This give a way for run Python's scripts from dotNET, Excel, Word, 
Internet-Explorer (HTA), C#, etc.  I have try all these things, with 
success.

-- 
@-salutations

Michel Claveau


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


Re: n-body problem at shootout.alioth.debian.org

2006-10-07 Thread Peter Maas
Giovanni Bajo wrote:
> Did you try using an old-style class instead of a new-style class?

The original program has an old style class, changing it to a new
style class increases run time by 25% (version is 2.4.3 btw).

-- 
Regards/Gruesse,

Peter Maas, Aachen
E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64')
-- 
http://mail.python.org/mailman/listinfo/python-list


Encoding and norwegian (non ASCII) characters.

2006-10-07 Thread joakim . hove
Hello,

I am having great problems writing norwegian characters æøå to file
from a python application. My (simplified) scenario is as follows:

1. I have a web form where the user can enter his name.

2. I use the cgi module module to get to the input from the user:

name = form["name"].value

3. The name is stored in a file

fileH = open(namefile , "a")
fileH.write("name:%s \n" % name)
fileH.close()

Now, this works very well indeed as long the users have 'ascii' names,
however when someone enters a name with one of the norwegian characters
æøå - it breaks at the write() statement.

   UnicodeDecodeError: 'ascii' codec can't decode byte 0x8f in position


Now - I understand that the ascii codec can't be used to decode the
particular characters, however my attempts of specifying an alternative
encoding have all failed.

I have tried variants along the line:

   fileH = codecs.open(namefile , "a" , "latin-1") / fileH =
open(namefile , "a")
   fileH.write(name)   /fileH.write(name.encode("latin-1"))

It seems *whatever* I do the Python interpreter fails to see my pledge
for an alternative encoding, and fails with the dreaded
UnicodeDecodeError.

Any tips on this would be *highly* appreciated.


Joakim

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


class print?

2006-10-07 Thread SpreadTooThin
Hi... Many python object can be printed simpy by saying:
print obj
what method(s) need to be implemented in my own classes such that print
dumps the object?

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


Re: class print?

2006-10-07 Thread Erik Max Francis
SpreadTooThin wrote:

> Hi... Many python object can be printed simpy by saying:
> print obj
> what method(s) need to be implemented in my own classes such that print
> dumps the object?

__str__

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   Can I walk with you / 'Till the day that my heart stops beating
-- India Arie
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: SimpleJSONRPCServer

2006-10-07 Thread aum
Hi,

I've built a module called SimpleJSONRPCServer, which is essentially the
same as the familiar python library module SimpleXMLRPCServer, except that
it uses the JSON-RPC protocol.

For those unfamiliar with JSON-RPC - see www.json-rpc.org - it's an
alternative to XML-RPC, offering most of its capabilities, but using far
less traffic and requiring less processing time on the server and client.

For more information, downloads and a live demo, visit:
http://www.freenet.org.nz/dojo/pyjson

If any Python honchos here want to raise a PEP for it, I'd support that
fully.

Cheers
aum


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


operator overloading + - / * = etc...

2006-10-07 Thread SpreadTooThin
Can these operators be overloaded?
If so.  How?

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


need some regular expression help

2006-10-07 Thread Chris
I need a pattern that  matches a string that has the same number of '('
as ')':
findall( compile('...'), '42^((2x+2)sin(x)) + (log(2)/log(5))' ) = [
'((2x+2)sin(x))', '(log(2)/log(5))' ]
Can anybody help me out?

Thanks for any help!

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


Re: n-body problem at shootout.alioth.debian.org

2006-10-07 Thread Peter Maas
Paul McGuire wrote:
> The advance method is the most fertile place for optimization, since it is 
> called approximately n(n-1)/2 times (where n=2E7).  I was able to trim about 
> 25% from the Python runtime with these changes:
[...]

My results:

Your changes: 18% runtime decrease
Your changes + objects->lists: 25% runtime decrease

The Python program is much closer to the Perl program then (~2250 vs 1900 sec)
but replacing the objects by lists is not worth the effort because the gain is
small and the Python program becomes less readable.

Taking arrays (from module array) instead of lists increases runtime by 19%!

If it weren't for the shootout I would of course take psyco and numpy.

-- 
Regards/Gruesse,

Peter Maas, Aachen
E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: SimpleJSONRPCServer

2006-10-07 Thread Sybren Stuvel
aum enlightened us with:
> I've built a module called SimpleJSONRPCServer, which is essentially
> the same as the familiar python library module SimpleXMLRPCServer,
> except that it uses the JSON-RPC protocol.

Thanks a lot! I've used XML-RPC on a low-speed device, and it was way
too slow.

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: operator overloading + - / * = etc...

2006-10-07 Thread Sybren Stuvel
SpreadTooThin enlightened us with:
> Can these operators be overloaded?

Yes.

> If so.  How?

Implement __add__, __sub__ etc. in the class that you want to be able
to add, subtract, etc.

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A critique of cgi.escape

2006-10-07 Thread Lawrence D'Oliveiro
Another useful function is this:

def JSString(Str) :
"""returns a JavaScript string literal that evaluates to Str. Note
I'm not worrying about non-ASCII characters for now."""
Result = []
for Ch in Str :
if Ch == "\\" :
Ch = ""
elif Ch == "\"" :
Ch = "\\\""
elif Ch == "\t" :
Ch = "\\t"
elif Ch == "\n" :
Ch = "\\n"
#end if
Result.append(Ch)
#end for
return "\"" + "".join(Result) + "\""
#end JSString

This can be used, for instance in

sys.stdout.write \
  (
"window.setTimeout(%s, 1000)\n"
%
JSString("alert(%s)" % JSString("Hi There!"))
  )

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


Re: operator overloading + - / * = etc...

2006-10-07 Thread Daniel Nogradi
> Can these operators be overloaded?
> If so.  How?
>

http://www.python.org/doc/ref/numeric-types.html

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


Reminder re Talk Proposals for PyCon 2007

2006-10-07 Thread Jeff Rush
October has arrived and the deadline for submitting a proposal to give a talk
at PyCon 2007 is October 31 (November 15 for tutorials).  While it is a PyCon
tradition to wait until the last minute to flood us with submissions, I would
like to encourage presenters to start a bit earlier this year.

We have a new talk (not tutorial) submissions system which lets you interact
with your proposal online, rather than a fire-and-forget
one-chance-to-get-it-right approach.  You'll need to create a user account at:

http://us.pycon.org/apps07/proposals/

Then you can post, revise and exchange a few comments with the proposal
reviewers, which can be useful to clarify your talk focus.

And it would be a great show of support, and relieve some stress of the
organizers, if those who are even considering giving a talk would create a
user account in the system.  You can still change your mind, but even a
skeletal proposal that you're pondering giving a talk about XYZ and you're
still working up your outline would be welcome.  It would help us in planning
topic coverage and whether we are reaching certain sectors of the Python
community.

PyCon is community-run and we need the involvement of everyone.  If you
didn't get the talks at previous PyCons you wanted, this is the
chance for you to make your wishes know.  If you can't give a talk, badger
(nicely) members of the relevant technical group to step forward.  Ask for a
talk in your forums.

We have a wiki page of topic idea at:

  http://us.pycon.org/TX2007/TalkIdeas

so add a link and create a subpage that contains the outline of your dream
talk, and then shop it around to find a speaker to give it. ;-)

Jeff Rush
PyCon 2007 Co-Chair
---
Python: Produce impressive results and have fun too!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: operator overloading + - / * = etc...

2006-10-07 Thread Tim Chase
>> Can these operators be overloaded?
> 
> Yes.

With the caveat of the "=" mentioned in the subject-line (being 
different from "==")...I haven't found any way to override 
assignment in the general case.  There might be some oddball way 
to do it via property() but AFAIK, this only applies to 
properties of objects, not top-level names/variables.  I'd love 
to know if there's some workaround for this though...

-tkc



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


Re: Encoding and norwegian (non ASCII) characters.

2006-10-07 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> Hello,
> 
> I am having great problems writing norwegian characters æøå to file
> from a python application. My (simplified) scenario is as follows:
> 
> 1. I have a web form where the user can enter his name.
> 
> 2. I use the cgi module module to get to the input from the user:
> 
> name = form["name"].value
> 
> 3. The name is stored in a file
> 
> fileH = open(namefile , "a")
> fileH.write("name:%s \n" % name)
> fileH.close()
> 
> Now, this works very well indeed as long the users have 'ascii' names,
> however when someone enters a name with one of the norwegian characters
> æøå - it breaks at the write() statement.
> 
>UnicodeDecodeError: 'ascii' codec can't decode byte 0x8f in position
> 
> 
> Now - I understand that the ascii codec can't be used to decode the
> particular characters, however my attempts of specifying an alternative
> encoding have all failed.
> 
> I have tried variants along the line:
> 
>fileH = codecs.open(namefile , "a" , "latin-1") / fileH =
> open(namefile , "a")
>fileH.write(name)   /fileH.write(name.encode("latin-1"))
> 
> It seems *whatever* I do the Python interpreter fails to see my pledge
> for an alternative encoding, and fails with the dreaded
> UnicodeDecodeError.
> 
> Any tips on this would be *highly* appreciated.

The approach with codecs.open() should succeed

>>> out = codecs.open("tmp.txt", "a", "latin1")
>>> out.write(u"æøå")
>>> out.write("abc")
>>> out.write("æøå")
Traceback (most recent call last):
  File "", line 1, in ?
  File "/usr/local/lib/python2.4/codecs.py", line 501, in write
return self.writer.write(data)
  File "/usr/local/lib/python2.4/codecs.py", line 178, in write
data, consumed = self.encode(object, self.errors)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)

provided that you write only unicode strings with characters in the range
unichr(0)...unichr(255) and normal strs in the range chr(0)...chr(127).

You have to decode non-ascii strs before feeding them to write() with the
appropriate encoding (that only you know)

>>> out.write(unicode("\xe6\xf8\xe5", "latin1"))

If there are unicode code points beyond unichr(255) you have to change the
encoding in codecs.open(), typically to UTF-8.

# raises UnicodeEncodeError
codecs.open("tmp.txt", "a", "latin1").write(u"\u1234") 

# works
codecs.open("tmp.txt", "a", "utf8").write(u"\u1234")

Peter

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

Re: operator overloading + - / * = etc...

2006-10-07 Thread Georg Brandl
Tim Chase wrote:
>>> Can these operators be overloaded?
>> 
>> Yes.
> 
> With the caveat of the "=" mentioned in the subject-line (being 
> different from "==")...I haven't found any way to override 
> assignment in the general case.  There might be some oddball way 
> to do it via property() but AFAIK, this only applies to 
> properties of objects, not top-level names/variables.  I'd love 
> to know if there's some workaround for this though...

In almost all cases, binding a name cannot be overridden.

There is a possibility to do that with globals, provided you do

exec code in globals_dict

where globals_dict is an instance of a subclass of dict that has a
customized __setitem__.

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


Re: need some regular expression help

2006-10-07 Thread Diez B. Roggisch

Chris wrote:
> I need a pattern that  matches a string that has the same number of '('
> as ')':
> findall( compile('...'), '42^((2x+2)sin(x)) + (log(2)/log(5))' ) = [
> '((2x+2)sin(x))', '(log(2)/log(5))' ]
> Can anybody help me out?

This is not possible with regular expressions - they can't "remember"
how many parens they already encountered.

You will need a real parser for this - pyparsing seems to be the most
popular choice today, I personally like spark. I'm sure you find an
example-grammar that will parse simple arithmetical expressions like
the one above.

Diez

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


Re: Making sure script only runs once instance at a time.

2006-10-07 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Tim
Williams wrote:

> On 29/09/06, Matthew Warren <[EMAIL PROTECTED]> wrote:
>> I have found that in real usage of other programs within the company that
>> use lockfiles, it sometimes causes a bit of troubleshooting time when it
>> stops working due to a stale lockfile.. This especially happens when the
>> program is killed, the lockfile remains and causes minor annoyance (to
>> somebody who knows that is, more annoyance to somebody who doesn't).
> 
> Then they were checking for the wrong thing :)  Chcking for a lock
> file's existance is prone to the above problem.

My script deals with this
.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: switching to numpy and failing, a user story

2006-10-07 Thread Fernando Perez
[EMAIL PROTECTED] wrote:

> After using numeric for almost ten years, I decided to attempt to
> switch a large codebase (python and C++) to using numpy. Here's are
> some comments about how that went.
> 
> - The code to automatically switch python stuff over just kind of
> works. But it was a 90% solution, I could do the rest by hand. Of
> course, the problem is that then the code is still using the old
> numeric API, so it's not a long term solution. Unfortunately, to switch
> to the numpy API one needs documentation, which is a problem; see
> below.

[ RNG issues, already addressed ] 

> - My extension modules just won't build because the new numpy stuff
> lives in a different location from where Numeric used to live. I
> probably could fix this, but without the documentation I can't figure
> out how to do that. I'd also need to figure out how to port my code to
> use the new numpy API instead of the compatibility layer, but I can't
> do that without docs either.

I have to call bull on this.  I happen to have the per-pay book, but I
recently converted a large codebase from Numeric to Numpy, and I actually
never had to open the book.  Travis has made sure that the
compatibility-related information is easy to find:

http://www.scipy.org/Converting_from_Numeric 

has most of what you need, and this page:

http://www.tramy.us/guidetoscipy.html

contains a link to the first two chapters FOR FREE.  A lot of what's needed
for a port is covered in there.

In addition, the C API is available here (as well as being obviously in the
source, which you have access to):

http://www.scipy.org/NumPyCapi

And the doc page has many more useful links:

http://www.scipy.org/Documentation

So yes, you have to buy the book.  Travis has sunk over a year of his time
into an absolutely herculean effort that provides working scientists with
tools that are better than anything money can buy (yes, I have access to
both Matlab and IDL, and you can't pay me enough to use them instead of
Python).  

And he has the gall to ask for some money for a 300 page book? How dare he,
when one can walk into any Barnes and Noble and just walk out of the store
with a cart full of books for free!

It's funny how I don't see anyone complaining about any of the Python books
sold here (or at any other publishing house):

http://www.oreilly.com/pub/topic/python

I recently was very happy to pay for the Twisted book, since I need Twisted
for a project and a well-organized book is a good complement to the
auto-generated documentation.


And finally, if you had porting problems, none were reported on any of the
numpy/scipy mailing lists (else you used a different name or email, since I
can't find traces of queries from you my gmail archive where I keep
everything posted on all the lists):

http://www.scipy.org/Mailing_Lists

Lots of people have been porting their codes recently, and inevitably some
have run into difficulties.  EVERY single time when they actually say
something on the list, Travis (and others as well) is very fast with
specific help on exactly how to solve the problems, or with bug fixes when
the problem happens to be a numpy bug discovered by the user.  But don't
take my word for it:

http://sourceforge.net/mailarchive/forum.php?thread_id=30703688&forum_id=4890

(and Francesc has found some really nasty things, given how pytables pushes
numpy far beyond where Numeric ever went, so this is not a light
compliment).

Look, I'm sure you had issues with your code, we all have.  But I want to
make sure that others don't take from your message the wrong impression
regarding numpy, its future, its quality as a scientific computing
platform, or Travis (I'd build the man a statue if I could :).  

The environment which is developing around Python for scientific computing
is nothing short of remarkable.  If you find issues in the process, ask for
help on the numpy/scipy lists and I'm sure you will receive some.  But
please refrain from spreading FUD.

Regards,

f

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


Re: operator overloading + - / * = etc...

2006-10-07 Thread Sybren Stuvel
Tim Chase enlightened us with:
> With the caveat of the "=" mentioned in the subject-line (being
> different from "==")...I haven't found any way to override
> assignment in the general case.

Why would you want to do that?

Sybren
-- 
Sybren Stüvel
Stüvel IT - http://www.stuvel.eu/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need some regular expression help

2006-10-07 Thread John Machin
Chris wrote:
> I need a pattern that  matches a string that has the same number of '('
> as ')':
> findall( compile('...'), '42^((2x+2)sin(x)) + (log(2)/log(5))' ) = [
> '((2x+2)sin(x))', '(log(2)/log(5))' ]
> Can anybody help me out?
>

No, there is so such pattern. You will have to code up a function.

Consider what your spec really is: '42^((2x+2)sin(x)) +
(log(2)/log(5))' has the same number of left and right parentheses; so
does the zero-length string; so does ') + (' -- perhaps you need to add
'and starts with a "("'

Consider what you are going to do with input like this:

print '(' + some_text + ')'

Maybe you need to do some lexical analysis and work at the level of
tokens rather than individual characters.

Which then raises the usual question: you have a perception that
regular expressions are the solution -- to what problem??

HTH,
John

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


Re: People's names (was Re: sqlite3 error)

2006-10-07 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Steve
Holden wrote:

> John Machin wrote:
>
> [lots of explanation about peculiarities of people's names]
>
> While I don't dispute any of this erudite display of esoteric
> nomenclature wisdom the fact remains that many (predominantly Western)
> databases do tend to use first and last name (in America often with the
> addition of a one- or two-character "middle initial" field).

Just because most Western designers of databases do it wrong doesn't mean
that a) you should do it wrong, or b) they will continue to do it wrong
into the future, as increasing numbers of those designers come from Asian
and other non-Western backgrounds.

> So, having distilled your knowledge to its essence could you please give
> me some prescriptive advice about what I *should* do? :-)

Has anyone come up with a proper universal table design for storing people's
names?

Certainly "first name" and "last name" are the wrong column names to use. I
think "family name" and "given names" would be a good start. For the
Icelanders, Somalians and the Muslims, their father's name goes in
the "family name" field, which makes sense because all their siblings (of
the same sex, at least) would have the same value in this field.

I wonder if we need another "middle" field for holding the "bin/binte" part
(could also hold, e.g. "Van" for those names that use this).

There would also need to be a flag field to indicate the canonical ordering
for writing out the full name: e.g. family-name-first, given-names-first.
Do we need something else for the Vietnamese case?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: operator overloading + - / * = etc...

2006-10-07 Thread Tim Chase
>> With the caveat of the "=" mentioned in the subject-line (being
>> different from "==")...I haven't found any way to override
>> assignment in the general case.
> 
> Why would you want to do that?

For the same reason one would use property() to create 
getter/setter functions for a particular variable--to intercept 
attempts to set a variable.  I'm not sure there's an elegant way 
to do it other than creating a custom container object with a 
getter/setter using property().

My purpose was just to note that the "=" assignment operator is 
distinct from the remainder of the operators that you correctly 
identified can be overridden with their associated __[operator]__ 
method.

-tkc




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


Painless way to do 3D visualization

2006-10-07 Thread Peter Beattie
Hey folks,

I need to do the following relatively simple 3D programming:

I want to convert data from four-item tuples into 3D co-ordinates in a
regular tetrahedron. Co-ordinates come in sequences of 10 to 20, and the
individual dots in the tetrahedron need to be connected into
discontinuous lines. A single tetrahedron should contain at least two,
possibly more, such lines. I would like to show certain similarities in
the sequences/lines, eg by changing color, thickness, or maybe attaching
indeces to certain points in a particular sequence.

I'd welcome suggestions as to what might be the most painless way to
achieve this in Python. So far, I've only tinkered a little with
VPython, but the lack of any decent documentation has proved to be a
major turn-off.

TIA!

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


Re: Painless way to do 3D visualization

2006-10-07 Thread faulkner
http://www.vpython.org/

Peter Beattie wrote:
> Hey folks,
>
> I need to do the following relatively simple 3D programming:
>
> I want to convert data from four-item tuples into 3D co-ordinates in a
> regular tetrahedron. Co-ordinates come in sequences of 10 to 20, and the
> individual dots in the tetrahedron need to be connected into
> discontinuous lines. A single tetrahedron should contain at least two,
> possibly more, such lines. I would like to show certain similarities in
> the sequences/lines, eg by changing color, thickness, or maybe attaching
> indeces to certain points in a particular sequence.
>
> I'd welcome suggestions as to what might be the most painless way to
> achieve this in Python. So far, I've only tinkered a little with
> VPython, but the lack of any decent documentation has proved to be a
> major turn-off.
> 
> TIA!
> 
> -- 
> Peter

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


Re: IDLE - Customizing output format

2006-10-07 Thread Ilias Lazaridis
Gabriel Genellina wrote:
> At Wednesday 27/9/2006 09:29, Ilias Lazaridis wrote:
>
> >import sys
> >def f(obj):
> > if obj:
> > print '::: ' + repr(obj)
> >sys.displayhook = f
>
> Have you tried that? You have to filter out None, not *any* False value.
>
> > > And notice that this replaces the output of *evaluated* expressions,
> > > not any print statement executed inside your code.
> >
> >Any simple solution for this?
>
> Displaying things interactively is not the same as executing a print
> statement inside the code - I feel right they are not considered the
> same thing. print output goes to sys.stdout, you could replace it.

this is nicely described here:

http://www.voidspace.org.uk/python/weblog/arch_d7_2006_01_21.shtml#e192

do i need the "getattr" and "writeline" methods in MyStdOut?

.

--
http://case.lazaridis.com/ticket/10

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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread MonkeeSage

On Oct 7, 12:37 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> for what?

  key in self.keys()

And d.get() looks like sugar for:

  if self.has_key(key):
return self[key]
  else:
return default_value

Why not have the same sugar for sequence types? E.g.,

  def has_index(self, index):
return index < len(self)

  def get(self, index, default=None):
if self.has_index(index):
  return self[index]
return default

I understand not wanting to add bloat without use cases and / or  when
the programmer can easily implement the functionality themselves; but I
don't see why the sugar would be added for dict but not sequence types.
The fact of easy implementation by the programmer without the
convenience method is the same in both cases, and I would assume (but
don't claim to know) that one could find many use cases for, e.g.,
list.has_index() / . get().

Regards,
Jordan

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


Re: n-body problem at shootout.alioth.debian.org

2006-10-07 Thread igouy

Peter Maas wrote:
> Paul McGuire wrote:
> > The advance method is the most fertile place for optimization, since it is
> > called approximately n(n-1)/2 times (where n=2E7).  I was able to trim about
> > 25% from the Python runtime with these changes:
> [...]
>
> My results:
>
> Your changes: 18% runtime decrease
> Your changes + objects->lists: 25% runtime decrease
>
> The Python program is much closer to the Perl program then (~2250 vs 1900 sec)
> but replacing the objects by lists is not worth the effort because the gain is
> small and the Python program becomes less readable.
>
> Taking arrays (from module array) instead of lists increases runtime by 19%!
>
> If it weren't for the shootout I would of course take psyco and numpy.
>
> --
> Regards/Gruesse,
>
> Peter Maas, Aachen
> E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64')

We can have our Python and Psyco too :-)

http://shootout.alioth.debian.org/gp4sandbox/fulldata.php?test=nbody&p1=python-0&p2=psyco-4&p3=iron-0&p4=psyco-3

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


Re: IDLE - Customizing output format

2006-10-07 Thread Ilias Lazaridis

Ilias Lazaridis wrote:
> IDLE has an output format like this:
>
>  >>> object
> 
>  >>> type
> 
>  >>> object.__class__
> 
>  >>> object.__bases__
>
> How can I customize it to become like that:
>
>  >>> object
>  
>  >>> type
>  
>  >>> object.__class__
>  
>  >>> object.__bases__
>
> or that:
>
>  >>> object
>: 
>  >>> type
>: 
>  >>> object.__class__
>: 
>  >>> object.__bases__
>
> (preferably without modifying code)

I am close to finalizing this task, but have two tiny problems:

import the module from within a site_packages *.pth file, or
include the code into sitecustomize, or
import it withine an IDLE session:

# idlex.py
#---
import sys

class ClaimStdOut:
def __init__(self, stream, prefix):
self.stdout = stream   #remember original stream
self.prefix = prefix

def write(self, output):
self.stdout.write(self.prefix + output)


#this one is _not_ executed on import:
sys.stdout = ClaimStdOut(sys.stdout, '=== ')

#workaround:
def f(obj):
if obj is not None:
print repr(obj)
# Claiming StdOut here
sys.stdout = ClaimStdOut(sys.stdout, '::: ')
#disable displayhook (which is just used to set stdout)
sys.displayhook = sys.__displayhook__

# this one _is_ executed on import
sys.displayhook = f
#---

So, why is this line not executed during import?

sys.stdout = ClaimStdOut(sys.stdout, '=== ')

additionally, the output of IDLE looks like this:

IDLE 1.1.3   No Subprocess 
>>> 1==1
True
[the new stdout is active now]
>>> 1==1
::: True:::
>>>

Possibly IDLE prints the CR/LF in a second call.

How can I compare this operating-system-independent?

if (output == ):
self.stdout.write(output)
else:
self.stdout.write(self.prefix + output)

.

--
http://case.lazaridis.com/ticket/10

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


Re: People's names (was Re: sqlite3 error)

2006-10-07 Thread John Machin
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Steve
> Holden wrote:
>
> > John Machin wrote:
> >
> > [lots of explanation about peculiarities of people's names]
> >
> > While I don't dispute any of this erudite display of esoteric
> > nomenclature wisdom the fact remains that many (predominantly Western)
> > databases do tend to use first and last name (in America often with the
> > addition of a one- or two-character "middle initial" field).
>
> Just because most Western designers of databases do it wrong doesn't mean
> that a) you should do it wrong, or b) they will continue to do it wrong
> into the future, as increasing numbers of those designers come from Asian
> and other non-Western backgrounds.

Unfortunately, lack of appreciation that different rules and customs
may apply on the other side of the county/state/national boundary is a
universal trait, not one restricted to Westerners.

>
> > So, having distilled your knowledge to its essence could you please give
> > me some prescriptive advice about what I *should* do? :-)
>
> Has anyone come up with a proper universal table design for storing people's
> names?
>
> Certainly "first name" and "last name" are the wrong column names to use. I
> think "family name" and "given names" would be a good start.

So far so good.

>  For the
> Icelanders, Somalians and the Muslims, their father's name goes in
> the "family name" field, which makes sense because all their siblings (of
> the same sex, at least) would have the same value in this field.

Two problems so far:
(1) If you then assume that you should print the phone directory in
order of family name, that's not appropriate in some places e.g.
Iceland; neither is addressing Jon Jonsson as "Mr Jonsson", and BTW it
can be their mother's name e.g. if she has more fame or recognition
than their father.
(2) Arabic names: you may or may not have their father's name. You
might not even have the [usually only one] given name. For example: the
person who was known as Abu Musab al-Zarqawi: this means "father of
Musab, the man from Zarqa [a city in Jordan]". You may have the family
name as well as the father's and grandfather's given name. You can have
the occupation, honorifics, nicknames. For a brief overview, read this:
http://en.wikipedia.org/wiki/Arabic_names

>
> I wonder if we need another "middle" field for holding the "bin/binte" part
> (could also hold, e.g. "Van" for those names that use this).

Not a good idea, IMHO. Consider "Nguyen Van Tran" vs 'Rembrandt van
Rijn". Would you peel the Da off Da Costa but not the D' off
D'Oliveiro? What do you do with the bod who fills in a form as Dermot
O'Sullivan one month and Diarmaid Ó Súilleabháin the next?

>
> There would also need to be a flag field to indicate the canonical ordering
> for writing out the full name: e.g. family-name-first, given-names-first.
> Do we need something else for the Vietnamese case?

As I said before, it depends on the application. In some applications,
it will be preferable to capture, in one field, the whole name as
supplied by the person, together with clues like nationality and place
of birth that will help in parsing it later. However if all you want to
do is post out the electricity bill to an address that your
meter-reader has verified, then you can afford to be a  little casual
with the name.

This is all a bit OT.  Before we close the thread down, let me leave
you with one warning:
Beware of enthusiastic maintenance programmers on a mission to clean up
the dirty names in your database:
E.g. (1) "Karim bin Md" may not appreciate getting a letter addressed
to "Dr Karim Bin" (Md is an abbreviation of Muhammad).
E.g. (2) Billing job barfs on a customer who has no given names and no
family name. Inspection reveals that he is over-endowed in the title
department: "Mr Earl King".

Cheers,
John

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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread Duncan Smith
MonkeeSage wrote:
> On Oct 7, 12:37 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> 
>>for what?
> 
> 
>   key in self.keys()
> 

[snip]

No.  The above constructs a list of keys and searches the list for the
key, O(n).  "key in somedict" is a lookup, O(1).

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


New-style classes slower than old-style classes? (Was: n-body problem at shootout.alioth.debian.org)

2006-10-07 Thread Giovanni Bajo
Peter Maas wrote:

>> Did you try using an old-style class instead of a new-style class?
>
> The original program has an old style class, changing it to a new
> style class increases run time by 25% (version is 2.4.3 btw).

Ah yes. Years ago when I first saw this test it was still using new-style
classes.

Anyway, this is a bug on its own I believe. I don't think new-style classes are
meant to be 25% slower than old-style classes. Can any guru clarify this?
-- 
Giovanni Bajo


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


Re: Python to use a non open source bug tracker?

2006-10-07 Thread Giovanni Bajo
Aahz wrote:

>> Are you ever going to try and make a point which is not "you are not
>> entitled to have opinions because you do not act"? Your sarcasm is
>> getting annoying. And since I'm not trolling nor flaming, I think I
>> deserve a little bit more of respect.
>
> IMO, regardless of whether you are trolling or flaming, you are
> certainly being disrespectful.  Why should we treat you with any more
> respect than you give others?

Disrespectful? Because I say that I don't agree with some specific requirement,
trying to discuss and understand the rationale behind it?
-- 
Giovanni Bajo


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


Re: Kde Taskbar

2006-10-07 Thread David Boddie
On Saturday 07 October 2006 15:41, Diez B. Roggisch wrote:

> pykde afaik supports systray-iconified apps. And you could use the
> dcop-mechanisms that are available as command line tools as well I
> guess, and invoke knotify.

I think DarkBlue wanted to affect the behaviour of the taskbar, though
a system tray icon might be a reasonable alternative.

> Hope this gives you some pointers - I'm currently on my mac so I can't
> provide an actual example.

I'd be interested in an example of how to use knotify via DCOP. A few
minutes at the command line looking at the DCOP interface didn't prove
particularly fruitful for me.

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


Re: Can't get around "IndexError: list index out of range"

2006-10-07 Thread MonkeeSage


On Oct 7, 7:14 pm, Duncan Smith <[EMAIL PROTECTED]> wrote:
> No.  The above constructs a list of keys and searches the list for the
> key, O(n).  "key in somedict" is a lookup, O(1).

My point wasn't in regard to implementation details, but in regard to
convenience methods. Obviously the sugary dict methods are tweaked for
the best performance (one would hope!), as would be sugary sequence
methods were they to be added. What I was wondering is why
dict.has_key() and get() are there but not list.has_index() and get().

Regards,
Jordan

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


  1   2   >