Re: python docs for beginner programmer?

2009-05-04 Thread Gabriel Genellina
En Sun, 03 May 2009 21:41:47 -0300, Deep_Feelings   
escribió:



Do you think python online docs are good starting point for me? ( i
experience with other programming languages ) or should i get giant
book or something ?


If you have some previous experience with other languages, I think that  
"Dive into Python" would be a good resource.


--
Gabriel Genellina

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


Re: What IDE support python 3.0.1 ?

2009-05-04 Thread JussiJ
On Apr 16, 1:26 pm, Brendon Wickham  wrote:

> I agree, no IDE needed. Just don't use Notepad! I'm on Mac, so
> spoiled for choice of text editors, but I'm sure there's one
> or 2 good uns if you're on Windows.

The Zeus for Windows IDE is Python aware:

   http://www.zeusedit.com/python.html

It does syntax highlighting, smart indenting etc. You can even
write Zeus scripts in Python.

Jussi Jumppanen
Author: Zeus for Windows IDE
--
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded alternatives to smtplib?

2009-05-04 Thread Alex Jurkiewicz

Diez B. Roggisch wrote:
Without more code, it's impossible to tell if there is anything 
peculiar in your usage of the lib. Maybe you close your connections to 
fast to see several open?


Here's the relevant stuff from my (python2.6) code:


CONCURRENCY = 3

def threadProcessRecipient():
   # Each thread has its own SMTP connection
   smtpserver = smtplib.SMTP(SMTPSERVER)
  
   # Each thread pulls a recipient entry from the queue to process and 
loops until the queue is empty.

   try:
   recipientData = recipientQueue.get_nowait()
   except Queue.Empty:
   recipientData = None
  
   while recipientData:

   message = prepareMessage()
   sendMail(senderEmail, recipientEmail, message, smtpserver)
  
   recipientQueue.task_done()

   try:
   recipientData = recipientQueue.get_nowait()
   except Queue.Empty:
   recipientData = None
  
   smtpserver.quit()


if __name__ == '__main__':
   THREADS = []
   for i in range(CONCURRENCY):
   THREADS.append(threading.Thread(target=threadProcessRecipient))
   for thread in THREADS:
   thread.run()
   for thread in THREADS:
   thread.join()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, Trouble with Message,Label widget

2009-05-04 Thread Hendrik van Rooyen

 "norseman"  wrote:

> There has to be some way of using a Message or Label (or some) widget as
> a simple posting board.

There is - look at textvariable - an instance of StringVar that is associated
with
the widget.

If all else fails, you can always use configure to change the text...

hth - Hendrik

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


Re: Threaded alternatives to smtplib?

2009-05-04 Thread Gabriel Genellina
En Mon, 04 May 2009 04:19:21 -0300, Alex Jurkiewicz  
 escribió:

Diez B. Roggisch wrote:
Without more code, it's impossible to tell if there is anything  
peculiar in your usage of the lib. Maybe you close your connections to  
fast to see several open?


Here's the relevant stuff from my (python2.6) code:


CONCURRENCY = 3

def threadProcessRecipient():
# Each thread has its own SMTP connection
smtpserver = smtplib.SMTP(SMTPSERVER)
   # Each thread pulls a recipient entry from the queue to process  
and loops until the queue is empty.

try:
recipientData = recipientQueue.get_nowait()
except Queue.Empty:
recipientData = None
   while recipientData:
message = prepareMessage()
sendMail(senderEmail, recipientEmail, message, smtpserver)
   recipientQueue.task_done()
try:
recipientData = recipientQueue.get_nowait()
except Queue.Empty:
recipientData = None
   smtpserver.quit()


Try logging the start/stop of your threads. It may be that your threads  
stop before you think. The above code works correctly only if you fill the  
queue before starting any thread - because as soon as a thread sees the  
queue empty, it finishes.
You could use the sample code in the Queue documentation at the end of  
http://docs.python.org/library/queue.html


--
Gabriel Genellina

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


Re: Multiprocessing.Queue - I want to end.

2009-05-04 Thread Hendrik van Rooyen
"Luis Alberto Zarrabeitia Gomez"  wrote:

>Quoting Hendrik van Rooyen :

>> In fact I happen to believe that anything that does any work needs
>> one and only one input queue and nothing else, but I am peculiar
>> that way.
>
>Well, I also need some output. In my case, the outputs are files with the
result
>of the processing, that can be summarized later (hence the need to 'join' the
>processes, to know when I can summarize them).

When you know what you want to do with the output (which
I suspect is your case) then the trick is to put the individual
outputs onto the input queue of the summary process.

This will form a virtual (or real if you have different machines)
systolic array with producers feeding consumers that feed
the summary process, all running concurrently.

Ponder on it that in the description only the word "feed" is used...

And if you don't know where your output must go, then it must be
put onto the input queue of your default router, who must know
what to do with stuff. - this is in a sense what happens when
you pipe stdout to stdin in a *nix environment - you use the OS
to set up a temporary systolic array.

You only need to keep the output of the consumers in files if
you need access to it later for some reason. In your case it sounds
as if you are only interested in the output of the summary.

- Hendrik


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


Re: Strange interaction between timeit and recursion

2009-05-04 Thread Hrvoje Niksic
Steven D'Aprano  writes:

> I don't understand why my recursive function hits the recursion
> limit inside the timeit.Timer when it works outside of it.

Probably because your test function is at the very edge of the
recursion limit, and timeit.Timer triggers it because it calls it at a
deeper stack level than is the case with the interactive prompt.
AFAIK the "recursion limit" simply limits the number of nested
function calls.

> Is there any way to see the current recursion depth at a particular
> moment?

I don't think that's possible from within Python, although maybe it
should be.  The current recursion depth is a simple member of the
thread state structure that could be exposed as a low-level function
that begins with an underscore, similar to sys._getframe.  The
"inspect" module and various debuggers might put it to good use.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Threaded alternatives to smtplib?

2009-05-04 Thread Alex Jurkiewicz

Gabriel Genellina wrote:
Try logging the start/stop of your threads. It may be that your 
threads stop before you think. The above code works correctly only if 
you fill the queue before starting any thread - because as soon as a 
thread sees the queue empty, it finishes.
You could use the sample code in the Queue documentation at the end of 
http://docs.python.org/library/queue.htm
The queue is actually filled before the threads are started, data is 
only removed after they start.


Logging thread state (at least in debug mode) would be good though. How 
would I go about it in this example? The docs suggest using thread.name, 
but in my current setup I don't have any idea which thread is running. 
Something like this:

for i in range(CONCURRENCY):
   THREADS.append( threading.Thread(target=threadProcessRecipient, 
args=i, name=i) )


And:

def threadProcessRecipient(name):
   print "Name is %s" % name


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


Re: Self function

2009-05-04 Thread bearophileHUGS
Arnaud Delobelle:
> >>> def bindfunc(f):
> ...     def boundf(*args, **kwargs):
> ...         return f(boundf, *args, **kwargs)
> ...     return boundf

> ...>>> @bindfunc
> ... def fac(self, n):
> ...     return 1 if n <= 1 else n * self(n - 1)
> ...>>> fac(5)
> 120

This is cute, now I have two names to take care of.
Thank you to all the people that have answered.
Another possible syntax:

def fact(n):
return 1 if n <= 1 else n * return(n - 1)

But I guess most people don't see this problem as important&common
enough to justify changing the language.

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


Re: Is it better to use threads or fork in the following case

2009-05-04 Thread Diez B. Roggisch
CTO wrote:

>> In addition, the zip file format stores the directory at the end of the
>> file. So you can't process it until it's completely downloaded.
>> Concurrency doesn't help here.
> 
> Don't think that's relevant, if I'm understanding the OP correctly.
> Lets say you've downloaded the file once and you're doing whatever
> the app does with it. Now, while that's happening the half an hour
> time limit comes up. Now you want to start another download, but
> you also want to continue to work with the old version. Voila,
> concurrency.

Which brings us backs to the "20 questions"-part of my earlier post. It
could be, but it could also be that processing takes seconds. Or it takes
so long that even concurrency won't help. Who knows?

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


Re: Threaded alternatives to smtplib?

2009-05-04 Thread Diez B. Roggisch
Alex Jurkiewicz wrote:

> Gabriel Genellina wrote:
>> Try logging the start/stop of your threads. It may be that your
>> threads stop before you think. The above code works correctly only if
>> you fill the queue before starting any thread - because as soon as a
>> thread sees the queue empty, it finishes.
>> You could use the sample code in the Queue documentation at the end of
>> http://docs.python.org/library/queue.htm
> The queue is actually filled before the threads are started, data is
> only removed after they start.
> 
> Logging thread state (at least in debug mode) would be good though. How
> would I go about it in this example? The docs suggest using thread.name,
> but in my current setup I don't have any idea which thread is running.
> Something like this:
> for i in range(CONCURRENCY):
> THREADS.append( threading.Thread(target=threadProcessRecipient,
> args=i, name=i) )
> 
> And:
> 
> def threadProcessRecipient(name):
> print "Name is %s" % name

Each thread gets an unique name assigned anyway. Alternatively, you can use
partial to bind parameters to functions. And last but not least to subclass
Thread is also an option.

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


Re: Threaded alternatives to smtplib?

2009-05-04 Thread Diez B. Roggisch
Diez B. Roggisch wrote:

> Alex Jurkiewicz wrote:
> 
>> Gabriel Genellina wrote:
>>> Try logging the start/stop of your threads. It may be that your
>>> threads stop before you think. The above code works correctly only if
>>> you fill the queue before starting any thread - because as soon as a
>>> thread sees the queue empty, it finishes.
>>> You could use the sample code in the Queue documentation at the end of
>>> http://docs.python.org/library/queue.htm
>> The queue is actually filled before the threads are started, data is
>> only removed after they start.
>> 
>> Logging thread state (at least in debug mode) would be good though. How
>> would I go about it in this example? The docs suggest using thread.name,
>> but in my current setup I don't have any idea which thread is running.
>> Something like this:
>> for i in range(CONCURRENCY):
>> THREADS.append( threading.Thread(target=threadProcessRecipient,
>> args=i, name=i) )
>> 
>> And:
>> 
>> def threadProcessRecipient(name):
>> print "Name is %s" % name
> 

Oh, and I forgot - threading.currentThread() gets you the actively running
thread of course.

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


Re: yet another list comprehension question

2009-05-04 Thread Arnaud Delobelle
Snorri H  writes:

> On May 3, 6:13 am, Ross  wrote:
>> I'm trying to set up a simple filter using a list comprehension. If I
>> have a list of tuples, a = [(1,2), (3,4), (5,None), (6,7), (8, None)]
>> and I wanted to filter out all tuples containing None, I would like to
>> get the new list b = [(1,2), (3,4),(6,7)].
>>
>> I tried b = [i for i in a if t for t in i is not None]   but I get the
>> error that "t is not defined". What am I doing wrong?
>
>
> Works as well:
> filter(lambda x:not None in x, your_list)
  ^
This is usually spelt 'None not in x'.

-- 
Arnaud

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


Re: yet another list comprehension question

2009-05-04 Thread Snorri H
On May 3, 6:13 am, Ross  wrote:
> I'm trying to set up a simple filter using a list comprehension. If I
> have a list of tuples, a = [(1,2), (3,4), (5,None), (6,7), (8, None)]
> and I wanted to filter out all tuples containing None, I would like to
> get the new list b = [(1,2), (3,4),(6,7)].
>
> I tried b = [i for i in a if t for t in i is not None]   but I get the
> error that "t is not defined". What am I doing wrong?


Works as well:
filter(lambda x:not None in x, your_list)
--
http://mail.python.org/mailman/listinfo/python-list


Re: yet another list comprehension question

2009-05-04 Thread David Robinow
On Mon, May 4, 2009 at 2:33 AM, namekuseijin
 wrote:
 ls = [(1,2), (3,4), (5, None), (6,7), (8, None)]
 [(x,y) for (x,y) in ls if y]
> [(1, 2), (3, 4), (6, 7)]

Nope. That filters out 0 as well as None. Not what the OP asked for.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to walk up parent directories?

2009-05-04 Thread Snorri H
On May 4, 5:04 am, Matthew Wilson  wrote:
> Is there already a tool in the standard library to let me walk up from a
> subdirectory to the top of my file system?


Never seen such a standard tool, yet it can be implemented in a way
like this

def walkup(path):
aux = path.rsplit('/')
while aux != ['']:
yield reduce(lambda x,y:x+'/'+y,aux)
aux.pop()
yield '/'

Maybe this is not the best way to ascend directories, but it seems to
work.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What IDE support python 3.0.1 ?

2009-05-04 Thread Mark
On Wed, 15 Apr 2009 22:45:35 +, Benjamin Peterson wrote:
> Why do you think you're wasting time with 2.x?

I'm a relative newbie to python as well but I'd agree that there is at
least a small degree of time "wasted" learning python 2.x simply because
the standard library of python 3.x has been cleaned up and consolidated
which makes learning it slightly easier.
--
http://mail.python.org/mailman/listinfo/python-list


find sublist inside list

2009-05-04 Thread Matthias Gallé

Hi.

My problem is to replace all occurrences of a sublist with a new element.

Example:
Given ['a','c','a','c','c','g','a','c'] I want to replace all 
occurrences of ['a','c'] by 6 (result [6,6,'c','g',6]).


If I do this with string ('acaccgac') I have the advantage of all the 
'find' functions, but perfomance is bad and some extra care must be 
taken if one element consist of more then one character (case of 11 for 
example)


So I really would like to work with lists straightforward, but I could 
not found anything to search a sublist inside a list.

Any propositions for a simple solution?

Thanks in advance,


--
Matthias Gallé
Project Symbiose
Centre de Recherche INRIA Rennes - Bretagne Atlantique,
Campus de Beaulieu, 35042 Rennes cedex, France
tel: (33|0) 2 9984 7523
http://www.irisa.fr/symbiose/matthias_galle
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread BJörn Lindqvist
2009/5/4  :
> An idea-syntax:
>
> def fact(n):
>    return 1 if n <= 1 else n * inspect.self(n - 1)
>
> Or even a lambda, because you don't need the name anymore to call the
> function:
>
> fact = lambda n: 1 if n <= 1 else n * self(n - 1)

How would it work with methods?

class Foo:
def fac(self, n):
return 1 if n <= 1 else n * self.self(n-1)

??


-- 
mvh Björn
--
http://mail.python.org/mailman/listinfo/python-list


replacing numbers in LARGE MATRIX with criterium in 2 columns (a--> b)

2009-05-04 Thread Alexzive
Hello,
I have this matrix [20*4 - but it could be n*4 , with n~100,000] in
file "EL_list" like this:

1,  1,  2,  3
 2,  4,  1,  5
 3,  5,  1,  6
 4,  7,  5,  6
 5,  8,  7,  9
 6,  8,  5,  7
 7, 10,  9,  7
 8, 10, 11, 12
 9,  7, 13, 10
10, 14, 15, 16
11, 14, 17, 15
12, 17, 14, 18
13, 13, 16, 10
14, 16, 15, 11
15, 16, 11, 10
16, 19, 20, 21
17, 22, 15, 20
18, 17, 20, 15
19, 23, 20, 24
20, 25, 24, 20

I would like to replace some numbers in "EL_list" but only in columns
2,3,4 using the criterium by line in file "criterium" (column 1 are
the new numbers, column 2 the old ones).

1   1
2   3
3   5
4   12
5   13
6   14
7   15
8   16
9   17
10  18
11  19
12  10
13  21
14  22
15  23
16  24
17  25

For example all the 7 have to replaced by 15 and so on..

-- How to implement it in a fast end efficient code?

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


Re: replacing numbers in LARGE MATRIX with criterium in 2 columns (a--> b)

2009-05-04 Thread Alessandro
On May 4, 2:38 pm, Alexzive  wrote:
> Hello,
> I have this matrix [20*4 - but it could be n*4 , with n~100,000] in
> file "EL_list" like this:
>
> 1,  1,  2,  3
>  2,  4,  1,  5
>  3,  5,  1,  6
>  4,  7,  5,  6
>  5,  8,  7,  9
>  6,  8,  5,  7
>  7, 10,  9,  7
>  8, 10, 11, 12
>  9,  7, 13, 10
> 10, 14, 15, 16
> 11, 14, 17, 15
> 12, 17, 14, 18
> 13, 13, 16, 10
> 14, 16, 15, 11
> 15, 16, 11, 10
> 16, 19, 20, 21
> 17, 22, 15, 20
> 18, 17, 20, 15
> 19, 23, 20, 24
> 20, 25, 24, 20
>
> I would like to replace some numbers in "EL_list" but only in columns
> 2,3,4 using the criterium by line in file "criterium" (column 1 are
> the new numbers, column 2 the old ones).
>
> 1   1
> 2   3
> 3   5
> 4   12
> 5   13
> 6   14
> 7   15
> 8   16
> 9   17
> 10  18
> 11  19
> 12  10
> 13  21
> 14  22
> 15  23
> 16  24
> 17  25



>
> For example all the 7 have to replaced by 15 and so on..
>

ERRATA: for example, all the 15 have to replaced by 7 and so on..
--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-04 Thread bearophileHUGS
Matthias Gallé:
> My problem is to replace all occurrences of a sublist with a new element.
> Example:
> Given ['a','c','a','c','c','g','a','c'] I want to replace all
> occurrences of ['a','c'] by 6 (result [6,6,'c','g',6]).

There are several ways to solve this problem. Representing a string as
a list of "chars" (1-strings) is fine if you work with small strings,
but once they get longer you need too much memory and time.

This is a starting point:

>>> mapper = {"a":6, "c":6}
>>> data = 'acaccgac'
>>> [mapper.get(c, c) for c in data]
[6, 6, 6, 6, 6, 'g', 6, 6]

If you need higher performance, to represent few small numbers into a
well defined string like genomic data, you can use ASCII values of 6
and 11:

>>> from string import maketrans
>>> tab = maketrans("acgt", "".join([chr(6), chr(6), "gt"]))
>>> s.translate(tab)
'\x06\x06\x06\x06\x06g\x06\x06'

Later in processing it's easy to tell apart normal genome bases from
those small numbers.

Note that there is the array.array function too in the standard lib,
and elsewhere there is Numpy too.

There are several other possible solutions, but I stop here so you can
explain your purposes and constraints better.

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


Re: find sublist inside list

2009-05-04 Thread John O'Hagan
On Mon, 4 May 2009, Matthias Gallé wrote:
> Hi.
>
> My problem is to replace all occurrences of a sublist with a new element.
>
> Example:
> Given ['a','c','a','c','c','g','a','c'] I want to replace all
> occurrences of ['a','c'] by 6 (result [6,6,'c','g',6]).
>

li=['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c'] 
for i  in range(len(li)):
if li[i:i + 2] == ['a', 'c']:
li[i:i + 2] = ['6']

HTH,

John




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


Re: find sublist inside list

2009-05-04 Thread Francesco Guerrieri
On Mon, May 4, 2009 at 3:01 PM, John O'Hagan  wrote:

> On Mon, 4 May 2009, Matthias Gallé wrote:
> > Hi.
> >
> > My problem is to replace all occurrences of a sublist with a new element.
> >
> > Example:
> > Given ['a','c','a','c','c','g','a','c'] I want to replace all
> > occurrences of ['a','c'] by 6 (result [6,6,'c','g',6]).
> >
>
> li=['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
> for i  in range(len(li)):
>if li[i:i + 2] == ['a', 'c']:
>li[i:i + 2] = ['6']
>
> HTH,
>
> John
>

Beware that you are mutating the list you are iterating over. That could
lead to some strange bugs (for instance if you replaced the deleted items
with a longer sequence, the range(len(li)) would still go up to the original
lenght).
It is better to modify a new list instead. Eg you could append to a new
list.

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


Help in getting the IP address of client machines

2009-05-04 Thread M Kumar
Hi,

I am using pylons web framework for my server. I need to get the ip address
of the client machine which made a request to the server in my python code.
How can I do that, I am new to pylons and the existing server has so many
applications. looking forward to get some solutions from the kind friendly
users

thanks & regards
Maneesh KB
--
http://mail.python.org/mailman/listinfo/python-list


Default padding for Tkinter grid

2009-05-04 Thread Amr
Hello all,

I've been spending the last few days experimenting with Tkinter. The
grid manager is nice and easy to use, but I have found that I am often
having to specify padx and pady options to every widget I add to my
grid. The way I am doing it is to create a dictionary:

paddding = {'padx': '1m', 'pady': '1m'}

and then apply it to the grid method using **padding.

However, I was wondering if there was a way of setting default padx
and pady controls for the grid, so that I can just call grid without
having to specify any extra parameters.

Thanks,

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


Re: [SPAM] Re: Threaded alternatives to smtplib?

2009-05-04 Thread MRAB

Diez B. Roggisch wrote:

Alex Jurkiewicz schrieb:

Hi all,
I'm writing a Python script to do a "mail merge" style email 
distribution. I create a few python threads and in each one I call 
`smtpserver = smtplib.SMTP(our.smtpserver.com)`. However, during the 
sending process, there seems to be only one connection open to our 
mail server at any one time. In other words, all these threads gain me 
no speed benefit at all!


I seem to be running into the issue where smtplib is not fully 
thread-safe, as mentioned in this thread:

http://mail.python.org/pipermail/python-list/2007-March/429067.html
http://mail.python.org/pipermail/python-list/2007-March/429172.html

Does anyone have suggestions as to a suitable workaround for this 
issue? I was looking at the Twisted library, which seems possible but 
significantly more complex.


I doubt that there is such issue. The above discussion is not concluding 
that there actually *are* threading-issues within smtplib. And looking 
at the source of smtplib, it certainly doesn't use any 
locking-primitives or (directly) any c-extension that might explain such 
behavior.


Without more code, it's impossible to tell if there is anything peculiar 
in your usage of the lib. Maybe you close your connections to fast to 
see several open?



If all the threads are using the same server, couldn't the SMTP part be
put into its own thread and then fed the pre-composed emails via a
queue?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-04 Thread Ross
On May 3, 10:16 pm, John Yeung  wrote:
> On May 3, 11:29 pm, Chris Rebert  wrote:
>
> > Probably not the cause of the problem, but where
> > did the magic numbers 1.072 and 1.08 come from?
>
> It is perhaps not the most direct cause of the problem, in the sense
> that the magic numbers could take various values and the problem would
> still be there.  But the magic numbers appear to be used for
> "spreading out" bye selection, and that's broken.
>
> The extended slice as written will always pick the first element,
> since the step is guaranteed to be positive.  Since the first player
> (or None, when there are an odd number of players) stays put in the
> first position during the round_robin shuffle, that player will always
> be selected for a bye.
>
> Further, as written, the calculated number of byes has no bearing on
> the actual number of byes selected.
>
> I think what I would do is adjust the shuffling algorithm in such a
> way that everyone moves through the various positions in the list
> (would it be as simple as adding a shift at the end of
> round_robin???).  Then I could simply select the byes from one end of
> the list (with a regular slice instead of an extended slice).
>
> John

The "magic numbers" that everyone is wondering about are indeed used
for spreading out the bye selection and I got them by simply
calculating a line of best fit when plotting several courts: byes
ratios.

The "byes = #whatever" in my code calculate the number of tuples that
need to be placed in the bye_list.

At first glance, the suggestion of adding a simple shift at the end of
round_robin doesn't seem to work since round_robin already shifts
everything except for the first position already. Please correct me if
I'm wrong because you might have been suggesting something different.
--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-04 Thread bearophileHUGS
Matthias Gallé:
>the int that can replace a sublist can be > 255,<

You didn't specify your integer ranges.
Probably there are many other solutions for your problem, but you have
to give more information. Like the typical array size, typical range
of the numbers, how much important is total memory used, how much
important is running speed, what kind of processing (or serialization/
output) you later have to do with such arrays, and so on.
Other solutions include using an array('H', []), and using 0-255 to
represent ASCII and numbers >255 <2^16 to represent the other numbers,
etc.
If speed is critical you can even think about creating a little
function with PyInline or D+Pyd, etc.

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


IDE for python 2.6 (auto complete)

2009-05-04 Thread Soumen banerjee
Hello,
I have just installed and run python 2.6.2 from the sources available
on the website. I notice that SPE (the editor which i used with python
2.5) is not displaying some of the functions new in 2.6 as
autocomplete options. Is there any IDE with support for autocomplete
in python 2.6 with all the newer functions included?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Default padding for Tkinter grid

2009-05-04 Thread Amr
On May 4, 3:57 pm, "Gabriel Genellina"  wrote:
> En Mon, 04 May 2009 10:27:49 -0300, Amr  escribió:
>
> > I've been spending the last few days experimenting with Tkinter. The
> > grid manager is nice and easy to use, but I have found that I am often
> > having to specify padx and pady options to every widget I add to my
> > grid. The way I am doing it is to create a dictionary:
>
> > paddding = {'padx': '1m', 'pady': '1m'}
>
> > and then apply it to the grid method using **padding.
>
> > However, I was wondering if there was a way of setting default padx
> > and pady controls for the grid, so that I can just call grid without
> > having to specify any extra parameters.
>
> You have to call grid() once on every widget, so adding **padding at the  
> end doesn't appear too bad to me:
>
>    label = Label(master, text="Hello world!")
>    widget.grid(row=3, col=1, **padding)
>
> What about a function:
>
> def grid_with_padding(widget, padx='1m', pady='1m', **kw):
>    widget.grid(padx=padx, pady=pady, **kw)
>
> If you want an uniform padding:
>
> def add_padding(container, padx='1m', pady='1m'):
>    nc, nr = container.grid_size()
>    for i in range(nc):
>      container.grid_columnconfigure(i, pad=padx)
>    for i in range(nr):
>      container.grid_rowconfigure(i, pad=pady)
>
> --
> Gabriel Genellina

Hi Gabriel,

Thanks for your reply - I like the method you mention at the end,
using grid_columnconfigure and grid_rowconfigure as I can use that to
apply setting to the whole grid at the end. I'll have a mess around
with it.

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


Re: Self function

2009-05-04 Thread Steve Howell
On May 3, 3:39 pm, bearophileh...@lycos.com wrote:
> Sometimes I rename recursive functions, or I duplicate&modify them,
> and they stop working because inside them there's one or more copy of
> their old name.
> This happens to me more than one time every year.
> So I have written this:
>
> from inspect import getframeinfo, currentframe
>
> def SOMEVERYUGLYNAME(n):
>     if n <= 1:
>         return 1
>     else:
>         self_name = getframeinfo(currentframe()).function
>         #self_name = getframeinfo(currentframe())[2] # older python
>
>         # only if it's a global function
>         #return n * globals()[self_name](n - 1)
>         return n * eval(self_name + "(%d)" % (n - 1))
> assert SOMEVERYUGLYNAME(6) == 2*3*4*5*6
>
> Are there nicer ways to do that? I don't know.
> If there aren't, then a way may be added.
> An idea-syntax:
>
> def fact(n):
>     return 1 if n <= 1 else n * inspect.self(n - 1)
>
> Or even a lambda, because you don't need the name anymore to call the
> function:
>
> fact = lambda n: 1 if n <= 1 else n * self(n - 1)
>
> (If you have two or more recursive functions that call each other this
> idea can't be used, but I think such situations are uncommon enough to
> not deserve help from the language).
>

One very simple thing that you can do is assign the current function
name to a local var at the very top to make it a little more obvious.

I agree that there are lots of recursive patterns where python itself
does not provide much sugar.  A pattern that comes up for me
occasionally is two methods with almost identical names, where one
function is the public interface and then another method that does
most of the recursion.
--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-04 Thread MRAB

Matthias Gallé wrote:

bearophileh...@lycos.com wrote:

John O'Hagan:

li=['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
for i  in range(len(li)):
if li[i:i + 2] == ['a', 'c']:
li[i:i + 2] = ['6']


Oh well, I have done a mistake, it seems.
Another solution then:


'acaccgac'.replace("ac", chr(6))

'\x06\x06cg\x06'

Bye,
bearophile


Thanks bearophile and John for your quick answers.
Unfortunately, the int that can replace a sublist can be > 255, but 
John's answer looks simple and good enough for me. I will use it as a 
starting point.



John's solution changes the length of the list over which it's
iterating.

I'd suggest something more like:

li = ['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
pos = 0
try:
while True:
pos = li.index('a', pos)
if li[pos : pos + 2] == ['a', 'c']:
li[pos : pos + 2] = [6]
pos += 1
except ValueError:
pass
--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-04 Thread Matthias Gallé

bearophileh...@lycos.com wrote:

John O'Hagan:

li=['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
for i  in range(len(li)):
if li[i:i + 2] == ['a', 'c']:
li[i:i + 2] = ['6']


Oh well, I have done a mistake, it seems.
Another solution then:


'acaccgac'.replace("ac", chr(6))

'\x06\x06cg\x06'

Bye,
bearophile


Thanks bearophile and John for your quick answers.
Unfortunately, the int that can replace a sublist can be > 255, but 
John's answer looks simple and good enough for me. I will use it as a 
starting point.


Thank's again.

--
Matthias Gallé
Project Symbiose
Centre de Recherche INRIA Rennes - Bretagne Atlantique,
Campus de Beaulieu, 35042 Rennes cedex, France
tel: (33|0) 2 9984 7523
http://www.irisa.fr/symbiose/matthias_galle
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-04 Thread Ross
On May 4, 7:01 am, Ross  wrote:
> On May 3, 10:16 pm, John Yeung  wrote:
>
>
>
> > On May 3, 11:29 pm, Chris Rebert  wrote:
>
> > > Probably not the cause of the problem, but where
> > > did the magic numbers 1.072 and 1.08 come from?
>
> > It is perhaps not the most direct cause of the problem, in the sense
> > that the magic numbers could take various values and the problem would
> > still be there.  But the magic numbers appear to be used for
> > "spreading out" bye selection, and that's broken.
>
> > The extended slice as written will always pick the first element,
> > since the step is guaranteed to be positive.  Since the first player
> > (or None, when there are an odd number of players) stays put in the
> > first position during the round_robin shuffle, that player will always
> > be selected for a bye.
>
> > Further, as written, the calculated number of byes has no bearing on
> > the actual number of byes selected.
>
> > I think what I would do is adjust the shuffling algorithm in such a
> > way that everyone moves through the various positions in the list
> > (would it be as simple as adding a shift at the end of
> > round_robin???).  Then I could simply select the byes from one end of
> > the list (with a regular slice instead of an extended slice).
>
> > John
>
> The "magic numbers" that everyone is wondering about are indeed used
> for spreading out the bye selection and I got them by simply
> calculating a line of best fit when plotting several courts: byes
> ratios.
>
> The "byes = #whatever" in my code calculate the number of tuples that
> need to be placed in the bye_list.
>
> At first glance, the suggestion of adding a simple shift at the end of
> round_robin doesn't seem to work since round_robin already shifts
> everything except for the first position already. Please correct me if
> I'm wrong because you might have been suggesting something different.

And also, as you all have pointed out, my inclusion of

> def test_round_robin(players, rounds, courts, doubles = False):
> players = range(players)
> for week in round_robin(players,rounds,courts):

should have been

> def test_round_robin(players, rounds, courts, doubles = False):
> players = range(players)
> for week in round_robin(players,rounds):

I forgot to erase that extra parameter when I was playing around with
my code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: IDE for python 2.6 (auto complete)

2009-05-04 Thread Mike Driscoll
On May 4, 10:13 am, Soumen banerjee  wrote:
> Hello,
> I have just installed and run python 2.6.2 from the sources available
> on the website. I notice that SPE (the editor which i used with python
> 2.5) is not displaying some of the functions new in 2.6 as
> autocomplete options. Is there any IDE with support for autocomplete
> in python 2.6 with all the newer functions included?

Wingware probably does. You should just submit a bug report to Stani
though. He can probably fix SPE for you.

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


Re: How to walk up parent directories?

2009-05-04 Thread David Smith
Matthew Wilson wrote:
> Is there already a tool in the standard library to let me walk up from a
> subdirectory to the top of my file system?
> 
> In other words, I'm looking for something like:
> 
> >>> for x in walkup('/home/matt/projects'):
> ... print(x)
> /home/matt/projects
> /home/matt
> /home
> /
> 
> I know I could build something like this with various os.path
> components, but I'm hoping I don't have to.
> 
> TIA
> 
> 
> Matt

You should take a look at the os.path module.  Seems like you might find
something in that toolbox for this.

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


Re: Default padding for Tkinter grid

2009-05-04 Thread Gabriel Genellina

En Mon, 04 May 2009 10:27:49 -0300, Amr  escribió:


I've been spending the last few days experimenting with Tkinter. The
grid manager is nice and easy to use, but I have found that I am often
having to specify padx and pady options to every widget I add to my
grid. The way I am doing it is to create a dictionary:

paddding = {'padx': '1m', 'pady': '1m'}

and then apply it to the grid method using **padding.

However, I was wondering if there was a way of setting default padx
and pady controls for the grid, so that I can just call grid without
having to specify any extra parameters.


You have to call grid() once on every widget, so adding **padding at the  
end doesn't appear too bad to me:


  label = Label(master, text="Hello world!")
  widget.grid(row=3, col=1, **padding)

What about a function:

def grid_with_padding(widget, padx='1m', pady='1m', **kw):
  widget.grid(padx=padx, pady=pady, **kw)

If you want an uniform padding:

def add_padding(container, padx='1m', pady='1m'):
  nc, nr = container.grid_size()
  for i in range(nc):
container.grid_columnconfigure(i, pad=padx)
  for i in range(nr):
container.grid_rowconfigure(i, pad=pady)

--
Gabriel Genellina

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


Re: Re: replacing numbers in LARGE MATRIX with criterium in 2 columns (a--> b)

2009-05-04 Thread Dave Angel



Alessandro wrote:

On May 4, 2:38 pm, Alexzive  wrote:
  

Hello,
I have this matrix [20*4 - but it could be n*4 , with n~100,000] in
file "EL_list" like this:

1,  1,  2,  3
 2,  4,  1,  5
 3,  5,  1,  6
 4,  7,  5,  6
 5,  8,  7,  9
 6,  8,  5,  7
 7, 10,  9,  7
 8, 10, 11, 12
 9,  7, 13, 10
10, 14, 15, 16
11, 14, 17, 15
12, 17, 14, 18
13, 13, 16, 10
14, 16, 15, 11
15, 16, 11, 10
16, 19, 20, 21
17, 22, 15, 20
18, 17, 20, 15
19, 23, 20, 24
20, 25, 24, 20

I would like to replace some numbers in "EL_list" but only in columns
2,3,4 using the criterium by line in file "criterium" (column 1 are
the new numbers, column 2 the old ones).

1   1
2   3
3   5
4   12
5   13
6   14
7   15
8   16
9   17
10  18
11  19
12  10
13  21
14  22
15  23
16  24
17  25





  

For example all the 7 have to replaced by 15 and so on..




ERRATA: for example, all the 15 have to replaced by 7 and so on..

  
What have you come up with so far?  Did the instructor give you any 
sample code to solve similar problems?  Did he really describe it as a 
matrix?


Sounds to me like you have two text files.  One contains a replacement 
table (which you can read into a dictionary), and the other (large) file 
is just text.  After building the dictionary, you'd want a loop that 
goes through the text file, splitting each line into a list of four.  
You then use the dictionary to replace list items 1, 2, and 3, and write 
the result someplace.


Try writing the code, see if anything goes wrong, and then ask for help.

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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-05-04 Thread Antoon Pardon
On 2009-04-24, Steven D'Aprano  wrote:
> On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:
>
>> Hello,
>> 
>> I'm trying to do a if statement with a function inside it. I want to use
>> that variable inside that if loop , without defining it.
>> 
>> def Test():
>> return 'Vla'
>> 
>> I searching something like this:
>> 
>> if (t = Test()) == 'Vla':
>> print t # Vla
>> 
>> or
>> 
>> if (t = Test()):
>> print t # Vla
>
> Fortunately, there is no way of doing that with Python. This is one 
> source of hard-to-debug bugs that Python doesn't have.

I think this is an unfortunate consequence of choosing '=' for the
assignment. They could have chosen an other token to indicate an
assignment one that would have made the difference between an
assignment and a comparison more visually different and thus
bugs by using one while needing the other less hard to track
down.

So when a certain kind of bug is hard to track down because of
the similarity of the tokens and not because of the specific
functionality I find it unfortunate they dropped the functionality
instead of making the tokens less similar.

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


Re: fcntl and siginfo_t in python

2009-05-04 Thread ma
Ok! So, I decided to write a C-extension instead of using ctypes. So
far, I create a module called dnotifier and the handler callback
receives two arguments, the signal number and the respective file
descriptor that was modified.

This works beautifully. Now, I want to release this to the public, so
I'm thinking of making a bit of code cleanup. Should I just pack the
entire siginfo_t struct, right now I just use the fd, into a
dictionary and pass it to the python callback handler function? Maybe
there might be some more suggestions to what data structures to use,
so I'm open right now to any of them.

The siginfo_t structure is defined as follows in C:

union sigval {
int sival_int;
void *sival_ptr;
};

typedef struct {
int si_signo;
int si_code;
union sigval si_value;
int si_errno;
pid_t si_pid;
uid_t si_uid;
void *si_addr;
int si_status;
int si_band;
} siginfo_t;

Thanks,
Mahmoud



On Fri, May 1, 2009 at 3:08 PM, ma  wrote:
>
> According to man signal,
> "The default action for an unhandled real-time signal is to terminate
> the receiving process."
>
> This means that my registered callback and sigaction does not work. I
> think the only solution would be to try this with a C-extension. Has
> anyone had any experience with this before?
>
> I attached my latest copy. Any insight is appreciated.
>
> On Thu, Apr 30, 2009 at 7:37 PM, ma  wrote:
> > I attached a clean copy of the .py file in case others couldn't read
> > it in their emails.
> > I'll try that and let you know how SIGRTMIN+1 goes!
> > What about this part?
> >
> > #sigemptyset(&act.sa_mask);
> > #python2.6 has byref(act, offset),how can i port this over?
> > #maybe addressof(act)+sizeof(sigaction.sa_mask)*(position_in_sigaction)
> > rc = __clib.sigemptyset(byref(act))
> >
> > Thanks!
> > Mahmoud
> >
> >
> >
> > On Thu, Apr 30, 2009 at 7:33 PM, Philip  wrote:
> >>
> >> ma  gmail.com> writes:
> >>
> >> >
> >> >
> >> >
> >> >
> >> > Here's something that I came up with so far, I'm having some issues with
> >> segfaulting, if I want to pass a struct member by ref in ctypes(see 
> >> below), if
> >> not, I just get a
> >> > "Real-time signal 0" sent back to me.
> >> >
> >> >
> >> > Any ideas?
> >>
> >> Try "SIGRTMIN+1", per http://souptonuts.sourceforge.net/code/dnotify.c.html
> >>
> >> Philip
> >>
> >>
> >>
> >> --
> >> http://mail.python.org/mailman/listinfo/python-list
> >
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-04 Thread Ross
On May 3, 8:29 pm, John Machin  wrote:
> On May 4, 12:36 pm, Ross  wrote:
>
>
>
> > For the past couple weeks, I've been working on an algorithm to
> > schedule tennis leagues given court constraints and league
> > considerations (i.e. whether it's a singles or a doubles league). Here
> > were my requirements when I was designing this algorithm:
>
> > -Each player plays against a unique opponent each week.
> > -Similarly, in a doubles league, each player plays with a unique
> > partner each week.
> > -Each player gets a fair number of bye weeks (i.e. the player with the
> > most bye weeks will have no more than one bye week than the player
> > with the least number of bye weeks)
>
> > I'm very close to arriving at my desired solution, but I have one
> > glaring flaw. When I have an even number of players sign up for my
> > league and there are court constraints, my current algorithm gives the
> > first player in my league a bye week every single week. I'll post my
> > code below and see how you guys think I should add to/ amend my code.
>
> > def round_robin(players, rounds):
> >     if len(players)%2:
> >         players.insert(0, None)
> >     mid = len(players)//2
> >     for i in range(rounds):
> >         yield zip(players[:mid], players[mid:])
> >         players = players[0:1] + players[mid:mid+1] + players[1:mid-1] +
> > players[mid+1:] + players[mid-1:mid]
>
> > def test_round_robin(players, rounds, courts, doubles = False):
> >     players = range(players)
>
> DON'T change the type/contents/meaning of a variable name like that.
> E.g. use "nthings" for a number of things and "things" for a
> collection of things.
>
> >     for week in round_robin(players,rounds,courts):
>
> The round_robin() function has only TWO arguments. This code won't
> even run.
>
> When you document neither your data structures nor what your functions
> are intended to do, the last hope for somebody trying to make sense of
> your code is to give meaningful names to your variables. "week" and
> "doubles_week" are NOT meaningful.
>
> >             if doubles == True:
>
> Bletch. s/ == True//
>
> >                     doubles_week = len(week)/2.0
>
> I doubt very much that using floating point is a good idea here.
>
> >                     byes = doubles_week - courts
> >                     if byes == 0:
> >                             bye_list = []
> >                     else:
> >                             bye_list = 
> > week[::int(round(1.072*(courts/byes)+1.08))]
>
> The derivation of the constants 1.072 and 1.08 is  what?
>
> >                     playing = [u for u in week if u not in bye_list]
> >                     midd = len(playing)//2
> >                     doub_sched = zip(playing[:midd], playing[midd:])
> >                     print doub_sched, bye_list
> >             else:
> >                     byes = len(week)- courts
> >                     if byes == 0:
> >                             bye_list = []
> >                     else:
> >                             bye_list = 
> > week[::int(round(1.072*(courts/byes)+1.08))]
> >                     playing = [u for u in week if u not in bye_list]
> >                     print playing, bye_list

For everybody's enlightenment, I have gone through and commented my
code so you can better understand what I'm doing. Here it is:

def round_robin(players, rounds):
# if number of players odd, insert None at first position
if len(players)%2:
players.insert(0, None)
mid = len(players)//2
for i in range(rounds):
yield zip(players[:mid], players[mid:])
players = players[0:1] + players[mid:mid+1] + players[1:mid-1] +
players[mid+1:] + players[mid-1:mid]
""" rotates players like this: 1 2  ->  3 -> 4

 /|

   5 <- 6 <-7 <- 8 """

def test_round_robin(players, rounds, courts, doubles = False):
players = range(players)
for week in round_robin(players,rounds):
if doubles == True: #for doubles pairings
doubles_week = len(week)/2.0
byes = doubles_week - courts #number of tuples to be put 
into
bye_list
if byes == 0:
bye_list = []
else: """ following formula equally spaces out tuples 
selected
for bye_list and selects appropriate number according to length of the
league"""
bye_list = 
week[::int(round(1.072*(courts/byes)+1.08))]
playing = [u for u in week if u not in bye_list]
midd = len(playing)//2
doub_sched = zip(playing[:midd], playing[midd:])#matches the
remaining tuples into doubles matches
print doub_sched, bye_list
else:
byes = len(week)- courts
if byes == 0:
bye_list = []
else:
bye

Re: replacing numbers in LARGE MATRIX with criterium in 2 columns (a--> b)

2009-05-04 Thread MRAB

Alexzive wrote:

Hello,
I have this matrix [20*4 - but it could be n*4 , with n~100,000] in
file "EL_list" like this:

1,  1,  2,  3
 2,  4,  1,  5
 3,  5,  1,  6
 4,  7,  5,  6
 5,  8,  7,  9
 6,  8,  5,  7
 7, 10,  9,  7
 8, 10, 11, 12
 9,  7, 13, 10
10, 14, 15, 16
11, 14, 17, 15
12, 17, 14, 18
13, 13, 16, 10
14, 16, 15, 11
15, 16, 11, 10
16, 19, 20, 21
17, 22, 15, 20
18, 17, 20, 15
19, 23, 20, 24
20, 25, 24, 20

I would like to replace some numbers in "EL_list" but only in columns
2,3,4 using the criterium by line in file "criterium" (column 1 are
the new numbers, column 2 the old ones).

1   1
2   3
3   5
4   12
5   13
6   14
7   15
8   16
9   17
10  18
11  19
12  10
13  21
14  22
15  23
16  24
17  25

For example all the 7 have to replaced by 15 and so on..

-- How to implement it in a fast end efficient code?

>
Read the contents of "criterium" into a dict with the old value as the
key and the new value as the value and then iterate through the matrix
replacing the values in columns 2 to 4 with criterium.get(current_value,
current_value).

Incidentally, the singular of "criteria" is "criterion" because it's
Greek, not Latin.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to walk up parent directories?

2009-05-04 Thread Matthew Wilson
On Sun 03 May 2009 09:24:59 PM EDT, Ben Finney wrote:
> Not every simple function belongs in the standard library :-)

Thanks for the help with this!  Maybe I'm overestimating how often
people need this walkup function.

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


Re: How to walk up parent directories?

2009-05-04 Thread Diez B. Roggisch
Snorri H wrote:

> On May 4, 5:04 am, Matthew Wilson  wrote:
>> Is there already a tool in the standard library to let me walk up from a
>> subdirectory to the top of my file system?
> 
> 
> Never seen such a standard tool, yet it can be implemented in a way
> like this
> 
> def walkup(path):
> aux = path.rsplit('/')
> while aux != ['']:
> yield reduce(lambda x,y:x+'/'+y,aux)
> aux.pop()
> yield '/'
> 
> Maybe this is not the best way to ascend directories, but it seems to
> work.

It's not working for windows. And using reduce to create a path instead of 

os.sep.join(aux)

seems to be showing off mad functional coding skillz than anything else...

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


Re: Your confirmation is required to join the Python-list mailing list

2009-05-04 Thread Allan Yuan
Hi,
I just wanna know how to set SYSTEM variables and USER variables of windows,
but got no way.

Firstly I thought "os.environ + os.system" may work well, but found no way
to let "os.environ" run to retrive USER variables.

Then I tried win32api, finding the GetEnvironmentVariables() mixing SYSTEM
and USER variables up, and SetEnvironmentVariables() failing to add
variables.

Could you help me, please?
Thanks a lot.
--
http://mail.python.org/mailman/listinfo/python-list


Re: AutoComplete in C++ Editor for Python

2009-05-04 Thread flamz3d
On May 3, 3:14 pm, Dave Angel  wrote:
> flam...@gmail.com wrote:
> > Hello,
> > I am embedding python support in my C++ application and was looking at
> > adding "Intellisense" or "AutoComplete" support.
>
> > I found a way to do it using the "dir" function, but this creates a
> > problem. Here's why. Let's say I have the following code in my editor:
>
> > import sys
> > x = sys
>
> > Now, I would like to get all attributes of the object called 'x'. I
> > can "instrument" the code and add "print dir(x)" at the end,
> > temporarily redirect the python output to a string and execute the
> > code.
>
> > But this is not safe: I do NOT want to execute the code while the user
> > is typing!
>
> > Is there a way to "compile" the python code and get access to the
> > symbol table from that compiled block?
>
> > Did anybody ever implement AutoComplete in a editor for Python?
>
> > cheers.
>
> Several editors for Python support auto-complete, to one extent or
> another.  The only one I have experience with is Komodo.  Komodo runs in
> a separate process, so it doesn't suffer from the problems of having two
> gui event-loops in the same process, and other similar problems.   It
> also won't be executing code that might have side effects in the child
> process.
>
> The downside is that in order to do auto-complete, it has to figure it
> out from other clues.  From the docs, and from reading, and from
> experiementing, I believe that it uses two approaches.  One approach is
> a set of language files which try to describe all the symbols in the
> standard language and library.  They have one for each release (2.4,
> 2.5, ...)  Theoretically, you could add your own for other libraries.  
> Second approach is to parse the code that's visible to it.  That parsing
> is well done, and surprisingly quick, but there are lots of tricks a
> developer might use that can fool it.  For example, wxPython lets you
> import just one symbol, and lots more appear magically.  It's no big
> deal, they have code structured one way, but the interface is very
> different.  Catch is that code completion frequently gets fooled by these.
>
> I'd point out that if you do walk the dictionaries at run time, you'll
> get different results when you do it with nothing running than if you do
> a strictly static analysis.  So some things might only show up if you've
> stepped into the function with the magic going on.
>
> Simplest example I can come up with of something a static analysis won't
> spot:   An instance object    obj   may have some number of attributes
> assigned the the __init__() method.  But it could also have new fields
> added by anyone with a referent into it.
>
> There is a Python parser in module ast.  Perhaps that'd be some help.  
> I've not used it, so can't give you any specifics.
>
> DaveA


I think it might be possible for me to figure out how to do
AutoCompletion using the symtable object. But I am having difficulty
making sense of it.

In my tests, I was use the following Python code:

[code]
import sys
x=sys
[/code]

The idea is to get the type of the variable x

To attempt this, I use the following C code (my editor is written in
C)

symtable* st = Py_SymtableString ( "import sys
\nx=sys,"",Py_single_input);

PyObject *name, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(st->st_symbols, &pos, &name, &value))
{
...
}



Using this code, I can get information like the name of the symbol
(x), but I can't figure out how to get the type. If I knew how to get
this it would solve 99% of my problems :)

Any ideas?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiprocessing.Queue - I want to end.

2009-05-04 Thread Luis Zarrabeitia
On Monday 04 May 2009 04:01:23 am Hendrik van Rooyen wrote:

> This will form a virtual (or real if you have different machines)
> systolic array with producers feeding consumers that feed
> the summary process, all running concurrently.

Nah, I can't do that. The summary process is expensive, but not nearly as 
expensive as the consuming (10 minutes vs. a few hours), and can't be started 
anyway before the consumers are done.

> You only need to keep the output of the consumers in files if
> you need access to it later for some reason. In your case it sounds
> as if you are only interested in the output of the summary.

Or if the summarizing process requires that it is stored on files. Or if the 
consumers naturally store the data on files. The consumers "produce" several 
gigabytes of data, not enough to make it intractable, but enough to not want 
to load them into RAM or transmit it back.

In case you are wondering what the job is: i'm indexing a lot of documents 
with Xapian. The producer reads the [compressed] documents from the hard 
disk, the consumers process it and index it on they own xapian database. When 
they are finished, I merge the databases (the summarizing) and delete the 
partial DBs. I don't need the DBs to be in memory at any time, and xapian 
works with files anyway. Even if I were to use different machines (not worth 
it for a process that will not run very frequently, except at developing 
time), it would be still cheaper to scp the files.

Now, if I only had a third core available to consume a bit faster ...

Regards,

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code works fine except...

2009-05-04 Thread Aahz
In article <8d4ec1df-dddb-469a-99a1-695152db7...@n4g2000vba.googlegroups.com>,
Ross   wrote:
>
>def test_round_robin(players, rounds, courts, doubles = False):
>players = range(players)
>for week in round_robin(players,rounds,courts):
>   if doubles == True:
>   doubles_week = len(week)/2.0
>   byes = doubles_week - courts

Side note: thou shalt indent four spaces, no more, no fewer

For more info, see PEP 8.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-04 Thread Aahz
In article ,
=?ISO-8859-1?Q?Matthias_Gall=E9?=   wrote:
>
>My problem is to replace all occurrences of a sublist with a new element.
>
>Example:
>Given ['a','c','a','c','c','g','a','c'] I want to replace all 
>occurrences of ['a','c'] by 6 (result [6,6,'c','g',6]).

What's your goal?  After you do this once, you cannot repeat the
operation with a different sublist because you are not tracking the
source of the numbers.  You might look into standard compression
algorithms for information about how to accomplish this.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


How is the start of my server monitoring code?

2009-05-04 Thread Echo
I just started a project to monitor servers(load, memory, processes,
etc) via ssh(using paramiko). And I was hoping to get some input on
the design of my project, how pythonic it is, etc. It is quite basic
right now. But it is currently able to get load and memory stats from
any number of servers. I haven't started the logging to a DB or the
GUI for it yet. I also haven't touched on error handling at all
either.

My reasons for making my own server monitoring project:
-It's fun
-Low requirements (only python, paramiko, and pycrypto 1.9+ is required)
-Nothing to install on the servers
-Easy to customize

You can view the code at:
http://github.com/brandonsinger/pywatchlmn/blob/43afb593a891a3d25f3cd9910c5829867bbe229d/monitor.py
The project page is at: http://github.com/brandonsinger/pywatchlmn/tree/master

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


Re: [ANN] regobj - Pythonic object-based access to the Windows Registry

2009-05-04 Thread Glenn Linderman
On approximately 5/3/2009 7:35 AM, came the following characters from 
the keyboard of Ryan Kelly:

Hi All,

  I've just released the results of a nice Sunday's coding, inspired by
one too many turns at futzing around with the _winreg module.  The
"regobj" module brings a convenient and clean object-based API for
accessing the Windows Registry.



Sounds very interesting, Ryan.  Just a couple questions about the 
dictionary interface.




If a subkey is assigned a dictionary, the structure of that dictionary
is copied into the subkey.  Scalar values become key values, while
nested  dictionaries create subkeys:

  >>> HKCU.Software.MyTests = {"val1":7, "stuff":{"a":1,"c":2,"e":3}}
  >>> [v.name for v in HKCU.Software.MyTests.values()]
  ['val1']
  >>> [k.name for k in HKCU.Software.MyTests.subkeys()]
  ['stuff']
  >>> len(HKCU.Software.MyTests.stuff)
  3

Any other value assigned to a subkey will become the default value for
that key (i.e. the value with name ""):

  >>> HKCU.Software.MyTests = "dead parrot"
  >>> HKCU.Software.MyTests[""].data
  u'dead parrot'



I could see how you could map  numbers to DWORD, 2.x str/3.x bytes to 
binary, and 2.x unicode/3.x str to REG_SZ.  But you don't document such 
a translation, so it is unclear exactly what you actually do.  This 
would be somewhat weird in 2.x, though, where str commonly would want to 
map to String rather than Binary.


It seems almost necessary to add an explanation of whatever mapping is 
presently done, to have complete documentation.




Thinking more, I wonder if it is possible to create objects of type 
Value to put in the dictionary to allow specification of multistring and 
expandablestring Registry types, but then the dictionary name would have 
to be redundant with the name attribute in the Value object.  Maybe a 
nameless value type could be invented, with just type and data attributes?


Then the dictionary could be populated with numbers (mapped to DWORD) 
str or unicode items (mapped to String), [3.x only] bytes (mapped to 
Binary), or nameless value objects (which map to their internal types).




This would allow a bidirectional conversion between dictionaries and 
registry keys... when asking for the value of a key, one could return a 
dictionary of nameless value types... and allow iterations over that.


Subkeys could be a tuple with the type of key, and the value of a key 
object.



Well, these are just thoughts.  I don't know if they would increase or 
decrease the Pythonicity of your design, which certainly sounds better 
than using _winreg, to me.



--
Glenn -- http://nevcal.com/
===
A protocol is complete when there is nothing left to remove.
-- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking
--
http://mail.python.org/mailman/listinfo/python-list


Re: replacing numbers in LARGE MATRIX with criterium in 2 columns (a--> b)

2009-05-04 Thread Aahz
In article <68d22002-fc0a-4590-9395-c78b6ee41...@r34g2000vba.googlegroups.com>,
Alexzive   wrote:
>
>I have this matrix [20*4 - but it could be n*4 , with n~100,000] in
>file "EL_list" like this:

Take a look at NumPy
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: IDE for python 2.6 (auto complete)

2009-05-04 Thread Detlev Offenbach
Mike Driscoll wrote:

> On May 4, 10:13 am, Soumen banerjee  wrote:
>> Hello,
>> I have just installed and run python 2.6.2 from the sources available
>> on the website. I notice that SPE (the editor which i used with python
>> 2.5) is not displaying some of the functions new in 2.6 as
>> autocomplete options. Is there any IDE with support for autocomplete
>> in python 2.6 with all the newer functions included?
> 
> Wingware probably does. You should just submit a bug report to Stani
> though. He can probably fix SPE for you.

And eric4 does this as well.

Detlev
-- 
Detlev Offenbach
det...@die-offenbachs.de
--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-04 Thread John O'Hagan
On Mon, 4 May 2009, Francesco Guerrieri wrote:
> On Mon, May 4, 2009 at 3:01 PM, John O'Hagan  wrote:
> > On Mon, 4 May 2009, Matthias Gallé wrote:
> > > Hi.
> > >
> > > My problem is to replace all occurrences of a sublist with a new
> > > element.
> > >
> > > Example:
> > > Given ['a','c','a','c','c','g','a','c'] I want to replace all
> > > occurrences of ['a','c'] by 6 (result [6,6,'c','g',6]).
> >
> > li=['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
> > for i  in range(len(li)):
> >if li[i:i + 2] == ['a', 'c']:
> >li[i:i + 2] = ['6']
> >
> > HTH,
> >
> > John
>
> Beware that you are mutating the list you are iterating over. That could
> lead to some strange bugs (for instance if you replaced the deleted items
> with a longer sequence, the range(len(li)) would still go up to the
> original lenght).
> It is better to modify a new list instead. Eg you could append to a new
> list.
[...]

Quite right, while it happens to work in this particular example, as you and 
MRAB point out, it's generally dangerous (and in fact this one silently and 
uselessly iterates over the last couple of indexes which no longer exist); a 
new list could be created like this:

index=0
newli=[]
while indexhttp://mail.python.org/mailman/listinfo/python-list


Re: Is it better to use threads or fork in the following case

2009-05-04 Thread CTO
> Which brings us backs to the "20 questions"-part of my earlier post. It
> could be, but it could also be that processing takes seconds. Or it takes
> so long that even concurrency won't help. Who knows?

Probably the OP ;)

Geremy Condra

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


Open a dialog from MainWindow - pyQT4 - Beginner :-)

2009-05-04 Thread Florian Wollenschein

Dear folks,

I'm just working on a pyQT4 version of my txt to html converter thc (see 
listick.org for details).


I created the MainWindow with QT Designer and then converted it to .py 
with pyuic4. It works well so far. Then I created a new UI for my 
abtDialog (about dialog for my application). I did the same as with the 
MainWindow, so I have two UIs and two *_ui.py files now. How can I open 
the dialog from my main application class?


Here's part of the code I'm using:

...
self.connect(self.actionAbout,
QtCore.SIGNAL("triggered()"), self.OpenAbout)
...
 def OpenAbout(self):
pass
...

The OpenAbout function should open the dialog. I've already tried a 
abtDialog.show() after creating it via abtDialog = ThcAboutDialog() 
(ThcAboutDialog is the class for this dlg).


Any ideas?

Thanks,
Listick Lorch
http://www.listick.org

PS: Keep in mind that I'm quite a beginner in the field of python and qt...
--
http://mail.python.org/mailman/listinfo/python-list


Personal recommendations for Python and Django on-boarding materials

2009-05-04 Thread Grant Rettke
Hi folks,

>From one developer to another, I am looking for some personal
recommendations on what are the best materials for fast tracking an on-
boarding to Python and Django.

I know how to program, get web apps and OO; this is the audience.

I have found some good recommendations and stuff on Amazon and various
websites, but if I could get some humans vouching for things directly
that would be worth a lot more.

Best wishes,

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


Re: find sublist inside list

2009-05-04 Thread mzdude
On May 4, 9:01 am, Matthias Gallé  wrote:
> bearophileh...@lycos.com wrote:
> > John O'Hagan:
> >> li=['a', 'c', 'a', 'c', 'c', 'g', 'a', 'c']
> >> for i  in range(len(li)):
> >>     if li[i:i + 2] == ['a', 'c']:
> >>         li[i:i + 2] = ['6']
>
> > Oh well, I have done a mistake, it seems.
> > Another solution then:
>
>  'acaccgac'.replace("ac", chr(6))
> > '\x06\x06cg\x06'
>
> > Bye,
> > bearophile
>
> Thanks bearophile and John for your quick answers.
> Unfortunately, the int that can replace a sublist can be > 255, but
> John's answer looks simple and good enough for me. I will use it as a
> starting point.
>

substring isn't limited to 0..255
>>> substring = "\0x%d\0x%d" % (257,257)
>>> 'acaccgac'.replace("ac", substring)
'\x00x257\x00x257\x00x257\x00x257cg\x00x257\x00x257'
--
http://mail.python.org/mailman/listinfo/python-list


improved search algorithm

2009-05-04 Thread grahamdick77
Hi

I have an excel file that is read into python (8000 rows)

from csvimport reader, writer
incsv = reader(open(MY_FILE), dialect='excel')
keys = incsv.next()

There are mixed datatypes.

the last column contains a cumulative frequency running in order
0. to 1. for the 8000 rows

for a loop of 100,000 times I want to take a new random number each
time and find the row with the next biggest cumulative frequency value

Here's my current (pseudo)code:

for 1 to 10

myRand = random.random()
for line in incsv:
if float(line[-1]) > myRand:
resline = []
for item in line:
try:
i = int(item)
except ValueError:
try:
i = float(item)
except ValueError:
i = item
resline.append(i)
#Here we construct a dict of pair values:
#{'ID':18,...
res = dict(zip(keys,resline))
break
else:
continue

  #do some stuff with res




I'm scanning over each line of the csv and deciding which row to
select (100k times) this is just not very efficient

How can i improve this code.
for line in incsv:
if float(line[-1]) > random.random():

I can use numpy etc. whatever
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread bearophileHUGS
Steve Howell:
>two methods with almost identical names, where one function is the public 
>interface and then another method that does most of the recursion.<

Thanks Guido & Walter both Python and D support nested functions, so
in such situations I put the recursive function inside the "public
interface" function/method.

Recursion is a high-level way to represent certain kinds of algorithms
in a short and readable way (when data structures are nested, the most
natural algorithms that work on them are recursive). But in Python
function calls are slow, the maximum level of nested calls is limited
(and it can't grow too much), so this has sometimes forced me to
manually convert recursive functions into iterative ones with a stack.
This is silly for a supposed high-level language. The bad support for
recursivity is one of the few faults of Python.

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


pychecker vs pychecker2

2009-05-04 Thread qhfgva
For my edification I was looking through the source code of
pychecker.  I noticed that there was also a pychecker2 directory
(ubuntu).  The pychecker command line tool points to pychecker (w/out
the 2).  Does anyone know off the top of their head what this second
directory is about?

thanks

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


change some lines from a read file

2009-05-04 Thread utab
Dear all,

I have to change some lines from a template file, which is rather long
to paste here, but I would like to make some parts of some lines
optional with my command line arguments but I could not see this
directly, I can count the line numbers and decide on this basis to
decide the lines to be configured to my will.

More specifically, say, I have a that file includes

this is an example python file to play around
.
.
.
some lines
.
.
.
. -> an option line for example.
.
.
.
-> another option line so on.

and execute the script
./myScript option1 option2

so that the options at correct locations will be written.

Any other options for this simple job that i can improve my Python a
bit as well.

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


Re: improved search algorithm

2009-05-04 Thread MRAB

grahamdic...@gmail.com wrote:

Hi

I have an excel file that is read into python (8000 rows)

from csvimport reader, writer
incsv = reader(open(MY_FILE), dialect='excel')
keys = incsv.next()

There are mixed datatypes.

the last column contains a cumulative frequency running in order
0. to 1. for the 8000 rows

for a loop of 100,000 times I want to take a new random number each
time and find the row with the next biggest cumulative frequency value

Here's my current (pseudo)code:

for 1 to 10

myRand = random.random()
for line in incsv:
if float(line[-1]) > myRand:
resline = []
for item in line:
try:
i = int(item)
except ValueError:
try:
i = float(item)
except ValueError:
i = item
resline.append(i)
#Here we construct a dict of pair values:
#{'ID':18,...
res = dict(zip(keys,resline))
break
else:
continue

  #do some stuff with res




I'm scanning over each line of the csv and deciding which row to
select (100k times) this is just not very efficient

How can i improve this code.
for line in incsv:
if float(line[-1]) > random.random():

I can use numpy etc. whatever


Here's a suggestion:

Construct the dicts for all the rows, stored in a list.

Construct a list of just the cumulative frequencies.

For each random value, use the bisect module to search for the value in
the cumulative frequencies list. This will return an index which you can
then use on your list of dicts.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread Arnaud Delobelle
bearophileh...@lycos.com writes:

> Steve Howell:
>>two methods with almost identical names, where one function is the
>>public interface and then another method that does most of the
>>recursion.<
>
> Thanks Guido & Walter both Python and D support nested functions, so
> in such situations I put the recursive function inside the "public
> interface" function/method.

Yes, this is a common idiom for me:

def public_function(a, b):
def rec():
...
return rec()

E.g, to continue with the factorial toy example (of course for this
particular example and in this particular language, a loop would be more
appropriate):

def fac(n):
def rec(n, acc):
if n <= 1:
return acc
else:
return rec(n - 1, n*acc)
return rec(n, 1)

This is tail recursive, but Python does not optimise tail-calls so there
is not much point.

> Recursion is a high-level way to represent certain kinds of algorithms
> in a short and readable way (when data structures are nested, the most
> natural algorithms that work on them are recursive). But in Python
> function calls are slow, the maximum level of nested calls is limited
> (and it can't grow too much), so this has sometimes forced me to
> manually convert recursive functions into iterative ones with a stack.
> This is silly for a supposed high-level language. The bad support for
> recursivity is one of the few faults of Python.

Bearophile, there is a thread on python-ideas about tail-call
optimization at the moment.

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


Re: change some lines from a read file

2009-05-04 Thread MRAB

utab wrote:

Dear all,

I have to change some lines from a template file, which is rather long
to paste here, but I would like to make some parts of some lines
optional with my command line arguments but I could not see this
directly, I can count the line numbers and decide on this basis to
decide the lines to be configured to my will.

More specifically, say, I have a that file includes

this is an example python file to play around
.
.
.
some lines
.
.
.
. -> an option line for example.
.
.
.
-> another option line so on.

and execute the script
./myScript option1 option2

so that the options at correct locations will be written.

Any other options for this simple job that i can improve my Python a
bit as well.


You could put special markers around the optional parts in the template
file. Your script would remove the markers from around the optional
parts it wants to keep and then remove any remaining unwanted optional
parts and their markers.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread bearophileHUGS
Arnaud Delobelle:
> def fac(n):
>     def rec(n, acc):
>         if n <= 1:
>             return acc
>         else:
>             return rec(n - 1, n*acc)
>     return rec(n, 1)

Right, that's another way to partially solve the problem I was talking
about. (Unfortunately the performance in Python is significantly
lower. I can use that in D).


> Bearophile, there is a thread on python-ideas about tail-call
> optimization at the moment.

Someday I'll have to start following those mailing lists...
But I am not interested in such optimization. It's not going to help
me significantly. Most times I use recursion, I think it can't be
optimized away by simple means (think about a visit to a binary tree).

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


Re: Self function

2009-05-04 Thread Aahz
In article ,
  wrote:
>Arnaud Delobelle:
>> 
>> Bearophile, there is a thread on python-ideas about tail-call
>> optimization at the moment.
>
>Someday I'll have to start following those mailing lists...
>But I am not interested in such optimization. It's not going to help
>me significantly. Most times I use recursion, I think it can't be
>optimized away by simple means (think about a visit to a binary tree).

When have you ever had a binary tree a thousand levels deep?  Consider
how big 2**1000 is...
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"It is easier to optimize correct code than to correct optimized code."
--Bill Harlan
--
http://mail.python.org/mailman/listinfo/python-list


Re: Personal recommendations for Python and Django on-boarding materials

2009-05-04 Thread Arnaud Delobelle
Grant Rettke  writes:

> Hi folks,
>
> From one developer to another, I am looking for some personal
> recommendations on what are the best materials for fast tracking an on-
> boarding to Python and Django.
>
> I know how to program, get web apps and OO; this is the audience.
>
> I have found some good recommendations and stuff on Amazon and various
> websites, but if I could get some humans vouching for things directly
> that would be worth a lot more.
>
> Best wishes,
>
> Grant

I've learnt both Python and Django using the tutorials, the docs and
lots of experimentation.  Django now have a book [1] which might be
useful to read.

[1] http://djangobook.com/

-- 
Arnaud

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


Re: change some lines from a read file

2009-05-04 Thread Anthra Norell

utab wrote:

Dear all,

I have to change some lines from a template file, which is rather long
to paste here, but I would like to make some parts of some lines
optional with my command line arguments but I could not see this
directly, I can count the line numbers and decide on this basis to
decide the lines to be configured to my will.

More specifically, say, I have a that file includes

this is an example python file to play around
.
.
.
some lines
.
.
.
. -> an option line for example.
.
.
.
-> another option line so on.

and execute the script
./myScript option1 option2

so that the options at correct locations will be written.

Any other options for this simple job that i can improve my Python a
bit as well.

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

  
Your description is not explicit enough to convey your intention. If 
your template file is too long to post, post a short representative 
section, an input data sample and a hand-edited sample of the output 
data you want to generate. You will get more and better advice. .


Frederic

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


Re: yet another list comprehension question

2009-05-04 Thread namekuseijin
On May 4, 9:15 am, David Robinow  wrote:
> On Mon, May 4, 2009 at 2:33 AM, namekuseijin
>
>  wrote:
>  ls = [(1,2), (3,4), (5, None), (6,7), (8, None)]
>  [(x,y) for (x,y) in ls if y]
> > [(1, 2), (3, 4), (6, 7)]
>
> Nope. That filters out 0 as well as None. Not what the OP asked for.

True.  I'm still a C programmer at heart I guess.  ah, the flexibility
of 0... ;)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread Tim Wintle
On Mon, 2009-05-04 at 19:51 +0100, Arnaud Delobelle wrote:
> 
> Bearophile, there is a thread on python-ideas about tail-call
> optimization at the moment.

Oooh - haven't noticed that (and don't have time to follow it), but has
anyone seen the results I got a week or so ago from briefly playing with
a couple of simple optimisations:



I was amazed how much you could improve performance by not jumping all
over the stack




signature.asc
Description: This is a digitally signed message part
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread bearophileHUGS
Aahz:
> When have you ever had a binary tree a thousand levels deep?

Yesterday.


>Consider how big 2**1000 is...<

You are thinking just about complete binary trees.
But consider that a topology like a single linked list (every node has
1 child, and they are chained) is a true binary tree still.

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


Re: Code works fine except...

2009-05-04 Thread Ross
On May 4, 12:15 pm, a...@pythoncraft.com (Aahz) wrote:
> In article <8d4ec1df-dddb-469a-99a1-695152db7...@n4g2000vba.googlegroups.com>,
>
> Ross   wrote:
>
> >def test_round_robin(players, rounds, courts, doubles = False):
> >    players = range(players)
> >    for week in round_robin(players,rounds,courts):
> >        if doubles == True:
> >                doubles_week = len(week)/2.0
> >                byes = doubles_week - courts
>
> Side note: thou shalt indent four spaces, no more, no fewer
>
> For more info, see PEP 8.
> --
> Aahz (a...@pythoncraft.com)           <*>        http://www.pythoncraft.com/
>
> "It is easier to optimize correct code than to correct optimized code."
> --Bill Harlan

Yes... I know this. Unfortunately, copy/pasting my code from the IDE
into the google group messes with indentations.
--
http://mail.python.org/mailman/listinfo/python-list


Re: AutoComplete in C++ Editor for Python

2009-05-04 Thread Dave Angel

flam...@gmail.com wrote:

On May 3, 3:14 pm, Dave Angel  wrote:
  

flam...@gmail.com wrote:


Hello,
I am embedding python support in my C++ application and was looking at
adding "Intellisense" or "AutoComplete" support.
  
I found a way to do it using the "dir" function, but this creates a

problem. Here's why. Let's say I have the following code in my editor:
  
import sys

x =ys
  
Now, I would like to get all attributes of the object called 'x'. I

can "instrument" the code and add "print dir(x)" at the end,
temporarily redirect the python output to a string and execute the
code.
  
But this is not safe: I do NOT want to execute the code while the user

is typing!
  
Is there a way to "compile" the python code and get access to the

symbol table from that compiled block?
  
Did anybody ever implement AutoComplete in a editor for Python?
  
cheers.
  

Several editors for Python support auto-complete, to one extent or
another.  The only one I have experience with is Komodo.  Komodo runs in
a separate process, so it doesn't suffer from the problems of having two
gui event-loops in the same process, and other similar problems.   It
also won't be executing code that might have side effects in the child
process.

The downside is that in order to do auto-complete, it has to figure it
out from other clues.  From the docs, and from reading, and from
experiementing, I believe that it uses two approaches.  One approach is
a set of language files which try to describe all the symbols in the
standard language and library.  They have one for each release (2.4,
2.5, ...)  Theoretically, you could add your own for other libraries.  
Second approach is to parse the code that's visible to it.  That parsing

is well done, and surprisingly quick, but there are lots of tricks a
developer might use that can fool it.  For example, wxPython lets you
import just one symbol, and lots more appear magically.  It's no big
deal, they have code structured one way, but the interface is very
different.  Catch is that code completion frequently gets fooled by these.

I'd point out that if you do walk the dictionaries at run time, you'll
get different results when you do it with nothing running than if you do
a strictly static analysis.  So some things might only show up if you've
stepped into the function with the magic going on.

Simplest example I can come up with of something a static analysis won't
spot:   An instance objectobj   may have some number of attributes
assigned the the __init__() method.  But it could also have new fields
added by anyone with a referent into it.

There is a Python parser in module ast.  Perhaps that'd be some help.  
I've not used it, so can't give you any specifics.


DaveA




I think it might be possible for me to figure out how to do
AutoCompletion using the symtable object. But I am having difficulty
making sense of it.

In my tests, I was use the following Python code:

[code]
import sys
x=s
[/code]

The idea is to get the type of the variable x

To attempt this, I use the following C code (my editor is written in
C)

symtable* st =y_SymtableString ( "import sys
\nx=s,"",Py_single_input);

PyObject *name, *value;
Py_ssize_t pos =;
while (PyDict_Next(st->st_symbols, &pos, &name, &value))
{
...
}



Using this code, I can get information like the name of the symbol
(x), but I can't figure out how to get the type. If I knew how to get
this it would solve 99% of my problems :)

Any ideas?

  
There's a type() function as a builtin.  It returns a string showing the 
type of any object you pass it.


I have my doubts about the 99%;   I'd say more like 1%.  Objects have to 
be instantiated to have a type, there's no declarations.  And a function 
has a type, but in order to see the result type through introspection, 
you'd have to run it.  And before you could do that, you'd have to guess 
its parameter types.  And hope it didn't have any serious side effects.


I can't help with the C++ code, since I've never written any that use 
the Python runtime, but perhaps you can experiment with a Python 
version, till you see what is and is-not possible.  Look at the 
following in Python:

import sys

dict = sys.__dict__
for sym in dict:
   print "**", sym, type(dict[sym]), str(dict[sym])


Now, for many of these sym values, sym.__dict__  could similarly be 
analyzed.  So you might write a recursive generator that gave you a list 
of symbols.



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


Re: IDE for python 2.6 (auto complete)

2009-05-04 Thread Dave Angel

Soumen banerjee wrote:

Hello,
I have just installed and run python 2.6.2 from the sources available
on the website. I notice that SPE (the editor which i used with python
2.5) is not displaying some of the functions new in 2.6 as
autocomplete options. Is there any IDE with support for autocomplete
in python 2.6 with all the newer functions included?

  

No idea if it's "all", but Komodo 5.1.1 has been updated for 2.6.


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


Re: How to walk up parent directories?

2009-05-04 Thread Dave Angel



Matthew Wilson wrote:

On Sun 03 May 2009 09:24:59 PM EDT, Ben Finney wrote:
  

Not every simple function belongs in the standard library :-)



Thanks for the help with this!  Maybe I'm overestimating how often
people need this walkup function.

Matt

  

Look at os.path.normpath(os.path.join( name, ".."))


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


Re: Threaded alternatives to smtplib?

2009-05-04 Thread Piet van Oostrum
> Alex Jurkiewicz  (AJ) wrote:

>AJ> def threadProcessRecipient():
[snip]
>AJ> if __name__ == '__main__':
>AJ>THREADS = []
>AJ>for i in range(CONCURRENCY):
>AJ>THREADS.append(threading.Thread(target=threadProcessRecipient))
>AJ>for thread in THREADS:
>AJ>thread.run()

You should use thread.start(), not thread.run(). When you use run(), it
will be sequential execution, as you experience. With start() you get
concurrency
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: change some lines from a read file

2009-05-04 Thread norseman

Anthra Norell wrote:

utab wrote:

Dear all,

I have to change some lines from a template file, which is rather long
to paste here, but I would like to make some parts of some lines
optional with my command line arguments but I could not see this
directly, I can count the line numbers and decide on this basis to
decide the lines to be configured to my will.

More specifically, say, I have a that file includes

this is an example python file to play around
.
.
.
some lines
.
.
.
. -> an option line for example.
.
.
.
-> another option line so on.

and execute the script
./myScript option1 option2

so that the options at correct locations will be written.

Any other options for this simple job that i can improve my Python a
bit as well.

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

  
Your description is not explicit enough to convey your intention. If 
your template file is too long to post, post a short representative 
section, an input data sample and a hand-edited sample of the output 
data you want to generate. You will get more and better advice. .


Frederic

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



===

Assuming the total number of changes is not large,

put OPTION1 where you want it to go in the text
put OPTION2  (same)

import sys

if len(sys.argv) >1:
  OPTION1 = sys.argv[1]
else:
  OPTION1 = "some default stuff"

similar for OPTION2
if len(sys.argv) >2:
  like above
and any others

print section1+OPTION1+section2+OPTION2

   or
  just using the line count  (in place of "print sect..")
line_number= 0
for i in template:
  if line_number matches line number to place Opt1
print OPTION1
  elif line_number matches v2
print OPTION2
and so forth
  else:
print i   (line from template NOT being changed)
  line_number += Line_number

you can group line number and replacement on command line
runprogram (43,"use this instead") (56,
and parse inside program before opening template

one thing to watch out for:
   for i in file...  often returns just one character at a time, 
meaning you will have to track EOL's yourself  OR
import the readline and use it to stand a better chance of getting what 
you expect from a read file function.



Today: 20090504
Logic outline, No particular version

HTH

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


Re: change some lines from a read file

2009-05-04 Thread norseman

Anthra Norell wrote:

utab wrote:

Dear all,

I have to change some lines from a template file, which is rather long
to paste here, but I would like to make some parts of some lines
optional with my command line arguments but I could not see this
directly, I can count the line numbers and decide on this basis to
decide the lines to be configured to my will.

More specifically, say, I have a that file includes

this is an example python file to play around
.
.
.
some lines
.
.
.
. -> an option line for example.
.
.
.
-> another option line so on.

and execute the script
./myScript option1 option2

so that the options at correct locations will be written.

Any other options for this simple job that i can improve my Python a
bit as well.

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

  
Your description is not explicit enough to convey your intention. If 
your template file is too long to post, post a short representative 
section, an input data sample and a hand-edited sample of the output 
data you want to generate. You will get more and better advice. .


Frederic

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



===

Assuming the total number of changes is not large,

put OPTION1 where you want it to go in the text
put OPTION2  (same)

import sys

if len(sys.argv) >1:
  OPTION1 = sys.argv[1]
else:
  OPTION1 = "some default stuff"

similar for OPTION2
if len(sys.argv) >2:
  like above
and any others

print section1+OPTION1+section2+OPTION2

   or
  just using the line count  (in place of "print sect..")
line_number= 0
for i in template:
  if line_number matches line number to place Opt1
print OPTION1
  elif line_number matches v2
print OPTION2
and so forth
  else:
print i   (line from template NOT being changed)
  line_number += Line_number

you can group line number and replacement on command line
runprogram (43,"use this instead") (56,
and parse inside program before opening template

one thing to watch out for:
   for i in file...  often returns just one character at a time, 
meaning you will have to track EOL's yourself  OR
import the readline and use it to stand a better chance of getting what 
you expect from a read file function.



Today: 20090504
Logic outline, No particular version

HTH

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


Re: Self function

2009-05-04 Thread Chris Rebert
On Mon, May 4, 2009 at 1:25 PM,   wrote:
> Aahz:
>> When have you ever had a binary tree a thousand levels deep?
>
> Yesterday.
>
>
>>Consider how big 2**1000 is...<
>
> You are thinking just about complete binary trees.
> But consider that a topology like a single linked list (every node has
> 1 child, and they are chained) is a true binary tree still.

And who in their right mind would not use a *self-balancing* binary
tree in that situation?

Cheers,
Chris
-- 
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there is any way to send messages to chunk of emails ID's concurrently using smptlib

2009-05-04 Thread Piet van Oostrum
> gganesh  (g) wrote:

>g> Hi friends,
>g> I suppose sendmail() can send mails one by one ,how to send mails
>g> concurrently ,
>g> It would be very grateful,if someone could point out a solution.

There is a discussion about this in the thread `Threaded alternatives to
smtplib?' 
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: SYSTEM and USER environment (was Your confirmation is required to join the Python-list mailing list)

2009-05-04 Thread Dave Angel

Allan Yuan wrote:

Hi,
I just wanna know how to set SYSTEM variables and USER variables of windows,
but got no way.

Firstly I thought "os.environ + os.system" may work well, but found no way
to let "os.environ" run to retrive USER variables.

Then I tried win32api, finding the GetEnvironmentVariables() mixing SYSTEM
and USER variables up, and SetEnvironmentVariables() failing to add
variables.

Could you help me, please?
Thanks a lot.

  
First, you need to put a meaningful subject line on a query to the 
list.  Hopefully you also did the confirmation, so that you'll actually 
be getting the list emails.


Next, your problem.  SYSTEM and USER variables are a uniquely Windows 
concept, and as far as I know, have no direct counterpart in Python.  
These are really just names used in the Control Panel applet to refer to 
two sections of the registry which are used to define which environment 
variables a task will start with, if the task is started directly from 
Explorer.  Tasks that are started by other tasks (eg. the command line) 
get environment variables as defined by the parent.


So, there are at least three obvious ways a process gets started.  One 
is by explorer, in which case it gets the environment described above.  
Two is by a DOS box, in which case it gets the environment variables 
according to the rules of the CMD shell.  And third is from an arbitrary 
3rd party process, in which case it's up to that developer.


So, which are you trying to change?  I'm suspecting you're interested in 
the Explorer version, for example that launches a program from a 
shortcut on the desktop, or via an association with a particular file 
extension.  i don't know which registry variables are involved, but 
there are two registry keys,
Try:hklm/SYSTEm/CurrentControlSet/Control/Session 
Manager/Environmentfor the SYSTEM environment variables

  and hkcu/Environment for the USER environment variables

Experiment first with REGEDIT, then when you get the behavior you want,  
look up module _winreg  (or winreg in Python 3.0) to do it 
programmatically.  Notice that existing DOS boxes won't see these new 
variables, only things launched by Explorer or the equivalent.


It's also possible you just want to set environment variables for a 
particular DOS box session.  In that case, use a .BAT or .CMD file, in 
which a SET statement tells the shell what values to use next time it 
launches.



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


Re: Self function

2009-05-04 Thread Arnaud Delobelle
bearophileh...@lycos.com writes:

> Aahz:
>> When have you ever had a binary tree a thousand levels deep?
>
> Yesterday.
>
>
>>Consider how big 2**1000 is...<
>
> You are thinking just about complete binary trees.
> But consider that a topology like a single linked list (every node has
> 1 child, and they are chained) is a true binary tree still.

In that case the following would not grow the stack, given tail-call
optimization:

def visit(node):
print 'visiting', node
if node.right is None:
return visit(node.left)
if node.left is not None:
visit(node.left)
return visit(node.right)

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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-05-04 Thread Rhodri James
On Mon, 04 May 2009 15:25:44 +0100, Antoon Pardon  
 wrote:


On 2009-04-24, Steven D'Aprano   
wrote:

On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:


Hello,

I'm trying to do a if statement with a function inside it. I want to  
use

that variable inside that if loop , without defining it.

def Test():
return 'Vla'

I searching something like this:

if (t = Test()) == 'Vla':
print t # Vla

or

if (t = Test()):
print t # Vla


Fortunately, there is no way of doing that with Python. This is one
source of hard-to-debug bugs that Python doesn't have.


I think this is an unfortunate consequence of choosing '=' for the
assignment. They could have chosen an other token to indicate an
assignment one that would have made the difference between an
assignment and a comparison more visually different and thus
bugs by using one while needing the other less hard to track
down.


What token could be used and still be meaningful, though?  Algol
used ":=", which has most of the same problems as "=" (more, in my
opinion, since it fools the eye more easily if you're scanning
printed code quickly).  Easily constructed arrows like "<=" or
"<-" collide with different comparators.  About all that's left
that even vaguely implies assignment is "~", and it's no better.

--
Rhodri James *-* Wildebeeste Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: find sublist inside list

2009-05-04 Thread Gabriel Genellina

En Mon, 04 May 2009 15:12:41 -0300, mzdude  escribió:


substring isn't limited to 0..255

substring = "\0x%d\0x%d" % (257,257)
'acaccgac'.replace("ac", substring)

'\x00x257\x00x257\x00x257\x00x257cg\x00x257\x00x257'


This isn't what you think it is. Look carefully:

py> substring = "\0x%d\0x%d" % (257,257)
py> len(substring)
10
py> list(substring)
['\x00', 'x', '2', '5', '7', '\x00', 'x', '2', '5', '7']

--
Gabriel Genellina

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


Re: Self function

2009-05-04 Thread Terry Reedy

bearophileh...@lycos.com wrote:


Another possible syntax:

def fact(n):
return 1 if n <= 1 else n * return(n - 1)

But I guess most people don't see this problem as important&common
enough to justify changing the language.


Actually, I would like a way to refer to the current function from 
inside a function.  but I would like support in the language, so that 
the compiler patched the code after the function object is created to 
directly refer to the function object (or can the code object call the 
code object?) without any name lookup at all. [An possible objection to 
doing this is that the code might no longer be valid if used to make 
another function object, but I think this is so rare at to hardly worry 
about.] Your initial post seemed to be about a hackish work around that 
looked to me to make as much trouble as it saves.  So I did not respond.


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


Re: find sublist inside list

2009-05-04 Thread Terry Reedy

Matthias Gallé wrote:

Hi.

My problem is to replace all occurrences of a sublist with a new element.

Example:
Given ['a','c','a','c','c','g','a','c'] I want to replace all 
occurrences of ['a','c'] by 6 (result [6,6,'c','g',6]).


If I do this with string ('acaccgac') I have the advantage of all the 
'find' functions, but perfomance is bad and some extra care must be 
taken if one element consist of more then one character (case of 11 for 
example)


So I really would like to work with lists straightforward, but I could 
not found anything to search a sublist inside a list.

Any propositions for a simple solution?


For a mutable homogenous array, consider the array module.
Any algorithm that applies to a sequence of chars can be adjusted to 
other sequences.  For the above case, remember than you can easily 
filter None out of a sequence.  IE, replace 'a','c' with 6, None and 
then filter when done.


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


exit a program gracefully

2009-05-04 Thread Robert . T . Lynch
In a python program I ask if the user wants to continue.  If they answer 
'no', what options do I have to halt execution?  I can put the rest of the 
code inside an "if bContinue:" block, but that seems awkward.  I have 
looked at raising an exception, and perhaps this is the preferred method, 
but it seems daunting to my non-OOP eyes.  Thanks -- Rob--
http://mail.python.org/mailman/listinfo/python-list


Re: exit a program gracefully

2009-05-04 Thread Chris Rebert
On Mon, May 4, 2009 at 3:02 PM,   wrote:
>
> In a python program I ask if the user wants to continue.  If they answer
> 'no', what options do I have to halt execution?  I can put the rest of the
> code inside an "if bContinue:" block, but that seems awkward.  I have looked
> at raising an exception, and perhaps this is the preferred method, but it
> seems daunting to my non-OOP eyes.  Thanks -- Rob

There's the C-like:
from sys import exit
exit(return_code)

Or if you prefer exceptions, the standard way is:
raise SystemExit

Cheers,
Chris
-- 
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: if statement, with function inside it: if (t = Test()) == True:

2009-05-04 Thread MRAB

Rhodri James wrote:
On Mon, 04 May 2009 15:25:44 +0100, Antoon Pardon 
 wrote:


On 2009-04-24, Steven D'Aprano  
wrote:

On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:


Hello,

I'm trying to do a if statement with a function inside it. I want to 
use

that variable inside that if loop , without defining it.

def Test():
return 'Vla'

I searching something like this:

if (t = Test()) == 'Vla':
print t # Vla

or

if (t = Test()):
print t # Vla


Fortunately, there is no way of doing that with Python. This is one
source of hard-to-debug bugs that Python doesn't have.


I think this is an unfortunate consequence of choosing '=' for the
assignment. They could have chosen an other token to indicate an
assignment one that would have made the difference between an
assignment and a comparison more visually different and thus
bugs by using one while needing the other less hard to track
down.


What token could be used and still be meaningful, though?  Algol
used ":=", which has most of the same problems as "=" (more, in my
opinion, since it fools the eye more easily if you're scanning
printed code quickly).  Easily constructed arrows like "<=" or
"<-" collide with different comparators.  About all that's left
that even vaguely implies assignment is "~", and it's no better.


If you're not limited to ASCII then there's '←' (U+2190, 'LEFTWARDS
ARROW'). It's a little too late now, though.
--
http://mail.python.org/mailman/listinfo/python-list


Re: AutoComplete in C++ Editor for Python

2009-05-04 Thread Scott David Daniels

flam...@gmail.com wrote:

... Using this code, I can get information like the name of the symbol
(x), but I can't figure out how to get the type. If I knew how to get
this it would solve 99% of my problems :)


If Python were statically typed, you might be correct.
A _value_ in python has a type, not a variable.  so, you can do:
   some_list = []
   for a in None, True, 1, 1.0, 3.1j, 'text', u'text':
   some_list.append(a)
   print some_list
and you will see something like:
[None, True, 1, 1.0, 3.1001j, 'text', u'text']
That is, a has the type of its current value.
any kind of object can be stored in any variable.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: exit a program gracefully

2009-05-04 Thread MRAB

robert.t.ly...@seagate.com wrote:


In a python program I ask if the user wants to continue.  If they answer 
'no', what options do I have to halt execution?  I can put the rest of 
the code inside an "if bContinue:" block, but that seems awkward.  I 
have looked at raising an exception, and perhaps this is the preferred 
method, but it seems daunting to my non-OOP eyes.  Thanks -- Rob



What is the overall structure of the program? What happens if the user
wants to continue? If you're in a loop then you can just use 'break' to
leave the loop.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Most Basic Question Ever - please help

2009-05-04 Thread seanm . py
On May 3, 12:22 am, CM  wrote:
> On May 2, 4:36 pm, seanm...@gmail.com wrote:
>
>
>
> > I am going to try posting here again with more detail to see if I can
> > finally get my first program to work.
>
> > I am working on a MacBook Pro with OS X 10.4.11. I opened a new window
> > in IDLE to create a file. The file had only one line of code and was
> > saved as module1.py. I saved it to Macintosh HD. The one line of code
> > in the file is copied below:
>
> > print 'Hello module world!'
>
> > I closed the file and tried to run it in IDLE and Terminal, but I have
> > had no success. I'll paste my commands and the error messages below
> > (for IDLE, then Terminal). Any help would be very much appreciated. I
> > feel like the marathon just started and I've fallen flat on my face.
> > Thanks.
>
> > IDLE 2.6.2>>> python module1.py
>
> > SyntaxError: invalid syntax
>
> > sean-m-computer:~ seanm$ python
> > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39)
> > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
> > Type "help", "copyright", "credits" or "license" for more information.>>> 
> > python module1.py
>
> >   File "", line 1
> >     python module1.py
> >                  ^
> > SyntaxError: invalid syntax
>
> Sean, also, keep in mind you can use IDLE to run
> your scripts.  After you have saved a script/program,
> there is an option for Run in the menu, and then under
> that, Run Module.  The output of the script will be
> sent to IDLE window indicated as the Python shell.
> You can also just test code directly from within
> that shell, though for multi-line programs, it is
> easier within the composing window.
>
> I suggest you sign up for the Python tutor 
> list:http://mail.python.org/mailman/listinfo/tutor
>
> And you can search through their big archive of
> questions and answers here:http://www.nabble.com/Python---tutor-f2981.html
>
> The tutors there are great and super-helpful, and
> will field any level of question but are particularly
> good for absolute beginners.
>
> Here is a tutorial on using 
> IDLE:http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
>
> And here is a very good general programming tutorial online
> book, focusing on Python:http://www.freenetpages.co.uk/hp/alan.gauld/
>
> Good luck!
> Che

Thanks Che! The explaination and links are much appreciated. -Sean
--
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] regobj - Pythonic object-based access to the Windows Registry

2009-05-04 Thread Ryan Kelly

> >   I've just released the results of a nice Sunday's coding, inspired by
> > one too many turns at futzing around with the _winreg module.  The
> > "regobj" module brings a convenient and clean object-based API for
> > accessing the Windows Registry.
>
> Sounds very interesting, Ryan.  Just a couple questions about the 
> dictionary interface.

Thanks for you interest and suggestions, a couple of quick points below.

> I could see how you could map  numbers to DWORD, 2.x str/3.x bytes to 
> binary, and 2.x unicode/3.x str to REG_SZ.  But you don't document such 
> a translation, so it is unclear exactly what you actually do.  This 
> would be somewhat weird in 2.x, though, where str commonly would want to 
> map to String rather than Binary.
> 
> It seems almost necessary to add an explanation of whatever mapping is 
> presently done, to have complete documentation.

I guess I just ran out of steam on the documentation front :-)

Currently it maps integers to DWORD and anything else to REG_SZ.  The
idea of having a distinct Value class is to allow a more nuanced mapping
to be developed, but I haven't got down to the details of that yet - my
current application only requires REG_SZ.

> Thinking more, I wonder if it is possible to create objects of type 
> Value to put in the dictionary to allow specification of multistring and 
> expandablestring Registry types, but then the dictionary name would have 
> to be redundant with the name attribute in the Value object.  Maybe a 
> nameless value type could be invented, with just type and data attributes?

It certainly is, using syntax like:

  HKCU.foo.bar["key"] = Value("%SYSTEMROOT%/mydir",type=REG_EXPAND_SZ)}

Putting a nameless Value() instance in the initialisation dictionary
should also work (but as you note, there's no documentation or tests for
this yet...)


  Cheers,

 Ryan



-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
r...@rfk.id.au|  http://www.rfk.id.au/ramblings/gpg/ for details



signature.asc
Description: This is a digitally signed message part
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread Scott David Daniels

Arnaud Delobelle wrote:

In that case the following would not grow the stack, given tail-call
optimization:

def visit(node):
print 'visiting', node
if node.right is None:
return visit(node.left)
if node.left is not None:
visit(node.left)
return visit(node.right)


Or (without TCO):
def visit(node):
while node is not None:
print 'visiting', node
if node.right is None:
node = node.left
else:
if node.left is not None:
visit(node.left)
node = node.right

Not so hard, really.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: exit a program gracefully

2009-05-04 Thread Gabriel Genellina

En Mon, 04 May 2009 19:14:53 -0300, Chris Rebert escribió:

On Mon, May 4, 2009 at 3:02 PM,   wrote:



In a python program I ask if the user wants to continue.  If they answer
'no', what options do I have to halt execution?  I can put the rest of  
the
code inside an "if bContinue:" block, but that seems awkward.  I have  
looked
at raising an exception, and perhaps this is the preferred method, but  
it

seems daunting to my non-OOP eyes.  Thanks -- Rob


There's the C-like:
from sys import exit
exit(return_code)

Or if you prefer exceptions, the standard way is:
raise SystemExit


I prefer to put the code inside a function, and just `return` earlier.
Having a sys.exit() in the middle of a function means that it's not  
reusable; I usually have a single exit() at the end.



def do_work():
  do some work
  ask the user
  if not continue:
return 0
  do more work
  return 0

if __name__=='__main__':
  try: sts = do_work()
  except: sts = 1, log exception
  sys.exit(sts)

--
Gabriel Genellina

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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-05-04 Thread Terry Reedy

Antoon Pardon wrote:

On 2009-04-24, Steven D'Aprano  wrote:

On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:


Hello,

I'm trying to do a if statement with a function inside it. I want to use
that variable inside that if loop , without defining it.

def Test():
return 'Vla'

I searching something like this:

if (t = Test()) == 'Vla':
print t # Vla

or

if (t = Test()):
print t # Vla
Fortunately, there is no way of doing that with Python. 


There is a way to do something close.

def x(v):
x.val = v
return v

if x(3)==3:
print('x.val is ', x.val)
# prints
x.val is  3

In OP's case, condition is "x(Test()) == 'Vla'"


This is one  source of hard-to-debug bugs that Python doesn't have.


I think this is an unfortunate consequence of choosing '=' for the
assignment.


Actually, is is a consequence of making assignment a statement rather 
than an expression.  And that is because if assignment were an 
expression, the new name would have to be quoted.  Or there would have 
to be a special exception to the normal expression evaulation rule.  In 
other words, the problems one sees in a pure expression language.  Note 
that C, for instance, which has such a special exception, does not, last 
I knew, allow a,b = 1,2.


The solution for this use case is to encapsulate the binding within a 
function.  The above is one possible example.  One could use a pocket 
class instead of a pocket function.  Or


def set_echo(name, val):
  globals()[name] = val
  return val

if set_echo('t', Test()) == 'Vla': print t ...

Terry Jan Reedy


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


Re: if statement, with function inside it: if (t = Test()) == True:

2009-05-04 Thread Scott David Daniels

MRAB wrote:

If you're not limited to ASCII then there's '←' (U+2190, 'LEFTWARDS
ARROW'). It's a little too late now, though.

Well, if you are old enough, that was the ASCII graphic for the
character now printed as '_' (ASCII), and SAIL used it for assignment
statements, causing much consternation when our source code displayed
funny on new-fangled terminals.  So, just an unfortunate setting on
the time machine is the basic flaw.

--Scott David Daniels
@Acm.Org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Self function

2009-05-04 Thread Carl Banks
On May 4, 1:25 pm, bearophileh...@lycos.com wrote:
> Aahz:
>
> > When have you ever had a binary tree a thousand levels deep?
>
> Yesterday.
>
> >Consider how big 2**1000 is...<
>
> You are thinking just about complete binary trees.
> But consider that a topology like a single linked list (every node has
> 1 child, and they are chained) is a true binary tree still.

1. Singly-linked lists can and should be handled with iteration.  All
recursion does it make what you're doing a lot less readable for
almost all programmers.

2. You should be using a Python list anyway.


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


  1   2   >