Biggles on Windows with python2.5

2008-04-04 Thread Charlie
Has anyone installed a version of biggles on Windows with python 2.5?

The Martin Lamar version for python 2.3 was a big help, but I finally 
upgraded to python 2.5 and I am having trouble with the biggles build.

Thanks,
Charlie



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


Re: ANN: pry unit testing framework

2008-04-04 Thread Kay Schluehr
On 2 Apr., 06:38, Aldo Cortesi <[EMAIL PROTECTED]> wrote:
> Hi Ben,
>
> > > We are happy to announce the first release of Pry, a unit testing
> > > framework.
>
> > Thanks for the announcement, and for the software.
>
> > If Pry is already incompatible with xUnit (i.e. Python's 'unittest'),
> > could we please have names that adhere to the Python style guide
> > ?
>
> > In particular the method names 'setUp', 'setUpAll', 'tearDown',
> > 'tearDownAll' don't comply with the style guide. Compliant names for
> > those methods would be 'set_up', 'set_up_all', etc.
>
> Keeping fixture setUp and tearDown names the same makes the transition
> from unittest to pry easier. At the moment, converting to pry is very
> simple - inherit your suites from AutoTree, rewrite tests to use
> assertions, and then instantiate your suites at the end of the module.
> Voila! You have a nice command-line interface, coverage analysis, and
> an easy path to saner, better-engineered unit tests.

But you could have added the integration of code coverage and other
helpful features with unittest as a conservative extension giving
everyone a chance to use it directly with existing tests instead of
forcing them to rewrite their tests for bike shading purposes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: *.py source file surprisingly deleted with Pydev/Eclipse. Who else experienced this ?

2008-04-04 Thread Alex9968
Gabriel Genellina wrote:
> En Fri, 04 Apr 2008 15:46:48 -0300, Alex9968 <[EMAIL PROTECTED]>  
> escribió:
>   
>> Nebur wrote:
>> 
>
>   
>>> No, I can't reproduce it, and I don't know whom to blame (Pydev?
>>> Eclipse ? The File System ? A Virus that only 2 times in half a year
>>> deletes a single file I'm busy working with, and seems to do nothing
>>> else? Myself beeing schizophrenic ??)
>>>   
>
>   
>> A virus created to remind you 2 times in half a year of the importance
>> of backup operations ;-) . I'm joking. I don't know what is this, but
>> I'm interested. Because my files won't be restorable from version
>> control :-(
>> 
>
> Then implement it! It's not so difficult, less if you're the only one  
> working on the files.
Implement what? The virus? I haven't said that I'm interested in virus, 
I meant I'd like to know WHAT is this
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TKinter, buttonwidget response problem(1) and all btns the same size(2)!

2008-04-04 Thread skanemupp
am i not doing that then? did u look at the code? where do i add the
bind if this:
btnDisplay = Button(self, text="1", command=self.Display)
btnDisplay.grid(row=3, column=0, padx=5, pady=5)

is not enough?



def Display(self, event_obj):
button = event_obj.widget
text = button.cget("text")

if text=="1":
print 1



i get this exception so i need to pass another argument? im passing 2
no?

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
TypeError: Display() takes exactly 2 arguments (1 given)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TKinter, buttonwidget response problem(1) and all btns the same size(2)!

2008-04-04 Thread Gabriel Genellina
En Sat, 05 Apr 2008 02:02:45 -0300, <[EMAIL PROTECTED]> escribió:

> one thing i dont rally get, i ahve to add my_button.bind() somewhere?
> i changed the stuff u said though and i get this error(the program
> executes though and i can press the buttons):

Either use command, or bind. command requires a function with no  
parameters (or a bound method with self alone). bind uses a function with  
a single parameter, the event (or a bound method with self and event  
parameters).

See the Tkinter book:
http://www.effbot.org/tkinterbook/tkinter-events-and-bindings.htm
http://www.effbot.org/tkinterbook/button.htm

-- 
Gabriel Genellina

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


Re: variable scope in list comprehensions

2008-04-04 Thread Piotr Sobolewski
Duncan Booth wrote:

> For the OP, in some languages (e.g. C) 'for' loops typically calculate
> the value of the loop control variable based on some expression
> involving the previous value. Python isn't like that. In Python the data
> used to compute the next value is stored internally: you cannot access
> it directly.

Great! Now everything is clear.

Thanks!

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


Re: Pickle to Source - Gabriel Genellina?

2008-04-04 Thread Gabriel Genellina
En Fri, 04 Apr 2008 22:47:47 -0300, $P!D3R DelSol <[EMAIL PROTECTED]>  
escribió:

> I found this 3 year old message asking about doing the same exact thing  
> I am trying to do. This is one wheel I REALLY don't want to re-invent.   
> Can anyone point me to code that does this?
>
>> I want to convert from pickle format to python source code. That is,
>> given an existing pickle, I want to produce a textual representation
>> which, when evaluated, yields the original object (as if I had
>> unpickled the pickle).

See the answer from J P Calderone on that thread about aot in Twisted,  
that's the only thing I know of.
I finally used an XML representation, somewhat legible by humans.

-- 
Gabriel Genellina

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


Re: TKinter, buttonwidget response problem(1) and all btns the same size(2)!

2008-04-04 Thread skanemupp
On 5 Apr, 07:02, [EMAIL PROTECTED] wrote:
> On 5 Apr, 05:57, [EMAIL PROTECTED] wrote:
>
>
>
> > On 5 Apr, 05:26, 7stud <[EMAIL PROTECTED]> wrote:
>
> > > On Apr 4, 7:06 pm, [EMAIL PROTECTED] wrote:
>
> > > > 1st question:
>
> > > > when i run this program 1 will be printed into the interpreter when i
> > > > run it BUT without me clicking the actual button.
> > > > when i then click the button "1", nothing happens.
>
> > > > obv i dont want any output when i dont push the button but i want it
> > > > when i do.
>
> > > > what am i doing wrong here?
>
> > > > 2nd question:
>
> > > > i want all the buttons to have the same size. i thought i should use
> > > > row/columnspan but i dont get that to work.
> > > > how should i do?
>
> > > > [code]
> > > > #! /usr/bin/env python
> > > > from Tkinter import *
> > > > import tkMessageBox
>
> > > > class GUIFramework(Frame):
> > > > """This is the GUI"""
>
> > > > def __init__(self,master=None):
> > > > """Initialize yourself"""
>
> > > > """Initialise the base class"""
> > > > Frame.__init__(self,master)
>
> > > > """Set the Window Title"""
> > > > self.master.title("Calculator")
>
> > > > """Display the main window"
> > > > with a little bit of padding"""
> > > > self.grid(padx=10,pady=10)
> > > > self.CreateWidgets()
>
> > > > def CreateWidgets(self):
>
> > > > self.enText = Entry(self)
> > > > self.enText.grid(row=0, column=0, columnspan=8, padx=5,
> > > > pady=5)
>
> > > > self.enText = Entry(self)
> > > > self.enText.grid(row=1, column=0, columnspan=8, padx=5,
> > > > pady=5)
>
> > > > self.btnDisplay = Button(self, text="1",
> > > > command=self.Display(1))
> > > > self.btnDisplay.grid(row=3, column=0, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="2", default=ACTIVE)
> > > > self.btnDisplay.grid(row=3, column=1, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="3", default=ACTIVE)
> > > > self.btnDisplay.grid(row=3, column=2, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="+", default=ACTIVE)
> > > > self.btnDisplay.grid(row=3, column=3, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="4", default=ACTIVE)
> > > > self.btnDisplay.grid(row=4, column=0, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="5", default=ACTIVE)
> > > > self.btnDisplay.grid(row=4, column=1, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="6", default=ACTIVE)
> > > > self.btnDisplay.grid(row=4, column=2, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="-", default=ACTIVE)
> > > > self.btnDisplay.grid(row=4, column=3, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="7", default=ACTIVE)
> > > > self.btnDisplay.grid(row=5, column=0, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="8", default=ACTIVE)
> > > > self.btnDisplay.grid(row=5, column=1, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="9", default=ACTIVE)
> > > > self.btnDisplay.grid(row=5, column=2, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="*", default=ACTIVE)
> > > > self.btnDisplay.grid(row=5, column=3, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="0", default=ACTIVE)
> > > > self.btnDisplay.grid(row=6, column=0, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="C", default=ACTIVE)
> > > > self.btnDisplay.grid(row=6, column=1, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="r", default=ACTIVE)
> > > > self.btnDisplay.grid(row=6, column=2, padx=5, pady=5)
>
> > > > self.btnDisplay = Button(self, text="/", default=ACTIVE)
> > > > self.btnDisplay.grid(row=6, column=3, padx=5, pady=5)
>
> > > > def Display(self, xbtn):
> > > > if xbtn==1:
> > > > print 1
>
> > > > if __name__ == "__main__":
> > > > guiFrame = GUIFramework()
> > > > guiFrame.mainloop()
>
> > > > [/code]
>
> > > If you have this function:
>
> > > def f():
> > >print 1
> > >return 10
>
> > > and you write:
>
> > > result = f()
>
> > > The '()' is the function execution operator; it tells python to
> > > execute the function.  In this case, the function executes, and then
> > > the return value of the function is assigned to the variable result.
> > > If a function does not have a return statement, then the function
> > > returns None by default.
>
> > > The same thing is happening in this portion of your code:
>
> > > command = self.Display(1)
>
> > > That code tells python to execute the Display function and assign the
> > > function's return value to the variable command.  As a result Display
> > > executes and 1 is displayed.  Then since Dispay does not have

Re: TKinter, buttonwidget response problem(1) and all btns the same size(2)!

2008-04-04 Thread skanemupp
On 5 Apr, 05:57, [EMAIL PROTECTED] wrote:
> On 5 Apr, 05:26, 7stud <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Apr 4, 7:06 pm, [EMAIL PROTECTED] wrote:
>
> > > 1st question:
>
> > > when i run this program 1 will be printed into the interpreter when i
> > > run it BUT without me clicking the actual button.
> > > when i then click the button "1", nothing happens.
>
> > > obv i dont want any output when i dont push the button but i want it
> > > when i do.
>
> > > what am i doing wrong here?
>
> > > 2nd question:
>
> > > i want all the buttons to have the same size. i thought i should use
> > > row/columnspan but i dont get that to work.
> > > how should i do?
>
> > > [code]
> > > #! /usr/bin/env python
> > > from Tkinter import *
> > > import tkMessageBox
>
> > > class GUIFramework(Frame):
> > > """This is the GUI"""
>
> > > def __init__(self,master=None):
> > > """Initialize yourself"""
>
> > > """Initialise the base class"""
> > > Frame.__init__(self,master)
>
> > > """Set the Window Title"""
> > > self.master.title("Calculator")
>
> > > """Display the main window"
> > > with a little bit of padding"""
> > > self.grid(padx=10,pady=10)
> > > self.CreateWidgets()
>
> > > def CreateWidgets(self):
>
> > > self.enText = Entry(self)
> > > self.enText.grid(row=0, column=0, columnspan=8, padx=5,
> > > pady=5)
>
> > > self.enText = Entry(self)
> > > self.enText.grid(row=1, column=0, columnspan=8, padx=5,
> > > pady=5)
>
> > > self.btnDisplay = Button(self, text="1",
> > > command=self.Display(1))
> > > self.btnDisplay.grid(row=3, column=0, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="2", default=ACTIVE)
> > > self.btnDisplay.grid(row=3, column=1, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="3", default=ACTIVE)
> > > self.btnDisplay.grid(row=3, column=2, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="+", default=ACTIVE)
> > > self.btnDisplay.grid(row=3, column=3, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="4", default=ACTIVE)
> > > self.btnDisplay.grid(row=4, column=0, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="5", default=ACTIVE)
> > > self.btnDisplay.grid(row=4, column=1, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="6", default=ACTIVE)
> > > self.btnDisplay.grid(row=4, column=2, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="-", default=ACTIVE)
> > > self.btnDisplay.grid(row=4, column=3, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="7", default=ACTIVE)
> > > self.btnDisplay.grid(row=5, column=0, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="8", default=ACTIVE)
> > > self.btnDisplay.grid(row=5, column=1, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="9", default=ACTIVE)
> > > self.btnDisplay.grid(row=5, column=2, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="*", default=ACTIVE)
> > > self.btnDisplay.grid(row=5, column=3, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="0", default=ACTIVE)
> > > self.btnDisplay.grid(row=6, column=0, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="C", default=ACTIVE)
> > > self.btnDisplay.grid(row=6, column=1, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="r", default=ACTIVE)
> > > self.btnDisplay.grid(row=6, column=2, padx=5, pady=5)
>
> > > self.btnDisplay = Button(self, text="/", default=ACTIVE)
> > > self.btnDisplay.grid(row=6, column=3, padx=5, pady=5)
>
> > > def Display(self, xbtn):
> > > if xbtn==1:
> > > print 1
>
> > > if __name__ == "__main__":
> > > guiFrame = GUIFramework()
> > > guiFrame.mainloop()
>
> > > [/code]
>
> > If you have this function:
>
> > def f():
> >print 1
> >return 10
>
> > and you write:
>
> > result = f()
>
> > The '()' is the function execution operator; it tells python to
> > execute the function.  In this case, the function executes, and then
> > the return value of the function is assigned to the variable result.
> > If a function does not have a return statement, then the function
> > returns None by default.
>
> > The same thing is happening in this portion of your code:
>
> > command = self.Display(1)
>
> > That code tells python to execute the Display function and assign the
> > function's return value to the variable command.  As a result Display
> > executes and 1 is displayed.  Then since Dispay does not have a return
> > statement, None is returned, and None is assigned to command.
> > Obviously, that is not what you want to do.
>
> > What you want to do is assign a "function reference" to command so
> > that python can execute the f

Re: TKinter, buttonwidget response problem(1) and all btns the same size(2)!

2008-04-04 Thread skanemupp
On 5 Apr, 05:26, 7stud <[EMAIL PROTECTED]> wrote:
> On Apr 4, 7:06 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > 1st question:
>
> > when i run this program 1 will be printed into the interpreter when i
> > run it BUT without me clicking the actual button.
> > when i then click the button "1", nothing happens.
>
> > obv i dont want any output when i dont push the button but i want it
> > when i do.
>
> > what am i doing wrong here?
>
> > 2nd question:
>
> > i want all the buttons to have the same size. i thought i should use
> > row/columnspan but i dont get that to work.
> > how should i do?
>
> > [code]
> > #! /usr/bin/env python
> > from Tkinter import *
> > import tkMessageBox
>
> > class GUIFramework(Frame):
> > """This is the GUI"""
>
> > def __init__(self,master=None):
> > """Initialize yourself"""
>
> > """Initialise the base class"""
> > Frame.__init__(self,master)
>
> > """Set the Window Title"""
> > self.master.title("Calculator")
>
> > """Display the main window"
> > with a little bit of padding"""
> > self.grid(padx=10,pady=10)
> > self.CreateWidgets()
>
> > def CreateWidgets(self):
>
> > self.enText = Entry(self)
> > self.enText.grid(row=0, column=0, columnspan=8, padx=5,
> > pady=5)
>
> > self.enText = Entry(self)
> > self.enText.grid(row=1, column=0, columnspan=8, padx=5,
> > pady=5)
>
> > self.btnDisplay = Button(self, text="1",
> > command=self.Display(1))
> > self.btnDisplay.grid(row=3, column=0, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="2", default=ACTIVE)
> > self.btnDisplay.grid(row=3, column=1, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="3", default=ACTIVE)
> > self.btnDisplay.grid(row=3, column=2, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="+", default=ACTIVE)
> > self.btnDisplay.grid(row=3, column=3, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="4", default=ACTIVE)
> > self.btnDisplay.grid(row=4, column=0, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="5", default=ACTIVE)
> > self.btnDisplay.grid(row=4, column=1, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="6", default=ACTIVE)
> > self.btnDisplay.grid(row=4, column=2, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="-", default=ACTIVE)
> > self.btnDisplay.grid(row=4, column=3, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="7", default=ACTIVE)
> > self.btnDisplay.grid(row=5, column=0, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="8", default=ACTIVE)
> > self.btnDisplay.grid(row=5, column=1, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="9", default=ACTIVE)
> > self.btnDisplay.grid(row=5, column=2, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="*", default=ACTIVE)
> > self.btnDisplay.grid(row=5, column=3, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="0", default=ACTIVE)
> > self.btnDisplay.grid(row=6, column=0, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="C", default=ACTIVE)
> > self.btnDisplay.grid(row=6, column=1, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="r", default=ACTIVE)
> > self.btnDisplay.grid(row=6, column=2, padx=5, pady=5)
>
> > self.btnDisplay = Button(self, text="/", default=ACTIVE)
> > self.btnDisplay.grid(row=6, column=3, padx=5, pady=5)
>
> > def Display(self, xbtn):
> > if xbtn==1:
> > print 1
>
> > if __name__ == "__main__":
> > guiFrame = GUIFramework()
> > guiFrame.mainloop()
>
> > [/code]
>
> If you have this function:
>
> def f():
>print 1
>return 10
>
> and you write:
>
> result = f()
>
> The '()' is the function execution operator; it tells python to
> execute the function.  In this case, the function executes, and then
> the return value of the function is assigned to the variable result.
> If a function does not have a return statement, then the function
> returns None by default.
>
> The same thing is happening in this portion of your code:
>
> command = self.Display(1)
>
> That code tells python to execute the Display function and assign the
> function's return value to the variable command.  As a result Display
> executes and 1 is displayed.  Then since Dispay does not have a return
> statement, None is returned, and None is assigned to command.
> Obviously, that is not what you want to do.
>
> What you want to do is assign a "function reference" to command so
> that python can execute the function sometime later when you click on
> the button.  A function reference is just the function name without
> the '()' after it.  So you would write:
>
> command = self.Display
>
> But writing it like that doesn't allow *you* to pass

Re: TKinter, buttonwidget response problem(1) and all btns the same size(2)!

2008-04-04 Thread 7stud
On Apr 4, 7:06 pm, [EMAIL PROTECTED] wrote:
> 1st question:
>
> when i run this program 1 will be printed into the interpreter when i
> run it BUT without me clicking the actual button.
> when i then click the button "1", nothing happens.
>
> obv i dont want any output when i dont push the button but i want it
> when i do.
>
> what am i doing wrong here?
>
> 2nd question:
>
> i want all the buttons to have the same size. i thought i should use
> row/columnspan but i dont get that to work.
> how should i do?
>
> [code]
> #! /usr/bin/env python
> from Tkinter import *
> import tkMessageBox
>
> class GUIFramework(Frame):
>     """This is the GUI"""
>
>     def __init__(self,master=None):
>         """Initialize yourself"""
>
>         """Initialise the base class"""
>         Frame.__init__(self,master)
>
>         """Set the Window Title"""
>         self.master.title("Calculator")
>
>         """Display the main window"
>         with a little bit of padding"""
>         self.grid(padx=10,pady=10)
>         self.CreateWidgets()
>
>     def CreateWidgets(self):
>
>         self.enText = Entry(self)
>         self.enText.grid(row=0, column=0, columnspan=8, padx=5,
> pady=5)
>
>         self.enText = Entry(self)
>         self.enText.grid(row=1, column=0, columnspan=8, padx=5,
> pady=5)
>
>         self.btnDisplay = Button(self, text="1",
> command=self.Display(1))
>         self.btnDisplay.grid(row=3, column=0, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="2", default=ACTIVE)
>         self.btnDisplay.grid(row=3, column=1, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="3", default=ACTIVE)
>         self.btnDisplay.grid(row=3, column=2, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="+", default=ACTIVE)
>         self.btnDisplay.grid(row=3, column=3, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="4", default=ACTIVE)
>         self.btnDisplay.grid(row=4, column=0, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="5", default=ACTIVE)
>         self.btnDisplay.grid(row=4, column=1, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="6", default=ACTIVE)
>         self.btnDisplay.grid(row=4, column=2, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="-", default=ACTIVE)
>         self.btnDisplay.grid(row=4, column=3, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="7", default=ACTIVE)
>         self.btnDisplay.grid(row=5, column=0, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="8", default=ACTIVE)
>         self.btnDisplay.grid(row=5, column=1, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="9", default=ACTIVE)
>         self.btnDisplay.grid(row=5, column=2, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="*", default=ACTIVE)
>         self.btnDisplay.grid(row=5, column=3, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="0", default=ACTIVE)
>         self.btnDisplay.grid(row=6, column=0, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="C", default=ACTIVE)
>         self.btnDisplay.grid(row=6, column=1, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="r", default=ACTIVE)
>         self.btnDisplay.grid(row=6, column=2, padx=5, pady=5)
>
>         self.btnDisplay = Button(self, text="/", default=ACTIVE)
>         self.btnDisplay.grid(row=6, column=3, padx=5, pady=5)
>
>     def Display(self, xbtn):
>         if xbtn==1:
>             print 1
>
> if __name__ == "__main__":
>     guiFrame = GUIFramework()
>     guiFrame.mainloop()
>
> [/code]



If you have this function:

def f():
   print 1
   return 10

and you write:

result = f()

The '()' is the function execution operator; it tells python to
execute the function.  In this case, the function executes, and then
the return value of the function is assigned to the variable result.
If a function does not have a return statement, then the function
returns None by default.

The same thing is happening in this portion of your code:

command = self.Display(1)

That code tells python to execute the Display function and assign the
function's return value to the variable command.  As a result Display
executes and 1 is displayed.  Then since Dispay does not have a return
statement, None is returned, and None is assigned to command.
Obviously, that is not what you want to do.

What you want to do is assign a "function reference" to command so
that python can execute the function sometime later when you click on
the button.  A function reference is just the function name without
the '()' after it.  So you would write:

command = self.Display

But writing it like that doesn't allow *you* to pass any arguments to
Display().  In addition, *tkinter* does not pass any arguments to
Display when tkinter calls Display in response to a button click.  As
a result, there is no way to pass an argument to Display.

However, there is another way to cause a function 

Re: Help me on function definition

2008-04-04 Thread Alan Isaac
aeneng wrote:

> WHAT IS WRONG WITH MY CODE? 

> def cross(u,v)



Missing colon.



hth,

Alan Isaac


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


Re: When does a binary extension gets the file extension '.pyd' and when is it '.so'

2008-04-04 Thread llothar
Thanks, my question was not how can i make python to it find. I don't
have a problem.

My question was: Why does setup.py generated sometimes a pyd and
sometimes a so file?

There must be a rule behind this.

Unforunately setup.py is not well documented. Here i mean i need a
specification not a
tutorial, because i want to know something not do something.

Don't ask why i need to know: I need to know. And maybe somebody here
can drop a
line before i have to dig around in the source code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: pry unit testing framework

2008-04-04 Thread Aldo Cortesi

Hi Jim,

Thus spake j vickroy ([EMAIL PROTECTED]):

> > We are happy to announce the first release of Pry, a unit testing framework.
> > 
> > Features
> > 
> > 
> > * Built-in coverage analysis, profiling, and quick-and-dirty 
> > benchmarking
> > * Assertion-based tests - no ugly failUnless*, failIf*, etc. methods
> > * Tree-based test structure for better fixture management
> > * No implicit instantiation of test suits
> > * Powerful command-line interface
> > 
> > 
> > Download:  http://dev.nullcube.com
> > 
> > Manual: http://dev.nullcube.com/doc/pry/index.html
> > 
> > 
> It appears this package can not be used with Microsoft Windows because 
> it uses the *fcntl* module which is not part of the Windows distribution.

Thanks for letting me know about this. I've just released version
0.2.1 of Pry, which addresses this and a few other Windows
compatibility issues. You can download it here:

http://dev.nullcube.com/download/pry-0.2.1.tar.gz




Regards,



Aldo



-- 
Aldo Cortesi
M: +61 419 492 863
P: +61 1300 887 007
W: www.nullcube.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-by-example - new online guide to Python Standard Library

2008-04-04 Thread ivan
Very cool.
Have you thought about making a printable version that doesn't wrap
any lines that shouldn't be and has page breaks at good spots?

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


Pickle to Source - Gabriel Genellina?

2008-04-04 Thread $P!D3R DelSol
Hello
I found this 3 year old message asking about doing the same exact thing I am 
trying to do. This is one wheel I REALLY don't want to re-invent.  Can anyone 
point me to code that does this?
Thanks
Ivan ( sunsp1der at yahoo dot com)

> I want to convert from pickle format to python source code. That is,
> given an existing pickle, I want to produce a textual representation
> which, when evaluated, yields the original object (as if I had
> unpickled the pickle).
> I know of some transformations pickle/xml (Zope comes with one such
> tool, gnosis xml is another) so I believe I could build something based
> on them.
> But I dont want to reinvent the wheel, I wonder if anyone knows of a
> library which could do what I want?

An example to make things clear:

class MyClass:
def __init__(self,a,b):
self.a=a
self.b=b
def foo(self):
self.done=1
# construct an instance and work with it
obj = MyClass(1,2)
obj.foo()
# save into file
pickle.dump(obj,file('test.dat','wb'))

Then, later, another day, using another process, I read the file and
want to print a block of python code equivalent to the pickle saved in
the file.
That is, I want to *generate* a block of code like this:

xxx = new.instance(MyClass)
xxx.a = 1
xxx.b = 2
xxx.done = 1

Or perhaps:

xxx = new.instance(MyClass, {'a':1,'b':2,'done':1})

In other words, I need a *string* which, being sent to eval(), would
return the original object state saved in the pickle.
As has been pointed, repr() would do that for simple types. But I need
a more general solution.

The real case is a bit more complicated because there may be references
to other objects, involving the persistent_id mechanism of pickles, but
I think it should not be too difficult. In this example, if xxx.z
points to another external instance for which persistent_id returns
'1234', would suffice to output another line like:
xxx.z = external_reference('1234')

I hope its more clear now.

Thanks,
Gabriel Genellina
Softlab SRL 
///\*_*/\\\ 

NOTICE: Empowered by Presidential Executive Orders, the National Security 
Agency may read this email without warning, warrant, or notice. The NSA may do 
this without any judicial or legislative oversight. The President also claims 
the right to designate the sender or the reader as an enemy combatant and to 
imprison him/her indefinitely without access to legal counsel or anyone else, 
and to be "rendered" to a foreign government for possible torture or death.





  

You rock. That's why Blockbuster's offering you one month of Blockbuster Total 
Access, No Cost.  
http://tc.deals.yahoo.com/tc/blockbuster/text5.com-- 
http://mail.python.org/mailman/listinfo/python-list

Re: having list attribute to track max size

2008-04-04 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Lets say I have a dynamic list class (may be extended from list),
| where I add and remove items during program.
| a = []
| a.append(1)
| 
|
| I am trying to find is there easy way keep track of 'maximum size of
| list reached"
| so for example len(a) goes from 0->3->4->3
| If I call a.max_size_ever(), I will get 4

Here is a start:

>>> class mlist(list):
  def __init__(self,it):
list.__init__(self,it)
self.maxlen = len(self)

>>> ll = mlist((1,2,3))
>>> ll.maxlen
3

Now, add methods for the list grow methods (.append, .extend, and 
.__setslice__) which follow a call to the parent method with

self.maxlen = max(self.maxlen, len(self)) # or equivalent code

tjr





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


TKinter, buttonwidget response problem(1) and all btns the same size(2)!

2008-04-04 Thread skanemupp
1st question:

when i run this program 1 will be printed into the interpreter when i
run it BUT without me clicking the actual button.
when i then click the button "1", nothing happens.

obv i dont want any output when i dont push the button but i want it
when i do.

what am i doing wrong here?



2nd question:

i want all the buttons to have the same size. i thought i should use
row/columnspan but i dont get that to work.
how should i do?



[code]
#! /usr/bin/env python
from Tkinter import *
import tkMessageBox

class GUIFramework(Frame):
"""This is the GUI"""

def __init__(self,master=None):
"""Initialize yourself"""

"""Initialise the base class"""
Frame.__init__(self,master)

"""Set the Window Title"""
self.master.title("Calculator")

"""Display the main window"
with a little bit of padding"""
self.grid(padx=10,pady=10)
self.CreateWidgets()

def CreateWidgets(self):

self.enText = Entry(self)
self.enText.grid(row=0, column=0, columnspan=8, padx=5,
pady=5)

self.enText = Entry(self)
self.enText.grid(row=1, column=0, columnspan=8, padx=5,
pady=5)

self.btnDisplay = Button(self, text="1",
command=self.Display(1))
self.btnDisplay.grid(row=3, column=0, padx=5, pady=5)

self.btnDisplay = Button(self, text="2", default=ACTIVE)
self.btnDisplay.grid(row=3, column=1, padx=5, pady=5)

self.btnDisplay = Button(self, text="3", default=ACTIVE)
self.btnDisplay.grid(row=3, column=2, padx=5, pady=5)

self.btnDisplay = Button(self, text="+", default=ACTIVE)
self.btnDisplay.grid(row=3, column=3, padx=5, pady=5)

self.btnDisplay = Button(self, text="4", default=ACTIVE)
self.btnDisplay.grid(row=4, column=0, padx=5, pady=5)

self.btnDisplay = Button(self, text="5", default=ACTIVE)
self.btnDisplay.grid(row=4, column=1, padx=5, pady=5)

self.btnDisplay = Button(self, text="6", default=ACTIVE)
self.btnDisplay.grid(row=4, column=2, padx=5, pady=5)

self.btnDisplay = Button(self, text="-", default=ACTIVE)
self.btnDisplay.grid(row=4, column=3, padx=5, pady=5)

self.btnDisplay = Button(self, text="7", default=ACTIVE)
self.btnDisplay.grid(row=5, column=0, padx=5, pady=5)

self.btnDisplay = Button(self, text="8", default=ACTIVE)
self.btnDisplay.grid(row=5, column=1, padx=5, pady=5)

self.btnDisplay = Button(self, text="9", default=ACTIVE)
self.btnDisplay.grid(row=5, column=2, padx=5, pady=5)

self.btnDisplay = Button(self, text="*", default=ACTIVE)
self.btnDisplay.grid(row=5, column=3, padx=5, pady=5)

self.btnDisplay = Button(self, text="0", default=ACTIVE)
self.btnDisplay.grid(row=6, column=0, padx=5, pady=5)

self.btnDisplay = Button(self, text="C", default=ACTIVE)
self.btnDisplay.grid(row=6, column=1, padx=5, pady=5)

self.btnDisplay = Button(self, text="r", default=ACTIVE)
self.btnDisplay.grid(row=6, column=2, padx=5, pady=5)

self.btnDisplay = Button(self, text="/", default=ACTIVE)
self.btnDisplay.grid(row=6, column=3, padx=5, pady=5)

def Display(self, xbtn):
if xbtn==1:
print 1

if __name__ == "__main__":
guiFrame = GUIFramework()
guiFrame.mainloop()

[/code]
-- 
http://mail.python.org/mailman/listinfo/python-list


455 bloqueador veicular sem mensalidades - http://bloqueadorgsm.vilabol.uol.com.br 4555333208173502757727274

2008-04-04 Thread bloqueador sem mensalidade
   Bloqueador veícluar com tecnologia gsm - Sem mensalidades

Tenha toda segurança para seu carro com um preço justo.

Apenas R$ 299,00 ( sem mensalidades )

http://bloqueadorgsm.vila.bol.com.br/

Compare e Compre.
Rastreador de Veículo
Rastreadores de Veículos
Rastreador GPS
Rastreadores GPS
Rastreador Ituran
Rastreadores Ituran
Rastreador Portátil
Rastreadores Portáteis.
Assistência 24 Horas

Visite agora mesmo nosso site.

http://bloqueadorgsm.vila.bol.com.br/


Graber - Teletrim - Tele Trim - Ituran -
Rastreadores gps , Localizadores, Bloqueadores
Graber - Teletrim - Tele Trim - Ituran -
Rastreadores gps , Localizadores, Bloqueadores
Graber - Teletrim - Tele Trim - Ituran -
Rastreadores gps , Localizadores, Bloqueadores
Graber - Teletrim - Tele Trim - Ituran -
Rastreadores gps , Localizadores, Bloqueadores
Graber - Teletrim - Tele Trim - Ituran -
Rastreadores gps , Localizadores, Bloqueadores





HTigfm&n(>'qai?5"!Co'IuTsX.5APO=7\pcuWJ6
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Nonlinear least square problem

2008-04-04 Thread Michael Press
In article 
<[EMAIL PROTECTED]>,
 Uwe Kotyczka <[EMAIL PROTECTED]> wrote:

> Hallo, sorry for multiposting, but I am really looking
> for some hint to solve my problem. And no, I don't
> use Matlab, but maybe the matlab people have an idea
> nevertheless.

No apology required, since you seem to have 
cross-posted appropriately, and not multi-posted.
Multi-posting is posting the same message one
at a time to more than one group. I see in
the Newsgroups: header line that you posted
to several groups at once. Furthermore the
number of groups is not out of bounds, and
the groups are appropriate to the question
and, presumably, your interests. 

Unfortunately, I cannot help with the actual question. :)

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


Re: Is there any way to say ignore case with "in"?

2008-04-04 Thread 7stud
On Apr 4, 2:43 pm, [EMAIL PROTECTED] wrote:
> Is there any way in python to say
>
>     if string1 in string2:
>         
>
> ignoring the case of string1 and string2?
>
> I know I could use:-
>
>     if lower(string1) in lower(string2):
>         
>
> but it somehow feels there ought to be an easier (tidier?) way.
>

Easier?  You mean like some kind of mind meld?

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


Re: Newbie Question - Overloading ==

2008-04-04 Thread Lie
On Apr 1, 2:22 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> >> Surely an A isn't equal to every other object which just happens to
> >> have the same attributes 'a' and 'b'?
>
> > And why not ?-)
>
> >> I would have thoughts the tests want to be
> >> something like:
>
> >> class A:
> >>     def __eq__(self,other):
> >>          return (isinstance(other, A) and
> >>             self.a == other.a and self.b == other.b)
>
> >> (and similar for B) with either an isinstance or exact match required
> >> for the type.
>
> > I don't think there's a clear rule here. Python is dynamically typed
> > for good reasons, and MHO is that you should not fight against this
> > unless you have equally good reasons to do so.
>
> I fully agree with that, but an apple != a pear, even if they are the same
> size and colour. There will be some types where you can have equality
> between objects of different types (e.g. int/float), but more often the
> fact that they are different types wil automatically mean they are not
> equal.

Even though an apple != a pear, sometimes when we just don't need to
care between their differences we can treat them as equal, that's what
duck typing is. It really depends on your need if you decided to use
or not to use isinstance checking, in most cases you'd want them to be
checked, but sometimes you just want to know whether the two objects
has the same values on their relevant attributes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python2.5 and MySQLdb

2008-04-04 Thread Carsten Haese
On Apr 4, 5:06 pm, writeson <[EMAIL PROTECTED]> wrote:
> It
> generates a huge lists of errors and warnings from gcc when I run the
> python2.5 setup.py build script that comes with the tar file. Anyone
> have any suggestions?

I suggest you post a couple of those error messages here, so that we
can help you without guessing.

--
Carsten Haese
http://informixdb.sourceforge.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Importing a 3rd Party windows DLL for use within th Python

2008-04-04 Thread Robert Kern
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I have recently started learing how to code/script in Python which I
> am realy enjoying. I am new to this game as my background is RF/HW
> design engineer so coding is not my first skillset , so please bare
> with me!
> 
>  I am a little lost with how to procede on this problem. I need to
> write a python script enabling me to comunnicate routines to a pico
> ADC212 oscilloscope. I have been provided with a windows DLL & a
> header filefrom the manufacturer.
> Is it possible for someone to provide the information on the steps
> necessary to access this DLL and treat it like any other pyd library?
> Maybe there is already a tutorial available for performing this task?
> Is this task straight forward?

It depends on how complicated the library is. For a first stab, I recommend 
using ctypes. ctypes lets you load the DLL and call its functions in pure 
Python 
without having to write an extension module (pyd) first. ctypes comes with 
Python 2.5 already; if you have Python 2.4, you can install it separately.

   http://python.net/crew/theller/ctypes/

You may eventually want to write an extension module. Here is the tutorial:

   http://docs.python.org/ext/ext.html

There are a couple of tools to make this task easier. I happen to like Cython 
for things like this:

   http://cython.org/

One large benefit of using ctypes instead of building an extension is that you 
do not have to compile anything. When wrapping binary-only DLLs on Windows, 
compiling and linking correctly are often the largest hurdles.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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


Re: Importing a 3rd Party windows DLL for use within th Python

2008-04-04 Thread sturlamolden
On Apr 5, 12:58 am, [EMAIL PROTECTED] wrote:

> Is it possible for someone to provide the information on the steps
> necessary to access this DLL and treat it like any other pyd library?
> Maybe there is already a tutorial available for performing this task?
> Is this task straight forward?

Short answer: Read the ctypes tutorial and reference.

http://python.net/crew/theller/ctypes/tutorial.html
http://python.net/crew/theller/ctypes/reference.html


Other options:
- Write a pyd wrapper manually in C
- Write a pyd wrapper using Pyrex or Cython
- Write a pyd wrapper using Swig
- Write a pyd wrapper using Boost.Python or PyCXX
- Inline C++ using scipy.weave












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


Importing a 3rd Party windows DLL for use within th Python

2008-04-04 Thread lee . walczak
Hi,

I have recently started learing how to code/script in Python which I
am realy enjoying. I am new to this game as my background is RF/HW
design engineer so coding is not my first skillset , so please bare
with me!

 I am a little lost with how to procede on this problem. I need to
write a python script enabling me to comunnicate routines to a pico
ADC212 oscilloscope. I have been provided with a windows DLL & a
header filefrom the manufacturer.
Is it possible for someone to provide the information on the steps
necessary to access this DLL and treat it like any other pyd library?
Maybe there is already a tutorial available for performing this task?
Is this task straight forward?

Look forward to 'a' response!

B.Regards,

Lee

Feel free to request more information if you feel it is necessary.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: displaying pgm file in python

2008-04-04 Thread Gabriel Genellina
En Fri, 04 Apr 2008 19:07:59 -0300, wilson <[EMAIL PROTECTED]>  
escribió:

> i converted an 8bit rgb .jpg file into .pgm using adobe photoshop and
> a plugin from  
> http://photoshop.pluginsworld.com/plugins/adobe/362/richard-rosenman/portable-pixmap-importer-exporter.html
> I want to check if this file can be properly displayed.
> Image opening and show() in PIL fails to do it so i tried Tkinter

> I checked the asci text of .pgm file ,it starts with a line P2 and
> then several lines with integers..can someone tell me if there is a
> way to display this properly

P2 is a rather old variant that it's not in use anymore AFAIK. Try  
replacing P2 with P5; at least PIL should recognize it, I think. PIL can  
read and write .pgm, why don't you do the conversion with PIL?

-- 
Gabriel Genellina

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


displaying pgm file in python

2008-04-04 Thread wilson
i converted an 8bit rgb .jpg file into .pgm using adobe photoshop and
a plugin from 
http://photoshop.pluginsworld.com/plugins/adobe/362/richard-rosenman/portable-pixmap-importer-exporter.html
I want to check if this file can be properly displayed.
Image opening and show() in PIL fails to do it so i tried Tkinter

i created a canvas in a tkinter gui and tried
self.myimg=PhotoImage(file="mytestpic.pgm")
 
self.selimgtag=self.canvorig.create_image(70,100,image=self.myimg)
self.canvorig.update_idletasks()

this causes AttributeError snd says can't identify image file
I checked the asci text of .pgm file ,it starts with a line P2 and
then several lines with integers..can someone tell me if there is a
way to display this properly

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


Re: python bisect questions

2008-04-04 Thread Gabriel Genellina
En Fri, 04 Apr 2008 18:08:57 -0300, <[EMAIL PROTECTED]> escribió:

>> b) Define a function to extract a "key" from your items such that items  
>>  
>> compare the same as their keys. For example, key(x) -> x.lower() may be  
>>  
>> used to compare text case-insensitively.
>> Then, use a tuple (key, value) instead of the bare value. When  
>> extracting  
>> items from the queue, remember to unpack both parts. This is known as  
>> the  
>> decorate-sort-undecorate pattern; google for it.
>> This is the approach used on your code snippet.
>>
> I liked decorate-sort-undecorate pattern idea.
> But is there anyway I can provide information for tie breaking.
> so for case, where keyfunc(x) returns same values,
> I need to provide additional tie-breaking rules, is that possible to
> do?

Use as much elements in the tuple as you need. By example, you could have  
(year, month, amount, invoice_object) - you would get invocies sorted by  
year, then by month, then by amount.

-- 
Gabriel Genellina

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


Re: Easy-to-install-and-use scientific graphics (plotting) package for Python 2.5.1 on Linux Ubuntu 7.1

2008-04-04 Thread Joshua Kugler
> Is there an easy scientific graphics (plotting) package for Python
> 2.5.1 running on Ubuntu Linux 7.1 ("Gutsy Gibbon")?
> 
> A few years ago I used PyLab (a MatLab-like plotting module for
> Python) on a Windows machine, but I don't know if there is a similar
> easy-to-install-and-use Python 2.5.1-compatible graphics package for
> Ubuntu Linux 7.1?

We've been using Matplotlib for a while, but are looking for alternatives. 
I recently came across Chaco (http://code.enthought.com/chaco/) and am
quite impressed with what I see so far.

It's API is very clean, not requiring the "magic functions" (can we say
setp()?) that is required by matplotlib.  Very OO, and from what I see of
example code, the API complies with PEP 8 conventions.

Installation was easy (easy_install), but for a couple packages, you will
need GCC, python-dev, and swig.

I haven't dug into it much, but it looks really, really promising.

j

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


Re: Python2.5 and MySQLdb

2008-04-04 Thread Jeffrey Froman
writeson wrote:

> I'm running a CentOS 4 server and have installed Python2.5 on there
> (it's our development machine) in preparation of moving to Python2.5
> everywhere. All looks good with our code and 2.5, except where it
> comes to MySQLdb, I can't get that to install on the machine. It
> generates a huge lists of errors and warnings from gcc when I run the
> python2.5 setup.py build script that comes with the tar file. Anyone
> have any suggestions?

MySQLdb compiles fine for me with python2.5 on CentOS-4. I suggest that you
examine the end of that long of warnings and errors to determine why it
won't compile on your machine.


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


Re: python bisect questions

2008-04-04 Thread ankitks . mital

>
> b) Define a function to extract a "key" from your items such that items  
> compare the same as their keys. For example, key(x) -> x.lower() may be  
> used to compare text case-insensitively.
> Then, use a tuple (key, value) instead of the bare value. When extracting  
> items from the queue, remember to unpack both parts. This is known as the  
> decorate-sort-undecorate pattern; google for it.
> This is the approach used on your code snippet.
>
> 
> def keyfunc(x):
>      return x.lower()
>
> x1 = "bcd"
> x2 = "abC"
> x3 = "Z"
> x4 = "AbC"
> queue = []
> insort(queue, (keyfunc(x1),x1))
> print queue
> insort(queue, (keyfunc(x2),x2))
> print queue
> insort(queue, (keyfunc(x3),x3))
> print queue
> insort(queue, (keyfunc(x4),x4))
> print queue
> print [value for (key,value) in queue]
> 

I liked decorate-sort-undecorate pattern idea.
But is there anyway I can provide information for tie breaking.
so for case, where keyfunc(x) returns same values,
I need to provide additional tie-breaking rules, is that possible to
do?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tokenizer inconsistency wrt to new lines in comments

2008-04-04 Thread George Sakkis
On Apr 4, 4:38 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> George Sakkis wrote:
> >> If it was a bug it has to violate a functional requirement. I can't
> >> see which one.
>
> > Perhaps it's not a functional requirement but it came up as a real
> > problem on a source colorizer I use. I count on newlines generating
> > token.NEWLINE or tokenize.NL tokens in order to produce  tags. It
> > took me some time and head scratching to find out why some comments
> > were joined together with the following line. Now I have to check
> > whether a comment ends in new line and if it does output an extra 
> > tag.. it works but it's a kludge.
>
> well, the real kludge here is of course that you're writing your own
> colorizer, when you can just go and grab Pygments:
>
>http://pygments.org/
>
> or, if you prefer something tiny and self-contained, something like the
> colorizer module in this directory:
>
>http://svn.effbot.org/public/stuff/sandbox/pythondoc/
>
> (the element_colorizer module in the same directory gives you XHTML in
> an ElementTree instead of raw HTML, if you want to postprocess things)
>
> 

First off, I didn't write it from scratch, I just tweaked a single
module colorizer I had found online. Second, whether I or someone else
had to deal with it is irrelevant; the point is that generate_tokens()
is not consistent with respect to new lines after comments.

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


Re: Is there any way to say ignore case with "in"?

2008-04-04 Thread Torsten Bronger
Hallöchen!

[EMAIL PROTECTED] writes:

> Is there any way in python to say
>
> if string1 in string2:
> 
>
> ignoring the case of string1 and string2? 

You can "normalise" both first, i.e. converting to lower case.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus
  Jabber ID: [EMAIL PROTECTED]
   (See http://ime.webhop.org for further contact info.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Python2.5 and MySQLdb

2008-04-04 Thread writeson
Hi all,

I'm running a CentOS 4 server and have installed Python2.5 on there
(it's our development machine) in preparation of moving to Python2.5
everywhere. All looks good with our code and 2.5, except where it
comes to MySQLdb, I can't get that to install on the machine. It
generates a huge lists of errors and warnings from gcc when I run the
python2.5 setup.py build script that comes with the tar file. Anyone
have any suggestions?

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


Re: *.py source file surprisingly deleted with Pydev/Eclipse. Who else experienced this ?

2008-04-04 Thread Fabio Zadrozny
On Fri, Apr 4, 2008 at 5:05 PM, Nebur <[EMAIL PROTECTED]> wrote:
> Yes. Linux viruses are rare but useful :-)
>  Well, I don't think the problem a very dangerous one. The Pydev/
>  Eclipse was used for much more than a year nearly daily and
>  intensively. The strange effect is very rare,obviously (plus the
>  chance that it's in my brain, as I mentioned ;-D ) so you probably can
>  lean back. Anyway, I'd be glad to get an even faint idea of the
>  problem.

Hi Nebur,

Well, I have absolutely no idea of what could trigger that either :(

So, just wanted to point out that eclipse saves your file history
(even if you do not have a vcs)...  that operation can be selected by
right clicking a parent folder and selecting 'restore from local
history'.

Cheers,

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


Re: Is there any way to say ignore case with "in"?

2008-04-04 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Is there any way in python to say
> 
> if string1 in string2:
> 
> 
> ignoring the case of string1 and string2? 

 if string1.lower() in string2.lower():
 ...

(there's no case-insensitive version of the "in" operator in stock Python)



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


having list attribute to track max size

2008-04-04 Thread ankitks . mital
Lets say I have a dynamic list class (may be extended from list),
where I add and remove items during program.
a = []
a.append(1)


I am trying to find is there easy way keep track of 'maximum size of
list reached"
so for example len(a) goes from 0->3->4->3
If I call a.max_size_ever(), I will get 4

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


Re: Self in Interactive Interpreter

2008-04-04 Thread Fredrik Lundh
kj7ny wrote:

> For years it has been a slight annoyance that every time I wanted to
> test a snippet of code from a class by running it in the interactive
> interpreter, I had to remove all of the self. instances from the
> code.  After I got it working correctly, I had to put all the self.'s
> back into the code to put it back into my class.

wouldn't it be a lot easier to test your code by importing the module 
containing it into the interactive interpreter?

 class dummy:
 def __init__(self):
 pass

or, shorter:

   >>> class dummy: pass



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


Is there any way to say ignore case with "in"?

2008-04-04 Thread tinnews
Is there any way in python to say

if string1 in string2:


ignoring the case of string1 and string2? 


I know I could use:-

if lower(string1) in lower(string2):


but it somehow feels there ought to be an easier (tidier?) way.

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


Re: Python in High School

2008-04-04 Thread Aahz
In article <[EMAIL PROTECTED]>,
Jan Claeys  <[EMAIL PROTECTED]> wrote:
>
>There are at least 3 books about game programming in python:
>

STAY AWAY

Speaking as half of the tech-editing team for this book (the formal title
is _Game Programming: The L Line, The Express Line to Learning_), I
recommend staying as far as possible from this book.  It does an okay job
of teaching pygame, but it does a poor job of teaching Python (for
example, it does not mention dicts) and therefore has a number of flaws
from a pedagogical perspective, *plus* there are some bugs in the code.
-- 
Aahz ([EMAIL PROTECTED])   <*> 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: Tokenizer inconsistency wrt to new lines in comments

2008-04-04 Thread Fredrik Lundh
George Sakkis wrote:

>> If it was a bug it has to violate a functional requirement. I can't
>> see which one.
> 
> Perhaps it's not a functional requirement but it came up as a real
> problem on a source colorizer I use. I count on newlines generating
> token.NEWLINE or tokenize.NL tokens in order to produce  tags. It
> took me some time and head scratching to find out why some comments
> were joined together with the following line. Now I have to check
> whether a comment ends in new line and if it does output an extra 
> tag.. it works but it's a kludge.

well, the real kludge here is of course that you're writing your own 
colorizer, when you can just go and grab Pygments:

http://pygments.org/

or, if you prefer something tiny and self-contained, something like the 
colorizer module in this directory:

http://svn.effbot.org/public/stuff/sandbox/pythondoc/

(the element_colorizer module in the same directory gives you XHTML in 
an ElementTree instead of raw HTML, if you want to postprocess things)



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


Re: Tokenizer inconsistency wrt to new lines in comments

2008-04-04 Thread George Sakkis
On Apr 4, 3:18 pm, Kay Schluehr <[EMAIL PROTECTED]> wrote:

> I guess it's just an artifact of handling line continuations within
> expressions where a different rule is applied. For compilation
> purposes both the newlines within expressions as well as the comments
> are irrelevant. There are even two different token namely NEWLINE and
> NL which are produced for newlines. NL and COMMENT will be ignored.
> NEWLINE is relevant for the parser.
>
> If it was a bug it has to violate a functional requirement. I can't
> see which one.

Perhaps it's not a functional requirement but it came up as a real
problem on a source colorizer I use. I count on newlines generating
token.NEWLINE or tokenize.NL tokens in order to produce  tags. It
took me some time and head scratching to find out why some comments
were joined together with the following line. Now I have to check
whether a comment ends in new line and if it does output an extra 
tag.. it works but it's a kludge.

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


Self in Interactive Interpreter

2008-04-04 Thread kj7ny
Hope this hasn't been posted hundreds of times. I have never seen it
before, but could have missed it.

For years it has been a slight annoyance that every time I wanted to
test a snippet of code from a class by running it in the interactive
interpreter, I had to remove all of the self. instances from the
code.  After I got it working correctly, I had to put all the self.'s
back into the code to put it back into my class.

The other day my brain had a functional synapse and I realized I could
just start my interactive session with:

>>> class dummy:
>>> def __init__(self):
>>> pass

>>> self=dummy()

I could then just set up my test variables something like:

>>> self.x='Hello'
>>> self.y='World'

And I could then use class type code such as:

>>> print self.x, self.y

I no longer had to remove and then replace all of the self. notation
from my code snippets.

So far I haven't seen why I shouldn't to this.  I haven't had any
problems using it, but I haven't used it that much.  If there is a
good reason to NOT do it, let me know.  Otherwise I hope this helps
anyone who has been annoyed by the same thing.

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


Re: *.py source file surprisingly deleted with Pydev/Eclipse. Who else experienced this ?

2008-04-04 Thread Nebur
Yes. Linux viruses are rare but useful :-)
Well, I don't think the problem a very dangerous one. The Pydev/
Eclipse was used for much more than a year nearly daily and
intensively. The strange effect is very rare,obviously (plus the
chance that it's in my brain, as I mentioned ;-D ) so you probably can
lean back. Anyway, I'd be glad to get an even faint idea of the
problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: *.py source file surprisingly deleted with Pydev/Eclipse. Who else experienced this ?

2008-04-04 Thread Gabriel Genellina
En Fri, 04 Apr 2008 15:46:48 -0300, Alex9968 <[EMAIL PROTECTED]>  
escribió:
> Nebur wrote:

>> No, I can't reproduce it, and I don't know whom to blame (Pydev?
>> Eclipse ? The File System ? A Virus that only 2 times in half a year
>> deletes a single file I'm busy working with, and seems to do nothing
>> else? Myself beeing schizophrenic ??)

> A virus created to remind you 2 times in half a year of the importance
> of backup operations ;-) . I'm joking. I don't know what is this, but
> I'm interested. Because my files won't be restorable from version
> control :-(

Then implement it! It's not so difficult, less if you're the only one  
working on the files.

-- 
Gabriel Genellina

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


Re: Any fancy grep utility replacements out there?

2008-04-04 Thread Robert Kern
[EMAIL PROTECTED] wrote:
> Thanks to everyone who responded, and sorry for my late response.
> 
> Grin seems like the perfect solution for me.  I finally had a chance
> to download it and play with it today.  It's great.
> 
> Robert...you were kind enough to ask if I had any requests.  Just the
> one right now of grepping through gzip files.  If for some reason you
> don't want to do it or don't have time to do it, I could probably do
> it and send you a patch.  But I imagine that since you wrote the code,
> you could do it more elegantly than I could.

I was hoping that the code would be understandable enough that it shouldn't 
matter who's modifying it. But I have a plane trip tomorrow; I'll take a stab 
at it.

> P.S.  Robertthis program totally deserves a real web page, not
> just being buried in an svn repository.  I spent a lot of time looking
> for a tool like this that was written in python.  I imagine others
> have as well, and have simply given up.

It will. Eventually.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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


Re: Any fancy grep utility replacements out there?

2008-04-04 Thread Robert Kern
Floris Bruynooghe wrote:
> I tried to find something similar a while ago and found ack[1].  I do
> realise it's written in perl but it does the job nicely.  Never needed
> to search in zipfiles though, just unzipping them in /tmp would always
> work...

Yup, I used ack for a little while before writing grin. Unfortunately, I got 
hooked on context lines and these were unimplemented in ack.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

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


Re: Classes in modules

2008-04-04 Thread Gabriel Genellina
En Thu, 03 Apr 2008 18:00:54 -0300, <[EMAIL PROTECTED]> escribió:

> Yeah, I was a little embarrassed putting my code up to be examined.
> Thanks for the reply.  I typed up some classes, but I seemed to have
> run into some more problems.  One of the classes keeps getting an
> error that it can't pop from an empty list.  Here's the code so far:
>
> #deck functions
> class Deck(object):
> def __init__(self):
> self.deck = []
> for i in range(52):
> self.deck.append(Cards(i % 13, i / 13))
> def draw(self): #This is where my (first) problem
> arises, though there may be more
> return self.deck.pop()  #IndexError: pop from empty list
> def size(self):
> return len(self.deck)

Next time post the whole traceback including the exception message. It  
really contains valuable information. Without it, one has to guess...
"pop from empty list" means that you are trying to draw a card after the  
deck is empty. The traceback would show the caller, but in this case it's  
easy because there is a single place:

> class Game(object):  #the main game class
> def __init__(self):
> self.deck = Deck()
> self.deck.shuffle()
> self.player = Hand()
> self.computer = Hand()
> for i in range(self.deck.size()):
> self.player.put(self.deck.draw())
> self.computer.put(self.deck.draw())
> self.stock = Stock()
> print self.stock.showtrump()

The loop takes 52 iterations but you draw two cards in each iteration -  
the 27th sees an empty deck.

-- 
Gabriel Genellina

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


Re: RELEASED Python 2.6a2 and 3.0a4

2008-04-04 Thread Martin v. Löwis
> The Windows x86 MSI installer is missing for both 2.6 and 3.0.

And likely will continue to do so for some time.

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


Re: Examples using msilib to build windows installers

2008-04-04 Thread Martin v. Löwis
> It would appear to me that the msilib library included with standard
> python 2.5 would allow be to do this. I found the source code that
> builds the python distrubition installer packages, but I was wondering
> if there were other examples that I can learn from.

Actually, the installer itself is built with Tools/msi/msilib, which
predates the msilib shipped in 2.5; the former one uses ActiveX
(automation), whereas the latter one links directly to a native
library (and hence doesn't require PythonCOM). That library was
also used (with modifications) to build Enthought Python.

In any case, the single known application of the shipped msilib
is the bdist_msi command of distutils.

If you want to start using MSI, you absolutely have to know about
the database tables and their purpose. Use orca.exe to inspect
MSI files, and try to make sense out of that. Read MSDN
documentation. msilib greatly helps in writing installers quickly,
but the "learning curve" is perhaps even steeper than "mere"
MSI, as you need to understand both the MSI principles themselves,
and then how msilib wraps it in a more compact form.

Of course, if you can manage to package your application as a
distutils package, you can just try running bdist_msi, and see
what you get.

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


Re: Tokenizer inconsistency wrt to new lines in comments

2008-04-04 Thread Kay Schluehr
On 4 Apr., 18:22, George Sakkis <[EMAIL PROTECTED]> wrote:
> The tokenize.generate_tokens function seems to handle in a context-
> sensitive manner the new line after a comment:
>
> >>> from StringIO import StringIO
> >>> from tokenize import generate_tokens
>
> >>> text = '''
>
> ... # hello world
> ... x = (
> ... # hello world
> ... )
> ... '''
>
> >>> for t in generate_tokens(StringIO(text).readline):
>
> ... print repr(t[1])
> ...
> '\n'
> '# hello world\n'
> 'x'
> '='
> '('
> '\n'
> '# hello world'
> '\n'
> ')'
> '\n'
> ''
>
> Is there a reason that the newline is included in the first comment
> but not in the second, or is it a bug ?
>
> George

I guess it's just an artifact of handling line continuations within
expressions where a different rule is applied. For compilation
purposes both the newlines within expressions as well as the comments
are irrelevant. There are even two different token namely NEWLINE and
NL which are produced for newlines. NL and COMMENT will be ignored.
NEWLINE is relevant for the parser.

If it was a bug it has to violate a functional requirement. I can't
see which one.

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


Re: generator functions: why won't this work?

2008-04-04 Thread Arnaud Delobelle
On Apr 2, 11:04 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Wed, 02 Apr 2008 14:11:30 -0300, <[EMAIL PROTECTED]> escribió:
>
> > On Apr 1, 10:42 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> > wrote:
> >> En Tue, 01 Apr 2008 23:56:50 -0300, <[EMAIL PROTECTED]> escribió:
>
> >>    yield *iterable
>
> >> could be used as a shortcut for this:
>
> >>    for __temp in iterable: yield __temp
>
> > How serious were you about that?
>
> Not so much, I haven't thougth enough on it. Looks fine in principle, but  
> yield expressions may be a problem.
>
> --
> Gabriel Genellina

Funnily, there's a patch for py3k to make this work as in your idea.
It's currently being discussed on python-3000 :)

--
Arnaud

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


Re: Looking for Advanced Python Tutorials

2008-04-04 Thread lbonafide
On Apr 4, 6:58 am, [EMAIL PROTECTED] wrote:
> I was wondering if anyone knew of some online (free if possible)
> advanced tutorials, especially ones that provides tasks and ideas for
> small projects. The issue for myself is I want to improve my python
> programming level, and my ability to program in general, but come up
> blank thinking of a possible task or project to undertake.

Look at PyGame (http://pygame.org) and write a simple game, like
asteroids or space invaders.  Or heck, start with pong.  You'll be
amazed at how game programming will stretch your programming skills.

Or do graphics with PyOpenGL.  Google for NeHe's OpenGL tutorials to
get you started.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generator functions: why won't this work?

2008-04-04 Thread Robert Lehmann
On Wed, 02 Apr 2008 19:04:30 -0300, Gabriel Genellina wrote:

> En Wed, 02 Apr 2008 14:11:30 -0300, <[EMAIL PROTECTED]> escribió:
> 
>> On Apr 1, 10:42 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
>>> En Tue, 01 Apr 2008 23:56:50 -0300, <[EMAIL PROTECTED]>
>>> escribió:
>>>
>>>    yield *iterable
>>>
>>> could be used as a shortcut for this:
>>>
>>>    for __temp in iterable: yield __temp
>>
>> How serious were you about that?
> 
> Not so much, I haven't thougth enough on it. Looks fine in principle,
> but yield expressions may be a problem.

Issue 2292: "Missing *-unpacking generalizations"
http://bugs.python.org/issue2292

Discussion on python-3000.devel:
http://thread.gmane.org/gmane.comp.python.python-3000.devel/12131

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

Training course in Los Angeles?

2008-04-04 Thread Student
Is there a training course in advanced-level Python in the Los Angeles
area? We are looking for web-development in particular.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: *.py source file surprisingly deleted with Pydev/Eclipse. Who else experienced this ?

2008-04-04 Thread Alex9968
Nebur wrote:
> No, I can't reproduce it, and I don't know whom to blame (Pydev?
> Eclipse ? The File System ? A Virus that only 2 times in half a year
> deletes a single file I'm busy working with, and seems to do nothing
> else? Myself beeing schizophrenic ??)
A virus created to remind you 2 times in half a year of the importance 
of backup operations ;-) . I'm joking. I don't know what is this, but 
I'm interested. Because my files won't be restorable from version 
control :-(
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: collecting results in threading app

2008-04-04 Thread George Sakkis
On Apr 4, 1:54 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Apr 4, 11:27 am, Gerardo Herzig <[EMAIL PROTECTED]> wrote:

> > There is an approach in which i can 'sum' after *any* thread finish?
>
> > Could a Queue help me there?
>
> Yes, you can push each result to a queue and have the main thread wait
> in a loop doing a queue.get() every time. After each get() you can do
> whatever with the results so far (partial sum, update a progress bar,
> etc.)
>
> 
> You can take a look at papyros [1],

I forgot the link: http://pypi.python.org/pypi/papyros/

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


Re: collecting results in threading app

2008-04-04 Thread George Sakkis
On Apr 4, 11:27 am, Gerardo Herzig <[EMAIL PROTECTED]> wrote:

> John Nagle wrote:
> >Gerardo Herzig wrote:
>
> >>Hi all. [EMAIL PROTECTED] over here. Im missing some point here, but cant
> >>figure out which one.
>
> >>This little peace of code executes a 'select count(*)' over every table
> >>in a database, one thread per table:
> >>
> >>class TableCounter(threading.Thread):
> >>   def __init__(self, conn, table):
> >>   self.connection = connection.Connection(host=conn.host,
> >>port=conn.port, user=conn.user, password='', base=conn.base)
> >>   threading.Thread.__init__(self)
> >>   self.table = table
>
> >>   def run(self):
> >>   result =  self.connection.doQuery("select count(*) from %s" %
> >>self.table, [])[0][0]
> >>   print result
> >>   return result
>
> >>class DataChecker(metadata.Database):
>
> >>   def countAll(self):
> >>   for table in self.tables:
> >>   t = TableCounter(self.connection, table.name)
> >>   t.start()
> >>   return
> >>
>
> >>It works fine, in the sense that every run() method prints the correct
> >>value.
> >>But...I would like to store the result of t.start() in, say, a list. The
> >>thing is, t.start() returns None, so...what im i missing here?
> >>Its the desing wrong?
>
> > 1.  What interface to MySQL are you using?  That's not MySQLdb.
> > 2.  If SELECT COUNT(*) is slow, check your table definitions.
> > For MyISAM, it's a fixed-time operation, and even for InnoDB,
> > it shouldn't take that long if you have an INDEX.
> > 3.  Threads don't return "results" as such; they're not functions.
>
> >As for the code, you need something like this:
>
> >class TableCounter(threading.Thread):
> >def __init__(self, conn, table):
> >  self.result = None
> >  ...
>
> > def run(self):
> > self.result =  self.connection.doQuery("select count(*) from %s" %
> >  self.table, [])[0][0]
>
> > def countAll(self):
> > mythreads = [] # list of TableCounter objects
> ># Start all threads
> > for table in self.tables:
> > t = TableCounter(self.connection, table.name)
> > mythreads.append(t) # list of counter threads
> > t.start()
> > # Wait for all threads to finish
> > totalcount = 0
> > for mythread in mythreads: # for all threads
> >mythread.join() # wait for thread to finish
> > totalcount += mythread.result  # add to result
> >print "Total size of all tables is:", totalcount
>
> >John Nagle
>
> Thanks John, that certanly works. According to George's suggestion, i
> will take a look to the Queue module.
> One question about
>
> for mythread in mythreads:  # for all threads
> mythread.join() # wait for thread to finish
>
> That code will wait for the first count(*) to finish and then continues
> to the next count(*). Because if is that so, it will be some kind of
> 'use threads, but execute one at the time'.
> I mean, if mytreads[0] is a very longer one, all the others will be
> waiting...rigth?

No, all will be executed in parallel; only the main thread will be
waiting for the first thread to finish. So if only the first job is
long, as soon as it finishes and join()s, all the others will already
have finished and their join() will be instantaneous.

> There is an approach in which i can 'sum' after *any* thread finish?
>
> Could a Queue help me there?

Yes, you can push each result to a queue and have the main thread wait
in a loop doing a queue.get() every time. After each get() you can do
whatever with the results so far (partial sum, update a progress bar,
etc.)


You can take a look at papyros [1], a small package I wrote for hiding
the details behind a simple Pythonic API. Using papyros, your example
would look something like this:


import sys
from papyros import Job
from papyros.multithreaded import MultiThreadedMaster

# a papyros.Job subclass for each type of task you want to run
concurrently
class CountJob(Job):
def __call__(self, connection, table_name):
return connection.doQuery("select count(*) from %s" %
table_name, [])[0][0]


class DataChecker(metadata.Database):
def countAll(self):
sum_count = 0
# create a pool of 4 threads
master = MultiThreadedMaster(4)
# issue all the jobs
for table in self.tables:
master.addJob(CountJob(self.connection, table.name))
# get each processed job as soon as it finishes
for job in iter(master.popProcessedJob, None):
# the job arguments are available as job.args
table_name = job.args[1]
try: # try to get the result
count = job.result
except Exception, ex:
# some exception was raised when executing this job
print '* Exception raised for table %s: %s' %
(tab

Re: *.py source file surprisingly deleted with Pydev/Eclipse. Who else experienced this ?

2008-04-04 Thread Nebur

> Are you using svn? I did have a problem once related to that (but it's

Hi Fabio,
No, there's no version control plugin. I use Mercurial, but externally
only.
I've considered a problem with version control, too.
But all external reasons (file sytem, virus, version control) seem
unplausible because when simply  removing the file from file system,
Eclipse would complain about the missing ressource.
So I have 2 ideas only: A _very_ strange bug inside the Eclipse/Plugin
process, or something with my brain ;-)
 Nebur
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: collecting results in threading app

2008-04-04 Thread John Nagle
Gerardo Herzig wrote:
> John Nagle wrote:
> 
>> Gerardo Herzig wrote:

> Thanks John, that certanly works. According to George's suggestion, i 
> will take a look to the Queue module.
> One question about
> 
> for mythread in mythreads:# for all threads
> mythread.join()# wait for thread to finish
> 
> 
> That code will wait for the first count(*) to finish and then continues 
> to the next count(*). Because if is that so, it will be some kind of 
> 'use threads, but execute one at the time'.

 No, all the threads are started in the first loop, and can run
their MySQL queries concurrently.  Once all threads have been
started, the second loop (above) waits for all of them to finish.

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


Re: troll poll

2008-04-04 Thread Aahz
In article <[EMAIL PROTECTED]>,
alex23  <[EMAIL PROTECTED]> wrote:
>
>That is awesome, thank you so much for posting this. The usual
>response to complaining about the lack of a killfile for Google Groups
>has been "use a decent client", but as I'm constantly moving between
>machines having a consistent app for usenet has more value to me.

That's why I ssh into my ISP for trn3.6  ;-)
-- 
Aahz ([EMAIL PROTECTED])   <*> 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: developing web spider

2008-04-04 Thread Kenji Noguchi
Attached is a essence of my crawler.  This collects  tag in a given URL

HTML parsing is not a big deal as "tidy" does all for you. It converts
a broken HTML
to a valid XHTML.  From that point there're wealth of XML libraries. Just write
whatever you want such as  element handler.

I've extended it for multi-thread, limit the number of thread for a
specific web host,
more flexible element handling, etc, etc. SQLite is nice for making URL db
by the way.

Kenji Noguchi
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, urllib, urllib2, cookielib
import xml.dom.minidom, tidy
from urlparse import urlparse, urljoin

_ua = "Mozilla/5.0 (Windows; U; Windows NT 6.0; ja; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12"

# I'm not sure if CookieJar() is thread safe
cj = cookielib.CookieJar()

class SingleCrawler:
def __init__(self, seed_url=None):
self.seed_url = seed_url
self.urls = {}

# static
def _convert(self, html):
if isinstance(html, unicode):
html = html.encode('utf-8')
options = dict(
doctype='strict',
drop_proprietary_attributes=True,
enclose_text=True,
output_xhtml=True,
wrap=0,
char_encoding='utf8',
newline='LF',
tidy_mark=False,
)
return str(tidy.parseString(html, **options))

def _collect_urls(self, node, nest=0):
if node.nodeType == 1 and node.nodeName == 'a':
href = node.getAttribute('href')
if not href.startswith('#'):
p = urlparse(href)
if p.scheme in ('', 'http', 'https'):
self.urls[node.getAttribute('href')] = True
else:
# mailto, javascript
print p.scheme

for i in node.childNodes:
self._collect_urls(i, nest+1)

def canonicalize(self):
d = {}

for url in self.urls:
d[urljoin(self.seed_url, url).encode('ascii')] = True
self.urls = d

def crawl(self):
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', _ua)]
try:
html = opener.open(self.seed_url).read()
except urllib2.HTTPError, e:
return None
except urllib2.URLError, e:
print "URL Error:", self.seed_url
return None
if html.startswith('')+2:]

html = self._convert(html)
try:
dom = xml.dom.minidom.parseString(html)
except ExpatError, e:
print "ExpatError:", html
return None

self._collect_urls(dom.childNodes[1])
self.canonicalize()
return self.urls.keys()

if __name__=='__main__':
crawler = SingleCrawler()
crawler.seed_url = 'http://www.python.org'
next_urls = crawler.crawl()
print next_urls
   

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

Re: Looking for Advanced Python Tutorials

2008-04-04 Thread 3c273
Thanks for this.
Louis

"Ravi Kotecha" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> On Apr 4, 12:58 pm, [EMAIL PROTECTED] wrote:
> > I was wondering if anyone knew of some online (free if possible)
> > advanced tutorials, especially ones that provides tasks and ideas for
> > small projects. The issue for myself is I want to improve my python
> > programming level, and my ability to program in general, but come up
> > blank thinking of a possible task or project to undertake. So with
> > that in mind I thought I'd ask the community if they knew of sites or
> > books to read up on and use as a starting block. Of course project
> > ideas would be great as well!
> >
> > Thanks for any help you can provide.
> >
> > Coko
>
> Project Euler is a site where you work through mathematical problems
> using any programming language you like.
>
> Once you solve a problem you can see everyone elses solutions and
> Python is quite popular on that site so you'll see some very clever
> uses of Python there.
>
> I like it a lot for when I haven't got anything better to code:
> http://projecteuler.net/
>
> - Ravi


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


Re: When does a binary extension gets the file extension '.pyd' and when is it '.so'

2008-04-04 Thread Fredrik Lundh
llothar wrote:

> On windows everything is '.pyd' but there seems to be two ways to get
> this on unix?

If you attempt to import the module "spam" on Windows, Python looks for 
"spam.dll" and "spam.pyd" (in addition to "spam.py/spam.pyw/spam.pyc" etc)

On most Unix platforms, Python looks for "spam.so" and "spammodule.so".

You can check what suffixes a given Python version uses via the "imp" 
module:

 >>> import imp
 >>> imp.get_suffixes()

To see *where* Python is looking as well, use the "-vv" flag:

 $ python -vv -c "import spam"
 ...
 # trying spam.so
 # trying spammodule.so
 # trying spam.py
 # trying spam.pyc
 ... etc

(-vv prints loads of stuff, so you may want to use "grep" to filter out 
the stuff you're interested in:

 $ python -vv -c "import spam" 2>&1 | grep spam

or, under Windows:

 > python -vv -c "import spam" 2> out.txt
 > findstr spam out.txt

)

> Why and what is the rule?

If you want Python to be able to import your binary extension, make sure 
to use a name it looks for.



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


Re: *.py source file surprisingly deleted with Pydev/Eclipse. Who else experienced this ?

2008-04-04 Thread Fabio Zadrozny
Hi Nebur,

Are you using svn? I did have a problem once related to that (but it's
more related to the svn plugin than to pydev)... I think that for some
reason the undo seems to be mapped to a creation of a file that came
from svn (I don't remember exactly how to reproduce it, but I do
remember it was associated only with svn -- cvs didn't have that
problem -- but it was something like trying to make undo on a file
that didn't have anything changed and then it would go to the svn and
remove another file).

Cheers,

Fabio

On Fri, Apr 4, 2008 at 12:38 PM, Nebur <[EMAIL PROTECTED]> wrote:
> Hi folks developing with Pydev/Eclipse,
>
>  this is the second time in about half a year that the following
>  surprise bites me:
>
>  I've switched between some files in Pydev/Eclipse using the
>  FileNavigator, and when I want to go back to my last-edited *.py file,
>  it is missing.
>  No more in the FileNavigator, no more in the OpenFiles-List of the
>  Editor. Removed anywhere. Erased from the file system. Restorable from
>  the version control only.
>  Only a young orphan *.pyc file is sitting around, showing me I haven't
>  dreamed of editing the file two minutes before.
>  I'm sure I did no delete operations with eclipse, and I'm sure I did
>  not use another application than eclipse in the meantime.
>
>  No, I can't reproduce it, and I don't know whom to blame (Pydev?
>  Eclipse ? The File System ? A Virus that only 2 times in half a year
>  deletes a single file I'm busy working with, and seems to do nothing
>  else? Myself beeing schizophrenic ??)
>
>  Someone else already had this effect ?
>   Nebur
>
>
>  PS: Debian Etch 64Bit/JFS,Eclipse3.3,Pydev1.3.14.
>  --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Tokenizer inconsistency wrt to new lines in comments

2008-04-04 Thread George Sakkis
The tokenize.generate_tokens function seems to handle in a context-
sensitive manner the new line after a comment:

>>> from StringIO import StringIO
>>> from tokenize import generate_tokens
>>>
>>> text = '''
... # hello world
... x = (
... # hello world
... )
... '''
>>>
>>> for t in generate_tokens(StringIO(text).readline):
... print repr(t[1])
...
'\n'
'# hello world\n'
'x'
'='
'('
'\n'
'# hello world'
'\n'
')'
'\n'
''

Is there a reason that the newline is included in the first comment
but not in the second, or is it a bug ?

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


Re: Is there an official way to add methods to an instance?

2008-04-04 Thread Charles Mason
And for such a behavior they've termed "monkeying"

Thus, the coinage "Monkeypatching" for what you want to do:

http://mail.python.org/pipermail/python-dev/2008-January/076194.html

There are a group of people who think "monkeypatching is destroying ruby."

You still probably should avoid it for production code.

On Fri, Apr 4, 2008 at 11:25 AM, John Nagle <[EMAIL PROTECTED]> wrote:

> Bruno Desthuilliers wrote:
> > Paul Rubin a écrit :
> >> Brian Vanderburg II <[EMAIL PROTECTED]> writes:
> >>> I've checked out some ways to get this to work.  I want to be able to
> >>> add a new function to an instance of an object.
> >>
> >> Ugh.  Avoid that if you can.
> >
> > Why so ? OO is about objects, not classes, and adding methods on a
> > per-object basis is perfectly legitimate.
>
>It's what professional programmers call a "l33t feature",
> one not suitable for production code.  Typically such features
> are used by programmers with about two years experience,
> trying too hard to prove that they're cool.
>
>John Nagle
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

UML reverse engineering

2008-04-04 Thread pierre-yves . dupont
Hello,

Do you know a free software witch can compute a UML class diagram from a python 
code. I tested many free UML softwares like BoUML, ArgoUML, Dia, PNSource (not 
found), UMLet and others ... But I didn't found what I needed.



-- 
Pierre-Yves Dupont-- 
http://mail.python.org/mailman/listinfo/python-list

Re: collecting results in threading app

2008-04-04 Thread Gerardo Herzig
John Nagle wrote:

>Gerardo Herzig wrote:
>  
>
>>Hi all. [EMAIL PROTECTED] over here. Im missing some point here, but cant 
>>figure out which one.
>>
>>This little peace of code executes a 'select count(*)' over every table 
>>in a database, one thread per table:
>>
>>class TableCounter(threading.Thread):
>>   def __init__(self, conn, table):
>>   self.connection = connection.Connection(host=conn.host, 
>>port=conn.port, user=conn.user, password='', base=conn.base)
>>   threading.Thread.__init__(self)
>>   self.table = table
>>
>>   def run(self):
>>   result =  self.connection.doQuery("select count(*) from %s" % 
>>self.table, [])[0][0]
>>   print result
>>   return result
>>
>>
>>class DataChecker(metadata.Database):
>>
>>   def countAll(self):
>>   for table in self.tables:
>>   t = TableCounter(self.connection, table.name)
>>   t.start()
>>   return
>>
>>
>>It works fine, in the sense that every run() method prints the correct 
>>value.
>>But...I would like to store the result of t.start() in, say, a list. The 
>>thing is, t.start() returns None, so...what im i missing here?
>>Its the desing wrong?
>>
>>
>
> 1.  What interface to MySQL are you using?  That's not MySQLdb.
> 2.  If SELECT COUNT(*) is slow, check your table definitions.
> For MyISAM, it's a fixed-time operation, and even for InnoDB,
> it shouldn't take that long if you have an INDEX.
> 3.  Threads don't return "results" as such; they're not functions.
>
>
>As for the code, you need something like this:
>
>class TableCounter(threading.Thread):
>def __init__(self, conn, table):
>  self.result = None
>  ...
>
> def run(self):
> self.result =  self.connection.doQuery("select count(*) from %s" %
>  self.table, [])[0][0]
>
>
> def countAll(self):
> mythreads = [] # list of TableCounter objects
>   # Start all threads
> for table in self.tables:
> t = TableCounter(self.connection, table.name)
> mythreads.append(t) # list of counter threads
> t.start()
> # Wait for all threads to finish
> totalcount = 0
> for mythread in mythreads:# for all threads
>   mythread.join() # wait for thread to finish
> totalcount += mythread.result # add to result
>   print "Total size of all tables is:", totalcount
>
>
>
>   John Nagle
>  
>
Thanks John, that certanly works. According to George's suggestion, i 
will take a look to the Queue module.
One question about

for mythread in mythreads:  # for all threads
mythread.join() # wait for thread to finish


That code will wait for the first count(*) to finish and then continues 
to the next count(*). Because if is that so, it will be some kind of 
'use threads, but execute one at the time'.
I mean, if mytreads[0] is a very longer one, all the others will be 
waiting...rigth?
There is an approach in which i can 'sum' after *any* thread finish?

Could a Queue help me there?
Thanks!

Gerardo

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


*.py source file surprisingly deleted with Pydev/Eclipse. Who else experienced this ?

2008-04-04 Thread Nebur
Hi folks developing with Pydev/Eclipse,

this is the second time in about half a year that the following
surprise bites me:

I've switched between some files in Pydev/Eclipse using the
FileNavigator, and when I want to go back to my last-edited *.py file,
it is missing.
No more in the FileNavigator, no more in the OpenFiles-List of the
Editor. Removed anywhere. Erased from the file system. Restorable from
the version control only.
Only a young orphan *.pyc file is sitting around, showing me I haven't
dreamed of editing the file two minutes before.
I'm sure I did no delete operations with eclipse, and I'm sure I did
not use another application than eclipse in the meantime.

No, I can't reproduce it, and I don't know whom to blame (Pydev?
Eclipse ? The File System ? A Virus that only 2 times in half a year
deletes a single file I'm busy working with, and seems to do nothing
else? Myself beeing schizophrenic ??)

Someone else already had this effect ?
 Nebur


PS: Debian Etch 64Bit/JFS,Eclipse3.3,Pydev1.3.14.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: collecting results in threading app

2008-04-04 Thread George Sakkis
On Apr 4, 10:42 am, Gerardo Herzig <[EMAIL PROTECTED]> wrote:

> Hi all. [EMAIL PROTECTED] over here. Im missing some point here, but cant
> figure out which one.
>
> This little peace of code executes a 'select count(*)' over every table
> in a database, one thread per table:
> 
> class TableCounter(threading.Thread):
> def __init__(self, conn, table):
> self.connection = connection.Connection(host=conn.host,
> port=conn.port, user=conn.user, password='', base=conn.base)
> threading.Thread.__init__(self)
> self.table = table
>
> def run(self):
> result =  self.connection.doQuery("select count(*) from %s" %
> self.table, [])[0][0]
> print result
> return result
>
> class DataChecker(metadata.Database):
>
> def countAll(self):
> for table in self.tables:
> t = TableCounter(self.connection, table.name)
> t.start()
> return
> 
>
> It works fine, in the sense that every run() method prints the correct
> value.
> But...I would like to store the result of t.start() in, say, a list. The
> thing is, t.start() returns None, so...what im i missing here?
> Its the desing wrong?

The simplest way is to just store it as an attribute in the
TableCounter instance:

 def run(self):
 self.result =  self.connection.doQuery(...)

Another alternative is to add it to a Queue. You can't use a list
unless you protect with a lock to prevent concurrent append()s, but
that's what Queues do anyway [1].

Regardless of where the results are stored, a second issue which you
don't address here is, how do you know that a given result or all
results are done ? Again there are several alternatives, but Python
2.5 adds two convenient Queue methods for this, task_done() and
join(). Check out the example at the bottom of the Queue doc page [2]
to see how it works.

HTH,
George


[1] http://docs.python.org/lib/module-Queue.html
[2] http://docs.python.org/lib/QueueObjects.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an official way to add methods to an instance?

2008-04-04 Thread John Nagle
Bruno Desthuilliers wrote:
> Paul Rubin a écrit :
>> Brian Vanderburg II <[EMAIL PROTECTED]> writes:
>>> I've checked out some ways to get this to work.  I want to be able to
>>> add a new function to an instance of an object.  
>>
>> Ugh.  Avoid that if you can.
> 
> Why so ? OO is about objects, not classes, and adding methods on a 
> per-object basis is perfectly legitimate.

It's what professional programmers call a "l33t feature",
one not suitable for production code.  Typically such features
are used by programmers with about two years experience,
trying too hard to prove that they're cool.

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


Re: collecting results in threading app

2008-04-04 Thread John Nagle
Gerardo Herzig wrote:
> Hi all. [EMAIL PROTECTED] over here. Im missing some point here, but cant 
> figure out which one.
> 
> This little peace of code executes a 'select count(*)' over every table 
> in a database, one thread per table:
> 
> class TableCounter(threading.Thread):
>def __init__(self, conn, table):
>self.connection = connection.Connection(host=conn.host, 
> port=conn.port, user=conn.user, password='', base=conn.base)
>threading.Thread.__init__(self)
>self.table = table
> 
>def run(self):
>result =  self.connection.doQuery("select count(*) from %s" % 
> self.table, [])[0][0]
>print result
>return result
> 
> 
> class DataChecker(metadata.Database):
> 
>def countAll(self):
>for table in self.tables:
>t = TableCounter(self.connection, table.name)
>t.start()
>return
> 
> 
> It works fine, in the sense that every run() method prints the correct 
> value.
> But...I would like to store the result of t.start() in, say, a list. The 
> thing is, t.start() returns None, so...what im i missing here?
> Its the desing wrong?

 1.  What interface to MySQL are you using?  That's not MySQLdb.
 2.  If SELECT COUNT(*) is slow, check your table definitions.
 For MyISAM, it's a fixed-time operation, and even for InnoDB,
 it shouldn't take that long if you have an INDEX.
 3.  Threads don't return "results" as such; they're not functions.


As for the code, you need something like this:

class TableCounter(threading.Thread):
def __init__(self, conn, table):
  self.result = None
  ...

 def run(self):
 self.result =  self.connection.doQuery("select count(*) from %s" %
  self.table, [])[0][0]


 def countAll(self):
 mythreads = [] # list of TableCounter objects
# Start all threads
 for table in self.tables:
 t = TableCounter(self.connection, table.name)
 mythreads.append(t) # list of counter threads
 t.start()
 # Wait for all threads to finish
 totalcount = 0
 for mythread in mythreads: # for all threads
mythread.join() # wait for thread to finish
 totalcount += mythread.result  # add to result
print "Total size of all tables is:", totalcount



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


Re: Nonlinear least square problem

2008-04-04 Thread Peter Spellucci

In article <[EMAIL PROTECTED]>,
 Uwe Kotyczka <[EMAIL PROTECTED]> writes:
 >Hallo, sorry for multiposting, but I am really looking
 >for some hint to solve my problem. And no, I don't
 >use Matlab, but maybe the matlab people have an idea
 >nevertheless.
 >
 >I have to solve a nonlinear least square problem.
 >Let me tell you some background first. Imagine
 >you have a tool to process some work piece, say
 >polishing some piece of glas. The tool behaves
 >different on different locations of the piece,
 >and I can describe that behaviour. Now the tool
 >shall smooth the surface of the workpiece.
 >Next I have information about the piece before
 >handling it. What I have to find is optimal
 >time curve for the tool to obtain a perfectly
 >smooth surface.
 >
 >How to formulate the problem?
 >Given a time vector (t_j) I have a function
 >g which calculates the remaining error (e_i)
 >(e_i) = g(t_j)
 >The rest error is given at, say, 100 points,
 >(t_j) is searched at 200 points.
 >My idea was to make the (t_j) a function of
 >some few parameters (t_j) = h(p_k), say 15
 >parameters. So the concatenated function
 >(e_i) = g(t_j) = g(h(p_k)) =: f(p_k) is to be minimized.
 >in the sense (e_i)-c -> Min, where c is a constant,
 >the end level of the surface.
 >
 >To solve this problem I use a "C" implementation
 >of the Levenberg-Marquardt algorithm as you can find
 >it in the LevMar Package (www.ics.forth.gr/~lourakis/levmar/).
 >
 >The function g contains the information about the
 >tool and about the initial surface. For the function
 >h I tried several approaches, making the time a
 >cubic spline of a selected times, or making it some
 >polynmial or...
 >
 >Now what is my problem? With the above I do find
 >solutions, however a lot of solutions seem to
 >give very similar remaining errors. The only problem
 >is that the corresponding time vectors, which are
 >(t_j_optimal) = h(p_k_optimal) look very different
 >from optimal solution to optimal solution.
 >In particular the optimization algorithm often prefers
 >solutions where the time vector is heavily oscillating.
 >
 >Now this is something I _must_ suppress, but I have no
 >idea how. The oscillation of the (t_j) depend of
 >the ansatz of h, of the number of parameters (p_k).
 >If f would be a linear function, then the matrix
 >representing it would be a band matrix with a lot
 >of diagonals nonzero. How many depends on the
 >ratio tool diameter to piece diameter.
 >
 >Now what are my question: Is the problem properly
 >formulated? Can I expect to find non-oscillating
 >solutions? Is it normal that taking more parameters
 >(p_k) makes the thing worse? What else should I
 >consider? Is this more verbal description sufficient?
 >
 >Thank you very much in advance.
 >
 >
 >
 > 

 wouldn't be the normal way to describe this problem be 
 an optimal control problem?
 and there will be constraints?
 let us take the example of the polishing problem: your tool must move 
 over the surface and will actually operate over a (small)disk: 
 you must design 
 a path of the disc center such that the working area of the tool covers the 
whole 
 surface. If you assume location dependent roughness, then it might be 
impossible 
 directly to polish one location perfectly, such that the path must be taken 
several times.
 maybe due to heating during the polishing process, it may be necessary to 
introduce gaps
 in the path in order to avoid overheating of some area. this may take time 
 and/or energy and you might want to solve a minimal time or minimal 
 energy problem subject to your constraints. if you are lucky, you end up 
 with a convex problem wwhich will exhibit a unique solution. otherwise
 you might be trapped in a local optimum. 
 such a path could be modeled by a spline curve for example, and as far as I
 know there are already industrial solvers for types of this problem.

 hth
 peter

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


collecting results in threading app

2008-04-04 Thread Gerardo Herzig
Hi all. [EMAIL PROTECTED] over here. Im missing some point here, but cant 
figure out which one.

This little peace of code executes a 'select count(*)' over every table 
in a database, one thread per table:

class TableCounter(threading.Thread):
def __init__(self, conn, table):
self.connection = connection.Connection(host=conn.host, 
port=conn.port, user=conn.user, password='', base=conn.base)
threading.Thread.__init__(self)
self.table = table

def run(self):
result =  self.connection.doQuery("select count(*) from %s" % 
self.table, [])[0][0]
print result
return result


class DataChecker(metadata.Database):

def countAll(self):
for table in self.tables:
t = TableCounter(self.connection, table.name)
t.start()
return


It works fine, in the sense that every run() method prints the correct 
value.
But...I would like to store the result of t.start() in, say, a list. The 
thing is, t.start() returns None, so...what im i missing here?
Its the desing wrong?

thanks!

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


Re: Unicode conversion problem (codec can't decode)

2008-04-04 Thread Eric S. Johansson

> 
> Almost there: use string-escape instead; it takes a byte string and  
> returns another byte string in ASCII.

perfect.  Exactly what I wanted.  thank you so very much.
> 
>> I really don't care about the character set used.  I'm looking for a  
>> matched set
>> of operations that converts the string to a seven bits a form and back  
>> to its
>> original form.
> 
> Ok, string-escape should work. But which database are you using that can't  
> handle 8bit strings?

I tripped over some bugs with pysqlite in terms of what it should and should 
not 
accept as text.  Now that I've gotten through my particular "crisis" I need to 
sit down and generate a test case so the problem can be fixed.

thanks again.

---eric

-- 
Speech-recognition in use.  It makes mistakes, I correct some.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for Advanced Python Tutorials

2008-04-04 Thread André
On Apr 4, 8:58 am, [EMAIL PROTECTED] wrote:
> I was wondering if anyone knew of some online (free if possible)
> advanced tutorials, especially ones that provides tasks and ideas for
> small projects. The issue for myself is I want to improve my python
> programming level, and my ability to program in general, but come up
> blank thinking of a possible task or project to undertake. So with
> that in mind I thought I'd ask the community if they knew of sites or
> books to read up on and use as a starting block. Of course project
> ideas would be great as well!
>

I suggest a different alternative: join an open source project.

André

> Thanks for any help you can provide.
>
> Coko

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


Re: Looking for Advanced Python Tutorials

2008-04-04 Thread Ravi Kotecha
On Apr 4, 12:58 pm, [EMAIL PROTECTED] wrote:
> I was wondering if anyone knew of some online (free if possible)
> advanced tutorials, especially ones that provides tasks and ideas for
> small projects. The issue for myself is I want to improve my python
> programming level, and my ability to program in general, but come up
> blank thinking of a possible task or project to undertake. So with
> that in mind I thought I'd ask the community if they knew of sites or
> books to read up on and use as a starting block. Of course project
> ideas would be great as well!
>
> Thanks for any help you can provide.
>
> Coko

Project Euler is a site where you work through mathematical problems
using any programming language you like.

Once you solve a problem you can see everyone elses solutions and
Python is quite popular on that site so you'll see some very clever
uses of Python there.

I like it a lot for when I haven't got anything better to code:
http://projecteuler.net/

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


Re: wsdl (soap) without code generation

2008-04-04 Thread Thomas Guettler
...

Thank you for your answers. I tried to parse the wsdl with two
libraries. (axis2 (java) and SOAPPy). Both fail because there
is no entry for 'service'.

The wsdl is from SAP XI.

Has someone hints?

  Thomas


-- 
Thomas Guettler, http://www.thomas-guettler.de/
E-Mail: guettli (*) thomas-guettler + de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python in High School

2008-04-04 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
(snip)
> I think I agree with all of the positive, supporting posts about
> Python. I would just like to add that Python (and PyGame) are open
> source

And run on most common platforms AFAIK.

> and so your students can download it at home and have fun
> exploring it on their own time (at their own pace). I think that is a
> real positive.

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


Looking for Advanced Python Tutorials

2008-04-04 Thread cokofreedom
I was wondering if anyone knew of some online (free if possible)
advanced tutorials, especially ones that provides tasks and ideas for
small projects. The issue for myself is I want to improve my python
programming level, and my ability to program in general, but come up
blank thinking of a possible task or project to undertake. So with
that in mind I thought I'd ask the community if they knew of sites or
books to read up on and use as a starting block. Of course project
ideas would be great as well!

Thanks for any help you can provide.

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


Re: Python-by-example - new online guide to Python Standard Library

2008-04-04 Thread AK
shurik wrote:
> that's great! thanks for putting this together. what about the inspect
> module? and particularly getsource :)
> 

Glad you like it! I will add every module eventually, but I'll put 
inspect up on top of todo list.

-- 
   -ak
Tobu | http://tobu.lightbird.net/ | Freeform DB / Tagger / PIM
Python-by-Example | http://pbe.lightbird.net/ | Guide to LibRef
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an official way to add methods to an instance?

2008-04-04 Thread Bruno Desthuilliers
Peter Otten a écrit :
(snip)

> Anyway, here is one more option to add too the zoo:
> 
 class A(object):
> ... def __init__(self, f, x):
> ... self._f = f
> ... self.x = x
> ... @property
> ... def f(self):
> ... return self._f.__get__(self)
> ... def __del__(self):
> ... print "deleting"
> ...

This is nice but requires that you know in advance how many methods 
you're going to add and how they will be named (which is not a bad thing 
in itself - on the contrary - but may not be what the OP is after), and 
that you can add these methods at instanciation time.

A variant could be:

class A(object):
 def __init__(self, x):
 self.x = x

 def __getattr__(self, name):
 target = '_' + name
 # avoids recursion
 if hasattr(self, target):
 func = getattr(self, target)
 if hasattr(func, '__get__'):
 return func.__get__(self, type(self))

 # nothing found, bye...
 raise AttributeError(
 "%s object has no attribute %s" % (self, name)
 )


a = A(21)
a._foo = lambda self: "answer is %s" % (self.x * 2)
print a.foo()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ignoring windows registry PythonPath subkeys

2008-04-04 Thread Thomas Heller
Floris Bruynooghe schrieb:
> Hi
> 
> We basically want the same as the OP in [1], i.e. when python starts
> up we don't want to load *any* sys.path entries from the registry,
> including subkeys of the PythonPath key.  The result of that thread
> seems to be to edit PC/getpathp.c[2] and recompile.
> 
> This isn't that much of a problem since we're compiling python anyway,
> but is that really still the only way?  Surely this isn't such an
> outlandish requirement?

If you look into PC/getpathp.c *and* PC/dl_nt.c, you'll find that the registry 
key name
if constructed from static components plus a variable component named 
PyWin_DLLVersionString.
The latter is loaded from a string resource (with resource ID 1000, IIRC) 
inside the pythonXY.dll.

This string resource can be changed (even without compiling!); so this is a way
for you to force the lookup of PythonPath to a different registry key.  You can 
choose
something that probably does not exist.

py2exe does this also for 'frozen' executables, and so has complete control
over sys.path.

Thomas

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


Re: Any fancy grep utility replacements out there?

2008-04-04 Thread Floris Bruynooghe
On Mar 19, 2:44 am, Peter  Wang <[EMAIL PROTECTED]> wrote:
> On Mar 18, 5:16 pm, Robert Kern <[EMAIL PROTECTED]> wrote:
>
>
>
> > [EMAIL PROTECTED] wrote:
> > > So I need to recursively grep a bunch of gzipped files.  This can't be
> > > easily done with grep, rgrep or zgrep.  (I'm sure given the right
> > > pipeline including using the find command it could be donebut
> > > seems like a hassle).
>
> > > So I figured I'd find a fancy next generation grep tool.  Thirty
> > > minutes of searching later I find a bunch in Perl, and even one in
> > > Ruby.  But I can't find anything that interesting or up to date for
> > > Python.  Does anyone know of something?
>
> > I have a grep-like utility I call "grin". I wrote it mostly to recursively 
> > grep
> > SVN source trees while ignoring the garbage under the .svn/ directories and 
> > more
> > or less do exactly what I need most frequently without configuration. It 
> > could
> > easily be extended to open gzip files with GzipFile.
>
> >https://svn.enthought.com/svn/sandbox/grin/trunk/
>
> > Let me know if you have any requests.
>
> And don't forget: Colorized output! :)

I tried to find something similar a while ago and found ack[1].  I do
realise it's written in perl but it does the job nicely.  Never needed
to search in zipfiles though, just unzipping them in /tmp would always
work...

I'll check out grin this afternoon!


Floris

[1] http://petdance.com/ack/

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


Ignoring windows registry PythonPath subkeys

2008-04-04 Thread Floris Bruynooghe
Hi

We basically want the same as the OP in [1], i.e. when python starts
up we don't want to load *any* sys.path entries from the registry,
including subkeys of the PythonPath key.  The result of that thread
seems to be to edit PC/getpathp.c[2] and recompile.

This isn't that much of a problem since we're compiling python anyway,
but is that really still the only way?  Surely this isn't such an
outlandish requirement?


Regards
Floris


[1]
http://groups.google.com/group/comp.lang.python/browse_frm/thread/4df87ffb23ac0c78/1b47f905eb3f990a?lnk=gst&q=sys.path+registry#1b47f905eb3f990a

[2] By looking at getpathp.c it seems just commenting out the two
calls to getpythonregpath(), for machinepath and userpath should work
in most cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RELEASED Python 2.6a2 and 3.0a4

2008-04-04 Thread Giampaolo Rodola'
On 4 Apr, 03:47, Barry Warsaw <[EMAIL PROTECTED]> wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> On behalf of the Python development team and the Python community, I'm  
> happy to announce the second alpha release of Python 2.6, and the  
> fourth alpha release of Python 3.0.
>
> Please note that these are alpha releases, and as such are not  
> suitable for production environments.  We continue to strive for a  
> high degree of quality, but there are still some known problems and  
> the feature sets have not been finalized.  These alphas are being  
> released to solicit feedback and hopefully discover bugs, as well as  
> allowing you to determine how changes in 2.6 and 3.0 might impact  
> you.  If you find things broken or incorrect, please submit a bug  
> report at
>
>    http://bugs.python.org
>
> For more information and downloadable distributions, see the Python  
> 2.6 web
> site:
>
>    http://www.python.org/download/releases/2.6/
>
> and the Python 3.0 web site:
>
>    http://www.python.org/download/releases/3.0/
>
> We are planning one more alpha release of each version, followed by  
> two beta releases, with the final releases planned for August 2008.  
> See PEP 361 for release details:
>
>      http://www.python.org/dev/peps/pep-0361/
>
> Enjoy,
> - -Barry
>
> Barry Warsaw
> [EMAIL PROTECTED]
> Python 2.6/3.0 Release Manager
> (on behalf of the entire python-dev team)
>
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v1.4.8 (Darwin)
>
> iQCVAwUBR/WImHEjvBPtnXfVAQJmoQP+MzqNDI+Xt8zua/FE7Ca4TVXoIIy2uoOm
> I1i3+vmevZ9vtAb9hcGwfEgPY4LSwb9Js4KnJJWMPaMuFJK4NgGoiMdj+t42zDbQ
> bEzfBUOCoVkejLRxIQnWeJf1Hu8JocYyCHIRffv57/QdKpHuiSs8aE8GIT3STo3o
> I88H5NY1GgI=
> =WT2z
> -END PGP SIGNATURE-

The Windows x86 MSI installer is missing for both 2.6 and 3.0.


--- Giampaolo
http://code.google.com/p/pyftpdlib
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an official way to add methods to an instance?

2008-04-04 Thread Bruno Desthuilliers
Paul Rubin a écrit :
> Brian Vanderburg II <[EMAIL PROTECTED]> writes:
>> I've checked out some ways to get this to work.  I want to be able to
>> add a new function to an instance of an object.  
> 
> Ugh.  Avoid that if you can.

Why so ? OO is about objects, not classes, and adding methods on a 
per-object basis is perfectly legitimate.

>  But see:
> 
>   http://en.wikipedia.org/wiki/Monkey_patch

Adding methods on a per-object basis is not monkey patching (as defined 
in the above article and as usually understood here) and doesn't address 
the same class (no pun intended) of problems.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python, Mysql, insert NULL

2008-04-04 Thread Pallavi Kale
Hello there, 

 

I was going through the thread of conversation happening around inserting
null using python into mysql. 

 

I am facing a similar problem here. I have to insert say 8 values into a
table using a stored procedure. Of the 8 values 2 are not null and the
remaining can be null, most of the values have datatypes as int or float.
When I try to pass null to these using python I keep getting None error from
the sql server.

 

I am using pymssql to talk to the database which is another reason the
parameters that I pass have to be type defined that is say @solutionID = %d
I, where @SolutionID is an integer type. 

 

Have anyone found a way to pass null into sql using python when the variable
is other than string, please let me know I am just learning python so I am
sure there must be a simpler and neater way to do it..

 

 

Thanks :-)

 

Best regards, 

 

Pallavi Kale 

 

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

Re: Unicode conversion problem (codec can't decode)

2008-04-04 Thread M.-A. Lemburg
On 2008-04-04 08:18, Jason Scheirer wrote:
> On Apr 3, 9:35 pm, "Eric S. Johansson" <[EMAIL PROTECTED]> wrote:
>> I'm having a problem (Python 2.4) converting strings with random 8-bit
>> characters into an escape form which is 7-bit clean for storage in a 
>> database.

If you don't want to process the 7-bit form in any way, there
are a couple of encodings which you could use:

>> Here's an example:
>>
>> body = meta['mini_body'].encode('unicode-escape')
>>
>> when given an 8-bit string, (in meta['mini_body']), the code fragment above
>> yields the error below.
>>
>> 'ascii' codec can't decode byte 0xe1 in position 13: ordinal not in 
>> range(128)

Try this:

body = meta['mini_body'].decode('latin-1').encode('unicode-escape')
mini_body = body.decode('unicode-escape').encode('latin-1')

or this:

body = meta['mini_body'].decode('latin-1').encode('utf-7')
mini_body = body.decode('utf-7').encode('latin-1')

If all you need is the 7-bit form, you're probably better of
with a base64 encoding:

body = meta['mini_body'].encode('base64')
mini_body = body.decode('base64')

>> the string that generates that error is:
>>
>> Reduce Whát You Owe by 50%. Get out of debt today!Reduuce Interest &
>> |V|onthlyy Paymeñts Easy, we will show you how..Freee Quote in 10
>> Min.http://www.freefromdebtin.net.cn

Looks like spam :-)

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Apr 04 2008)
 >>> Python/Zope Consulting and Support ...http://www.egenix.com/
 >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
 >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
Registered at Amtsgericht Duesseldorf: HRB 46611
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: object-relational mappers

2008-04-04 Thread Michael Ströder
M.-A. Lemburg wrote:
> On 2008-04-01 22:40, Aaron Watters wrote:
>> I've been poking around the world of object-relational
>> mappers and it inspired me to coin a corellary to the
>> the famous quote on regular expressions:
>>
>> "You have objects and a database: that's 2 problems.
>> So: get an object-relational mapper:
>> now you have 2**3 problems."
>>
>> That is to say I feel that they all make me learn
>> so much about the internals and features of the
>> O-R mapper itself that I would be better off rolling
>> my own queries on an as-needed basis without
>> wasting so many brain cells.
>>
>> comments?
> 
> I fully agree :-)

BTW: Some people implemented O/R mappers above python-ldap. All 
implementations I saw up to now are falling short regarding the 
complexity of the LDAP attribute sub-types, the syntactical rules for 
attribute type descriptive names and attribute name aliasing. So first a 
developer has also to evaluate whether a O/R mapper is really complete 
before using it.

Ciao, Michael.
-- 
http://mail.python.org/mailman/listinfo/python-list


urllib and bypass proxy

2008-04-04 Thread kc
Under MS Windows, I encountered a problem with the proxy bypass
specification. In windows, the bypass specification for the proxy
uses semi-colons to delimit entries. Mine happens to have two
semi-colons back-to-back. Internet explorer handles this just fine but
urllib equates this with ALWAYS bypass the proxy. (I'm using Python
2.5.2) 

This is caused because the double semi-colon is turned into an empty
string entry and at the bottom of urllib.py, and empty string can
always be found in a host name. Therefore it always chooses to bypass
the proxy. 

Of course the fix is to get rid of the double colon in the bypass
settings in internet explorer (which I did). But it took me an hour to
track this down (first time using urllib). Perhaps a better fix
would be to test for the empty string and continue the loop in that
case. From urllib.py: 

# now check if we match one of the registry values.
for test in proxyOverride:
if test == "": continue
test = test.replace(".", r"\.") # mask dots

This is not really a bug but rather a way to be more consistent with
internet explorer. If this has value, do I submit a bug report or does
someone else? 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an official way to add methods to an instance?

2008-04-04 Thread Paul Rubin
Brian Vanderburg II <[EMAIL PROTECTED]> writes:
> I've checked out some ways to get this to work.  I want to be able to
> add a new function to an instance of an object.  

Ugh.  Avoid that if you can.  But see:

  http://en.wikipedia.org/wiki/Monkey_patch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable scope in list comprehensions

2008-04-04 Thread Duncan Booth
Steve Holden <[EMAIL PROTECTED]> wrote:

>> For a moment I thought that maybe list comprehension has its own
>> scope, but it doesn't seem to be so:
>> print [[y for y in range(8)] for y in range(8)]
>> print y
>> 
>> Does anybody understand it?
>> 
>> 
> This isn't _a_ list comprehension, it's *two* list comprehensions. The
> interpreter computes the value if the inner list comprehension and
> then duplicates eight references to it (as you will see if you change
> an element).
> 
Do you want to reconsider that statement? The interpreter recomputes the 
inner list comprehension eight times, there are no duplicated 
references.

For the OP, in some languages (e.g. C) 'for' loops typically calculate 
the value of the loop control variable based on some expression 
involving the previous value. Python isn't like that. In Python the data 
used to compute the next value is stored internally: you cannot access 
it directly.

That means you can reassign or delete the loop control variable if you 
want, but it doesn't affect the loop iteration; every time round the 
loop there is a fresh assignment to the variable.

So the code:
   for y in range(8):
   for y in range(8):
  pass # or whatever the body of the loops

is sort of equivalent to:

   __loop_control_1__ = iter(range(8))
   while True:
  try:
  y = __loop_control_1__.next()
  except StopIteration:
  break
  __loop_control_2__ = iter(range(8))
  while True:
  try:
  y = __loop_control_1__.next()
  except StopIteration:
  break
  pass # or whatever the body of the loops

except there are no accessible variables __loop_control_1__ or 
__loop_control_2__.
-- 
http://mail.python.org/mailman/listinfo/python-list


INDIAN TAJ-MAHAL

2008-04-04 Thread TAJMAHAL TEMPLE
http://ttdtemple.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there an official way to add methods to an instance?

2008-04-04 Thread Peter Otten
Brian Vanderburg II wrote:

> I don't know if this is the correct place to send this question.

It is.
 
> I've checked out some ways to get this to work.  I want to be able to
> add a new function to an instance of an object.  I've tested two
> different methods that cause problems with 'deleting'/garbage collection
> (__del__ may never get called), but implemented one sort of hackishly
> maybe that works find. I'm wondering if there is more of an official way
> than mine.

[snip]

I think "Try hard to avoid __del__()" is as close to an official stance as
you can get ;)

Anyway, here is one more option to add too the zoo:

>>> class A(object):
... def __init__(self, f, x):
... self._f = f
... self.x = x
... @property
... def f(self):
... return self._f.__get__(self)
... def __del__(self):
... print "deleting"
...
>>> a = A(lambda s: s.x * 2, 2)
>>> b = A(lambda s: s.x * 3, 3)
>>> a.f()
4
>>> b.f()
9
>>> del a
deleting
>>> del b
deleting

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