Re: [Tutor] inconsistent destruction

2013-08-08 Thread Steven D'Aprano
On Wed, Aug 07, 2013 at 08:54:26PM -0700, Jim Mooney wrote:
 This bugs me for some reason. The final variable is saved in a for
 loop but not in a list comprehension. It just seems to me they should
 both be destroyed to avoid confusion.

The variable in a for-loop is deemed to be in the same scope as the rest 
of the function, the same as any other local variable. This is often 
very useful:


for item in objects:
if condition(item):
break
print(item)


If for-loops introduced their own scope, as they do in a few other 
languages, you would need to do something like this:

found = None
for item in objects:
if condition(item):
found = item
break
print(found)


On the other hand, list comprehensions (since Python 3) and generator 
expressions (always) are deemed to exist in their own scope. That makes 
conceptual sense, since a generator expression is its own chunk of 
executable code, like a function, and in fact are implemented much the 
same way that functions are implemented internally. List comps look the 
same, and since Python 3 are now treated the same. That way you can use 
a list comp or generator expression without worrying that its loop 
variable will clobber an existing local variable of the same name.


[...]
 Is there a form of for loop that would destroy the loop variable? I
 could always do del cnt right after the for, but that seems
 artificial.

Why do you care? The typical function is chock full of local variables 
that are used a few times, then hang around doing nothing until the 
function exits. This doesn't cause any problems in practice.



-- 
Steven
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Trouble, Please Help!

2013-08-08 Thread Alan Gauld

On 25/07/13 00:23, Jonathan Hong wrote:


because of my lack of computer knowledge. When I do put in python
helloworld.py into the command prompt line, the computer gives me a
response of: python: can't open file 'hello.py': [Errno 2] No such file


You need to supply the full path to the file (or be in the same 
directory as the file) when you try to run it.


Mostly on Windows you can run scripts from Windows explorer but for 
simple scripts (like hello world) the window appears and then 
dissappears too quickly to see it. You can most easily get around that 
by putting one of:


raw_input(Hit Enter to quit)   # for Python v2

input(Hit Enter to quit)   # for Python v3


as the last line in your script.

You might find that technique easier than using the CMD window.
But the CMD window is better when things go wrong - it lets you see any 
error messages,...


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread SM
I am defining multiple classes (some of them are threads)
I have been writing Python programs for a few months, but never faced this
issue so far unless I am doing something different inadvertently. The only
difference I see is that I am calling the methods belonging to other
classes, from a class which is also a thread.
 I see the following error:

AttributeError: 'Ui_MainWindow' object has no attribute
'textEdit_fwcmdlineoutput'

Code Snippets:

class Ui_MainWindow(object):
[snip]

def setStdoutToTextEditWindowFw(self):
  self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )
  sys.stdout = self.oldstdout

Calling the above method from within the class works fine. But I am calling
it from another class as below:

class bcThread(threading.Thread):
def __init__(self, cmd):
threading.Thread.__init__(self)
self.cmd = cmd
def run(self):
[snip]
Ui_MainWindow.setStdoutToTextEditWindowFw(Ui_MainWindow)

The highlighted line gives the following error :


Exception in thread Thread-1:
Traceback (most recent call last):
  File /usr/lib/python3.2/threading.py, line 740, in _bootstrap_inner
self.run()
  File bc_reports_tab.py, line 1299, in run
Ui_MainWindow.setStdoutToTextEditWindowFw(Ui_MainWindow)
  File bc_reports_tab.py, line 465, in setStdoutToTextEditWindowFw
self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )
AttributeError: type object 'Ui_MainWindow' has no attribute
'textEdit_fwcmdlineoutput'

I also tried many different ways of calling the method. The highlighted
line is one of them. Another one I tried is here where I create an
instance, which also gives the same error:

x = Ui_MainWindow()
x.setStdoutToTextEditWindowFw()

I see the same error.
Can someone guide me as to what is the correct way to do something like
this?


Thanks in advance.
-SM
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread Alan Gauld

On 08/08/13 17:23, SM wrote:

I am defining multiple classes (some of them are threads)
I have been writing Python programs for a few months, but never faced
this issue so far unless I am doing something different inadvertently.
The only difference I see is that I am calling the methods belonging to
other classes, from a class which is also a thread.


Your main issue is that you are trying to program using classes not objects.
The normal usage of classes is to create an object from the class and 
then call the methods via the objects. You can pass objects around as 
arguments to the methods etc.


So if you have two classes A and B you can create objects
from those called, say, a and b:

class A:
   def f(self):
  print 'in A.f'

class B:
   def g(self):
  print 'in B.g'
   def h(self,anObject)
  anObject.f()   #cxall method of the object passed in

#create the object instances
a = A()
b = B()
a2 = A()# a second object of class A.


#Now we can call the methods using the objects
a.f()   #- print in A.f
b.g()   #- print in B.g
a2.f()  #- print in A.f again

# pass object a into object B's h() method
b.h(a)  # use a from b to print in A.f
b.h(a2) # and again using a2 this time

So by creating objects within your threads you
can access the methods of your classes. You can even access
global level objects from multiple threads and share state
 - but be careful about synchronising and locking issues.

Finally you need to make sure your classes are visibnle in the threads 
that use them. So if you define a master class per thread and keep each 
in its own module then each module will need to import the other class 
modules before it can use them.


I'm going out soon and typed that in a hurry. I hope it makes sense and 
doesn't have too many mistakes(all untested!).


HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread SM
Ramit:
Thanks for the quick response. You are right about the error. When I did
the following:
x = Ui_MainWindow()
x.setStdoutToTextEditWindowFw()

I got the following error:
AttributeError: 'Ui_MainWindow' object has no attribute
'textEdit_fwcmdlineoutput'

But I do have code that creates an attribute in Ui_MainWindow() class:

self.textEdit_fwcmdlineoutput = QtGui.QTextEdit(self.tab_fw)

This is what is making me get confused as to why it complains that there is
no attribute.

Thanks,
-SM



On Thu, Aug 8, 2013 at 1:17 PM, Prasad, Ramit ramit.pra...@jpmorgan.comwrote:

 SM wrote:
 
  I am defining multiple classes (some of them are threads)
  I have been writing Python programs for a few months, but never faced
 this issue so far unless I am
  doing something different inadvertently. The only difference I see is
 that I am calling the methods
  belonging to other classes, from a class which is also a thread.
   I see the following error:
 
  AttributeError: 'Ui_MainWindow' object has no attribute
 'textEdit_fwcmdlineoutput'
  Code Snippets:
 
  class Ui_MainWindow(object):
  [snip]
 
  def setStdoutToTextEditWindowFw(self):
self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )
sys.stdout = self.oldstdout
  Calling the above method from within the class works fine. But I am
 calling it from another class as
  below:
 
  class bcThread(threading.Thread):
  def __init__(self, cmd):
  threading.Thread.__init__(self)
  self.cmd = cmd
  def run(self):
  [snip]
  Ui_MainWindow.setStdoutToTextEditWindowFw(Ui_MainWindow)
  The highlighted line gives the following error :
 
  Exception in thread Thread-1:
  Traceback (most recent call last):
File /usr/lib/python3.2/threading.py, line 740, in _bootstrap_inner
  self.run()
File bc_reports_tab.py, line 1299, in run
  Ui_MainWindow.setStdoutToTextEditWindowFw(Ui_MainWindow)
File bc_reports_tab.py, line 465, in setStdoutToTextEditWindowFw
  self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )
  AttributeError: type object 'Ui_MainWindow' has no attribute
 'textEdit_fwcmdlineoutput'
  I also tried many different ways of calling the method. The highlighted
 line is one of them. Another
  one I tried is here where I create an instance, which also gives the
 same error:
 
  x = Ui_MainWindow()
  x.setStdoutToTextEditWindowFw()
  I see the same error.

 I do not think that actually gave you the same error.
 Most likely it gave you a *similar* error. See the below.

  o = object()
  o.blah # on instance object, not class object
 AttributeError: 'object' object has no attribute 'blah'

  object.blah # on class object, not instance object
 AttributeError: type object 'object' has no attribute 'blah'


 If you got the top error from the snippet where you instantiate
 an instance of Ui_MainWindow then I believe some function must
 create the textEdit_fwcmdlineoutput attribute and that needs
 to be called first. I would have imagined this creation should
 occur on __init__ but obviously it must be somewhere else.
 You will need to call that section of code. It should be in
 the Ui_MainWindow class and look something like:

 self.textEdit_fwcmdlineoutput = create TextEdit object here

  Can someone guide me as to what is the correct way to do something like
 this?
 
  Thanks in advance.
  -SM
 



 This email is confidential and subject to important disclaimers and
 conditions including on offers for the purchase or sale of securities,
 accuracy and completeness of information, viruses, confidentiality, legal
 privilege, and legal entity disclaimers, available at
 http://www.jpmorgan.com/pages/disclosures/email.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread SM
Hi Alan,
Thanks for your quick and detailed reply.
I guess what you are suggesting is very similar to what I am doing (of
course not when I use the class. I tried using the class when I couldn't
figure out why it gave error when I used the object).  Looking at your
example, I ended up doing exactly what you suggested. I am sure I am
missing something, as it is giving the same error:
Here is what I am doing based on your suggestion:

class bcThread(threading.Thread):
def __init__(self, cmd):
threading.Thread.__init__(self)
self.cmd = cmd


def h(self, y):
y.setStdoutToTextEditWindowFw()   #(line 1277)

def run(self):
# Run the command first.
(data, err) = Popen(self.cmd, stdout=PIPE,
stderr=PIPE).communicate()
 [snip]
 x = Ui_MainWindow()
 self.h(x)# (line 1319)


class Ui_MainWindow(object)
def setupUi(self, MainWindow):
[snip]

self.textEdit_fwcmdlineoutput = QtGui.QTextEdit(self.tab_fw)

self.textEdit_fwcmdlineoutput.setObjectName(_fromUtf8(textEdit_fwcmdlineoutput))

[snip]
(line: 475)
def setStdoutToTextEditWindowFw(self):
self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )
sys.stdout = self.oldstdout


   The error looks like this:

Exception in thread Thread-1:
Traceback (most recent call last):
  File /usr/lib/python3.2/threading.py, line 740, in _bootstrap_inner
self.run()
  File bc_reports_tab.py, line 1319, in run
self.h(x)
  File bc_reports_tab.py, line 1277, in h
y.setStdoutToTextEditWindowFw()
  File bc_reports_tab.py, line 475, in setStdoutToTextEditWindowFw
self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )
AttributeError: 'Ui_MainWindow' object has no attribute
'textEdit_fwcmdlineoutput'


Wonder why it says the class/object has no attribute.

Thanks,
-SM


On Thu, Aug 8, 2013 at 1:22 PM, Alan Gauld alan.ga...@btinternet.comwrote:

 On 08/08/13 17:23, SM wrote:

 I am defining multiple classes (some of them are threads)
 I have been writing Python programs for a few months, but never faced
 this issue so far unless I am doing something different inadvertently.
 The only difference I see is that I am calling the methods belonging to
 other classes, from a class which is also a thread.


 Your main issue is that you are trying to program using classes not
 objects.
 The normal usage of classes is to create an object from the class and then
 call the methods via the objects. You can pass objects around as arguments
 to the methods etc.

 So if you have two classes A and B you can create objects
 from those called, say, a and b:

 class A:
def f(self):
   print 'in A.f'

 class B:
def g(self):
   print 'in B.g'
def h(self,anObject)
   anObject.f()   #cxall method of the object passed in

 #create the object instances
 a = A()
 b = B()
 a2 = A()# a second object of class A.


 #Now we can call the methods using the objects
 a.f()   #- print in A.f
 b.g()   #- print in B.g
 a2.f()  #- print in A.f again

 # pass object a into object B's h() method
 b.h(a)  # use a from b to print in A.f
 b.h(a2) # and again using a2 this time

 So by creating objects within your threads you
 can access the methods of your classes. You can even access
 global level objects from multiple threads and share state
  - but be careful about synchronising and locking issues.

 Finally you need to make sure your classes are visibnle in the threads
 that use them. So if you define a master class per thread and keep each in
 its own module then each module will need to import the other class modules
 before it can use them.

 I'm going out soon and typed that in a hurry. I hope it makes sense and
 doesn't have too many mistakes(all untested!).

 HTH
 --
 Alan G
 Author of the Learn to Program web site
 http://www.alan-g.me.uk/

 __**_
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/**mailman/listinfo/tutorhttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread Alan Gauld

On 08/08/13 21:24, SM wrote:


example, I ended up doing exactly what you suggested. I am sure I am
missing something, as it is giving the same error:
Here is what I am doing based on your suggestion:

class bcThread(threading.Thread):
 def h(self, y):
 y.setStdoutToTextEditWindowFw()   #(line 1277)


...

  [snip]
  x = Ui_MainWindow()
  self.h(x)# (line 1319)


So far so good.


class Ui_MainWindow(object)
 def setupUi(self, MainWindow):
 [snip]

 self.textEdit_fwcmdlineoutput = QtGui.QTextEdit(self.tab_fw)


This only comes into existence after setupUi is called.
Normally that would be in the UI init() method but you don;t
show any init or any other call to setupUi


self.textEdit_fwcmdlineoutput.setObjectName(_fromUtf8(textEdit_fwcmdlineoutput))



 def setStdoutToTextEditWindowFw(self):
 self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )


So this fails if setupUi has not been called earlier because the 
attribute has not been initialised yet.



 self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )
AttributeError: 'Ui_MainWindow' object has no attribute
'textEdit_fwcmdlineoutput'


You need to ensure that the UI __init__() method calls self.setupUi()
I suspect.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread SM
Is it necessary that the call should be in __init__? The widget is very
much getting created and I have the line (copied again here) under a method
setupUi() under Ui_MainWindow:

class Ui_MainWindow(object):
[snip]
def setupUi(self, MainWindow):
[snip]
self.textEdit_fwcmdlineoutput = QtGui.QTextEdit(self.tab_fw)

self.textEdit_fwcmdlineoutput.setObjectName(_fromUtf8(textEdit_fwcmdlineoutput))
self.gridLayout.addWidget(self.textEdit_fwcmdlineoutput, 6, 0, 1, 3)


Thanks,
-SM



On Thu, Aug 8, 2013 at 4:41 PM, Prasad, Ramit ramit.pra...@jpmorgan.comwrote:

 Please post responses in-line or at the bottom for this
 mailing list.

 SM wrote:
 
  Ramit:
  Thanks for the quick response. You are right about the error. When I did
 the following:
  x = Ui_MainWindow()
  x.setStdoutToTextEditWindowFw()
  I got the following error:
  AttributeError: 'Ui_MainWindow' object has no attribute
 'textEdit_fwcmdlineoutput'
  But I do have code that creates an attribute in Ui_MainWindow() class:
 
  self.textEdit_fwcmdlineoutput = QtGui.QTextEdit(self.tab_fw)
  This is what is making me get confused as to why it complains that there
 is no attribute.
  Thanks,
  -SM

 You need to call that line of code to create the widget. Obviously
 it is not being created from the class's __init__.


 ~Ramit



 This email is confidential and subject to important disclaimers and
 conditions including on offers for the purchase or sale of securities,
 accuracy and completeness of information, viruses, confidentiality, legal
 privilege, and legal entity disclaimers, available at
 http://www.jpmorgan.com/pages/disclosures/email.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread SM
On 08/08/13 21:24, SM wrote:

 example, I ended up doing exactly what you suggested. I am sure I am
 missing something, as it is giving the same error:
 Here is what I am doing based on your suggestion:

 class bcThread(threading.Thread):
  def h(self, y):
  y.setStdoutToTextEditWindowFw()   #(line 1277)


...

   [snip]
   x = Ui_MainWindow()
   self.h(x)# (line 1319)


So far so good.


 class Ui_MainWindow(object)
  def setupUi(self, MainWindow):
  [snip]

  self.textEdit_fwcmdlineoutput = QtGui.QTextEdit(self.tab_fw)


This only comes into existence after setupUi is called.
Normally that would be in the UI init() method but you don;t
show any init or any other call to setupUi

[SM] Sorry that I didn't add that part. setupUI is called from the main as
below:

if __name__ == __main__:
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())

Wonder if it is necessary to call it through __init__. I used Py Qt4
Designer to generate the skeleton of the Gui code and have been using it
like this for sometime now.

Thanks,
-SM

self.textEdit_fwcmdlineoutput.setObjectName(_fromUtf8(textEdit_fwcmdlineoutput))


  def setStdoutToTextEditWindowFw(self):
  self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )


So this fails if setupUi has not been called earlier because the attribute
has not been initialised yet.


  self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )
 AttributeError: 'Ui_MainWindow' object has no attribute
 'textEdit_fwcmdlineoutput'


You need to ensure that the UI __init__() method calls self.setupUi()
I suspect.


On Thu, Aug 8, 2013 at 4:57 PM, Alan Gauld alan.ga...@btinternet.comwrote:

 On 08/08/13 21:24, SM wrote:

  example, I ended up doing exactly what you suggested. I am sure I am
 missing something, as it is giving the same error:
 Here is what I am doing based on your suggestion:

 class bcThread(threading.Thread):
  def h(self, y):
  y.setStdoutToTextEditWindowFw(**)   #(line 1277)


 ...

[snip]
   x = Ui_MainWindow()
   self.h(x)# (line 1319)


 So far so good.


  class Ui_MainWindow(object)
  def setupUi(self, MainWindow):
  [snip]

  self.textEdit_fwcmdlineoutput = QtGui.QTextEdit(self.tab_fw)


 This only comes into existence after setupUi is called.
 Normally that would be in the UI init() method but you don;t
 show any init or any other call to setupUi

  self.textEdit_fwcmdlineoutput.**setObjectName(_fromUtf8(**
 textEdit_fwcmdlineoutput))


   def setStdoutToTextEditWindowFw(**self):
  self.textEdit_fwcmdlineoutput.**setText( sys.stdout.getvalue() )


 So this fails if setupUi has not been called earlier because the attribute
 has not been initialised yet.


   self.textEdit_fwcmdlineoutput.**setText( sys.stdout.getvalue() )
 AttributeError: 'Ui_MainWindow' object has no attribute
 'textEdit_fwcmdlineoutput'


 You need to ensure that the UI __init__() method calls self.setupUi()
 I suspect.


 --
 Alan G
 Author of the Learn to Program web site
 http://www.alan-g.me.uk/

 __**_
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/**mailman/listinfo/tutorhttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread Alan Gauld

On 08/08/13 22:03, SM wrote:


[SM] Sorry that I didn't add that part. setupUI is called from the main
as below:

if __name__ == __main__:
 import sys
 app = QtGui.QApplication(sys.argv)
 MainWindow = QtGui.QMainWindow()
 ui = Ui_MainWindow()
 ui.setupUi(MainWindow)
 MainWindow.show()
 sys.exit(app.exec_())

Wonder if it is necessary to call it through __init__.


Thats the problem.
You are creating a new instance inside your run() method but
the call in main() only sets it for the instance created in
main. It won't set it up for any other instance. You need
to call it every time you create a new object. Unless

If you put it in init() it will be called every time you
create a new instance. Much safer.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread Alan Gauld

On 08/08/13 23:02, eryksun wrote:


You are creating a new instance inside your run() method but
the call in main() only sets it for the instance created in
main. It won't set it up for any other instance. You need
to call it every time you create a new object. Unless

If you put it in init() it will be called every time you
create a new instance. Much safer.


I'm confused. Why does the OP want multiple instances of the user
interface widgets?



He may not, but he is creating them! But it is possible he does want 
multiple duplicate windows, one monitoring each thread. (eg progress 
dialogs on an FTP program). Since I don't know the context I'm

assuming he knows how many windows he wants!

If he does want just one then he needs to reference the global object in 
his run() method... But that brings us back into the land of 
synchronisation issues and threadsafe locks etc.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inconsistent destruction

2013-08-08 Thread David Hutto
if the variable is the range in the first one, then just don't append it,
and replace it with something else.

The second, you use cnt2, but it is a part of the the list comp, but not a
variable:

#this is in [ython 3, but you can import from future, or remove quotes from
print parameters
lst = [cnt2 for cnt2 in range(5)]
print(lst)

you want cnt2, but cnt2 is in the list comprehension, so it is a variable
within the list comp, but after it has been used there, then you need to
iterate through the list(lst), in order to find particular cnt's within the
lst list of cnt2 variables..



On Wed, Aug 7, 2013 at 11:54 PM, Jim Mooney cybervigila...@gmail.comwrote:

 This bugs me for some reason. The final variable is saved in a for
 loop but not in a list comprehension. It just seems to me they should
 both be destroyed to avoid confusion.

 lst = []
 for cnt in range(5):
 lst.append(cnt)
 cnt
 4

 lst = [cnt2 for cnt2 in range(5)]
 cnt2
 builtins.NameError: name 'cnt2' is not defined

 Is there a form of for loop that would destroy the loop variable? I
 could always do del cnt right after the for, but that seems
 artificial.

 --
 Jim
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




-- 
Best Regards,
David Hutto
*CEO:* *http://www.hitwebdevelopment.com*
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] hi

2013-08-08 Thread Vick
Hi,

It just plot one line. How to print several lines?

I've attached your example and I've corrected my own 3d code which works now
but it is not an animation. So how can I plot it using the code you gave me?

By the way, I think you know that I'm trying to plot for n-body problem?
Have you made a python code for the n-body problem? Mine works, but I'm just
having trouble with 3d plotting of the orbits. And also I have searched the
web on how to integrate conservation of energy as you suggested to me, but I
couldn't find any article that talks about 1st order ODEs for energy, and
the annotation is different from mine.

PS: Also how do you make the plot run only once without having to do it over
and over again?

Thanks
Vick

-Original Message-
From: Oscar Benjamin [mailto:oscar.j.benja...@gmail.com] 
Sent: Tuesday, 06 August, 2013 18:40
To: Vick
Cc: tutor@python.org
Subject: Re: [Tutor] hi

On 1 August 2013 12:32, Vick vick1...@orange.mu wrote:
 Hi,

Hi Vick, sorry I've been away and I've only had a chance to look at this
now.

 As per your request below, I have attached a stand-alone example 
 (test3d.py) of my problem. I am trying to plot in 3D using ion() from a
loop.

Basically don't use ion() for animation: it is intended for interactive use.
Use matplotlib's animation API for animation. See
here:
http://jakevdp.github.io/blog/2012/08/18/matplotlib-animation-tutorial/

I've put example scripts below. Both run fine on this computer. You'll want
a recent matplotlib version.

Here's a 2d animation script:

#!/usr/bin/env python
# 2d animation

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure(figsize=(5, 5))
ax = fig.add_axes([0.15, 0.15, 0.70, 0.70]) line, = ax.plot([], [],
linewidth=2)

def init():
ax.set_xlim([-1, 1])
ax.set_ylim([-1, 1])
line.set_data([], [])
return line,

def animate(i):
t = dt * np.arange(i)
x = np.cos(omega * t)
y = np.sin(omega * t)
line.set_data(x, y)
return line,

dt = .02 # in seconds
T = 10   # Period (seconds)
omega = 2 * np.pi / T  # 0.1 Hz

anim = animation.FuncAnimation(fig, animate, init_func=init,
   frames=int(T/dt), interval=int(1000*dt),
blit=True)

plt.show()


And here's a 3d script:

#!/usr/bin/env python
# 3d animation

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(5, 5))
ax = fig.add_axes([0.15, 0.15, 0.70, 0.70], projection='3d') line, =
ax.plot([], [], [], linewidth=2)

def init():
ax.set_xlim([-1, 1])
ax.set_ylim([-1, 1])
ax.set_zlim([0, 10])
line.set_data([], [])
return line,

def animate(i):
t = dt * np.arange(i)
x = np.cos(omega * t)
y = np.sin(omega * t)
z = t
line.set_data(x, y)
line.set_3d_properties(z)  # WTF!
return line,

dt = .02 # in seconds
T = 10   # Duration (seconds)
omega = 2 * np.pi  # 1 Hz

anim = animation.FuncAnimation(fig, animate, init_func=init,
   frames=int(T/dt), interval=int(1000*dt),
blit=True)

plt.show()




Oscar
from pylab import *
#import pylab
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d


def drange(start, stop, step):
r = start
while r  stop:
yield r
r += step


a=[]
b=[]
z1=[]
c=[]
d=[]
z2=[]




#plt.ion()

fig = plt.figure(dpi=100)
ax = axes3d.Axes3D(fig)#fig.add_subplot(111, projection = '3d')

t = 0
dt = 1
tn= 50

for i in drange (t+dt, tn,dt):
aa = sin(i)
bb = cos(i)
cc = aa*bb
aa1 = 1.5 *sin(i)
bb1 = 1.5*cos(i)
cc1 = aa1*bb1
a.append(aa)
b.append(bb)
z1.append(cc)
c.append(aa1)
d.append(bb1)
z2.append(cc1)
#clf()
#ax.plot(a,b,z1, marker='o', linestyle='None')
#ax.plot(c,d,z2, marker='o', linestyle='None')
ax.plot(a,b,z1)
ax.plot(c,d,z2)
plt.show()

#!/usr/bin/env python
# 2d animation

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

fig = plt.figure(figsize=(5, 5))
ax = fig.add_axes([0.15, 0.15, 0.70, 0.70])
line, = ax.plot([], [], linewidth=2)

def init():
ax.set_xlim([-1, 1])
ax.set_ylim([-1, 1])
line.set_data([], [])
return line,

def animate(i):
t = dt * np.arange(i)
x = np.cos(omega * t)
y = np.sin(omega * t)
line.set_data(x, y)
return line,

dt = .02 # in seconds
T = 10   # Period (seconds)
omega = 2 * np.pi / T  # 0.1 Hz

anim = animation.FuncAnimation(fig, animate, init_func=init,
   frames=int(T/dt), interval=int(1000*dt), 
blit=True)

plt.show()




#!/usr/bin/env python
# 3d animation

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(5, 5))
ax = fig.add_axes([0.15, 0.15, 0.70, 0.70], projection='3d')
line, = ax.plot([], [], 

Re: [Tutor] Question in regards to loops and matplotlib

2013-08-08 Thread Zachary Rizer
This looks quite clean! Since posting this question I have cleaned up this
script by using multiple functions, but it still isn't this clean! My data
is a normal CSV table with column headers. It isn't in a dictionary format
like your sample data here. I'm sure I could switch it to that format
though. I'll post a sample of my data, first 10 rows with column headers
here, and my current rendition of the code. Also, not to familiar with the
lambda function you did here. Little bit confused on how you split the
groups up. Anyway, new version of code and sample data:

I attached the ten row sample because it has 60 columns of info on each row
and would look huge pasted.


Zach Rizer
UVJ plot of n2 pop compare qui and sf disk and bulge pop
data = n2_qui_flag.csv


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patch
from matplotlib.path import Path

z1 = (0.6, 0.9, 0.59, 0.81, 2, 0.6z0.9)
z2 = (0.9, 1.3, 0.52, 0.89, 1.93, 0.9z1.3)
z3 = (1.3, 1.8, 0.49, 0.92, 1.9, 1.3z1.8)
z4 = (1.8, 2.5, 0.49, 0.92, 1.9, 1.8z2.5)

def redshift(table,z_range):

takes a given csv table and a chosen redshift range and spits
out a new array with only the objects with said redshift

z_data = []
for row in table:
if row['pz_z'] = z_range[0]  and row['pz_z']  z_range[1]:
z_data.append(row)
z_data = np.array(z_data)
return z_data

def quiescence(table,z_range):

takes given csv table and specific redshfit range and spits out
a two-tuple where first index of the tuple is the quiescent pop
and the second index is the star forming pop

qui_data = []
sf_data = []
for row in table:
if row['rf_UminV']  1.3 and row['rf_VminJ']  1.6 and
row['rf_UminV']  0.88*(row['rf_VminJ'])+z_range[2]:
qui_data.append(row)
else:
sf_data.append(row)
qui_data = np.array(qui_data)
sf_data = np.array(sf_data)
return qui_data, sf_data

def disk_vs_bulge(table):

turns given csv table into a two-tuple array where the first
index is the disk-dom pop and the second index is the bulge-dom
pop: these cuts are determined by visclass data

disk_data = []
bulge_data = []
for row in table:
if row['vc_Dv']  0.65 and row['vc_DSw']  0.65:
disk_data.append(row)
elif row['vc_Dv']  0.35 and row['vc_DSw']  0.65:
bulge_data.append(row)
disk_data = np.array(disk_data)
bulge_data = np.array(bulge_data)
return disk_data, bulge_data

def make_mass_cuts(table):

make mass cuts using logMass row and creates four-tuple
each index is divided into its own dual tuple, x and y UVJ colors
array returned = [(m1_x, m1_y), (m2_x, m2_y), (m3_x, m3_y), (m4_x,
m4_y)]

m1_x = []
m1_y = []
m2_x = []
m2_y = []
m3_x = []
m3_y = []
m4_x = []
m4_y = []
for row in table:
if row['ms_lmass'] = 9.7 and row['ms_lmass']  10:
m1_x.append(row['rf_VminJ'])
m1_y.append(row['rf_UminV'])
elif row['ms_lmass'] = 10 and row['ms_lmass']  10.5:
m2_x.append(row['rf_VminJ'])
m2_y.append(row['rf_UminV'])
elif row['ms_lmass'] = 10.5 and row['ms_lmass']  10.8:
m3_x.append(row['rf_VminJ'])
m3_y.append(row['rf_UminV'])
elif row['ms_lmass'] = 10.8:
m4_x.append(row['rf_VminJ'])
m4_y.append(row['rf_UminV'])
return [(m1_x, m1_y), (m2_x, m2_y), (m3_x, m3_y), (m4_x, m4_y)]

def plots(m_q_disk, m_q_bulge, m_sf_disk, m_sf_bulge):

plot the first column as x, and second column as y
takes all four mass arrays and plots all 16 subplots
returns a 3-tuple of plot of qui_bulge, sf_bulge, sf_disk for legend

plt.plot(m_q_disk[3][0], m_q_disk[3][1], 'wo', ms=12)
qui_bulge_label, = plt.plot(m_q_bulge[3][0], m_q_bulge[3][1], 'ro',
ms=12)
plt.plot(m_q_disk[2][0], m_q_disk[2][1], 'wo', ms=9)
plt.plot(m_q_bulge[2][0], m_q_bulge[2][1], 'ro', ms=9)
plt.plot(m_q_disk[1][0], m_q_disk[1][1], 'wo', ms=6)
plt.plot(m_q_bulge[1][0], m_q_bulge[1][1], 'ro', ms=6)
plt.plot(m_q_disk[0][0], m_q_disk[0][1], 'wo', ms=3)
plt.plot(m_q_bulge[0][0], m_q_bulge[0][1], 'ro', ms=3)

sf_disk_label, = plt.plot(m_sf_disk[3][0], m_sf_disk[3][1], 'wo', ms=12)
sf_bulge_label, = plt.plot(m_sf_bulge[3][0], m_sf_bulge[3][1], 'bo',
ms=12)
plt.plot(m_sf_disk[2][0], m_sf_disk[2][1], 'wo', ms=9)
plt.plot(m_sf_bulge[2][0], m_sf_bulge[2][1], 'bo', ms=9)
plt.plot(m_sf_disk[1][0], m_sf_disk[1][1], 'wo', ms=6)
plt.plot(m_sf_bulge[1][0], m_sf_bulge[1][1], 'bo', ms=6)
plt.plot(m_sf_disk[0][0], m_sf_disk[0][1], 'wo', ms=3)
plt.plot(m_sf_bulge[0][0], m_sf_bulge[0][1], 'bo', ms=3)

return qui_bulge_label, sf_bulge_label, sf_disk_label

def make_hash_region(z_range):
make quiescent region
verts = [(-1.,1.3),
 (z_range[3],1.3),
 

[Tutor] Python Programming for the absolute beginner 3e Ch3 Challenge 4

2013-08-08 Thread John Feleppa
Hello,

I am working through Michael Dawson's book, Python Programming for the
absolute beginner 3rd edition.

Have just completed Chapter 3, but cannot solve Challenge 4.

Has anyone solved this yet - and be willing to share this code?

I would much appreciate..

John.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Online references for Python

2013-08-08 Thread Travis Farley
I've also found this to be helpful:

http://www.diveintopython.net/toc/index.html

It's a little dated but most of the information still applies.


On Mon, Jul 29, 2013 at 10:29 AM, Rene Datta reneda...@gmail.com wrote:

 Hi:

 I was wondering if anyone could suggest a good quality online resource
 tool or compendium to provide a beginner's level of information to start
 learning the Python language.

 Thank you.

 Rene Datta
 reneda...@gmail.com

 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inconsistent destruction

2013-08-08 Thread David Hutto
In other words lst is a global variable, where as cnt2 is a local variable
to just the list comps completion of the data being diplayed in the list
comp, with each cnt2 in the global var lst being contained in the list
comp, but only accessible through iteration/placing/splicing of the lst
variable that corresponds within the lst global variable which uses list
methods.


On Thu, Aug 8, 2013 at 12:15 AM, David Hutto dwightdhu...@gmail.com wrote:

 if the variable is the range in the first one, then just don't append it,
 and replace it with something else.

 The second, you use cnt2, but it is a part of the the list comp, but not a
 variable:

 #this is in [ython 3, but you can import from future, or remove quotes
 from print parameters
 lst = [cnt2 for cnt2 in range(5)]
 print(lst)

 you want cnt2, but cnt2 is in the list comprehension, so it is a variable
 within the list comp, but after it has been used there, then you need to
 iterate through the list(lst), in order to find particular cnt's within the
 lst list of cnt2 variables..



 On Wed, Aug 7, 2013 at 11:54 PM, Jim Mooney cybervigila...@gmail.comwrote:

 This bugs me for some reason. The final variable is saved in a for
 loop but not in a list comprehension. It just seems to me they should
 both be destroyed to avoid confusion.

 lst = []
 for cnt in range(5):
 lst.append(cnt)
 cnt
 4

 lst = [cnt2 for cnt2 in range(5)]
 cnt2
 builtins.NameError: name 'cnt2' is not defined

 Is there a form of for loop that would destroy the loop variable? I
 could always do del cnt right after the for, but that seems
 artificial.

 --
 Jim
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor




 --
 Best Regards,
 David Hutto
 *CEO:* *http://www.hitwebdevelopment.com*




-- 
Best Regards,
David Hutto
*CEO:* *http://www.hitwebdevelopment.com*
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] constrained least square fitting using python

2013-08-08 Thread sudipta
Hi All,

I am facing a problem for constrained linear least square fitting. In my
case the matrix equation looks like [Y]nX1=[X]nXm[P]mX1, where Y and P are
vectors and X is a matrix and n, m are dimension of the matrix. Further,
there is a equality constraint on P which is Sum(P(i))=0.0. How do I
proceed to solve that? Which function of python is suitable for this? I saw
few of discussion on scipy.optimize.fmin_slsqp() function but the
implementation of this function is not very straightforward. Therefore, I
need your help. I am new in SCIPY. Please help me out in this regard.
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] inconsistent destruction

2013-08-08 Thread Japhy Bartlett
you can either manually manage the memory with `del cnt` or let the built
in memory management .. manage the memory.


On Wed, Aug 7, 2013 at 10:54 PM, Jim Mooney cybervigila...@gmail.comwrote:

 This bugs me for some reason. The final variable is saved in a for
 loop but not in a list comprehension. It just seems to me they should
 both be destroyed to avoid confusion.

 lst = []
 for cnt in range(5):
 lst.append(cnt)
 cnt
 4

 lst = [cnt2 for cnt2 in range(5)]
 cnt2
 builtins.NameError: name 'cnt2' is not defined

 Is there a form of for loop that would destroy the loop variable? I
 could always do del cnt right after the for, but that seems
 artificial.

 --
 Jim
 ___
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Programming for the absolute beginner 3e Ch3 Challenge 4

2013-08-08 Thread Alan Gauld

On 08/08/13 18:05, John Feleppa wrote:


I am working through Michael Dawson's book, Python Programming for the
absolute beginner 3rd edition.

Have just completed Chapter 3, but cannot solve Challenge 4.

Has anyone solved this yet - and be willing to share this code?


If you give us a clue what it is then more of us might be able to give 
you a hint... Especially if you tell us what you've tried so far.

Also what python version you are using...


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] constrained least square fitting using python

2013-08-08 Thread Alan Gauld

On 07/08/13 22:37, sudipta wrote:


this? I saw few of discussion on scipy.optimize.fmin_slsqp() function
but the implementation of this function is not very straightforward.
Therefore, I need your help. I am new in SCIPY. Please help me out in


This list is really aimed at newcomers to Python and is standard 
library. You probably will get a better response on a dedicated

scipy forum/mailing list.

However, we do have a few scipy users here too so you might be lucky.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread SM
I'm confused. Why does the OP want multiple instances of the user
interface widgets?

 He may not, but he is creating them! But it is possible he does want
multiple duplicate windows, one monitoring each thread. (eg progress
dialogs on an FTP program). Since I don't know the context I'm
assuming he knows how many windows he wants!

If he does want just one then he needs to reference the global object in
his run() method... But that brings us back into the land of
synchronisation issues and threadsafe locks etc.

OP is me? Not sure what it stands for, but I am a 'she' :)
Since you asked here is some context on what I am trying to do:
I don't want multiple instances of the widget. I have a Gui with 3 tabs,
each for a different purpose, with a unique functionality within the main
window.  Each tab has only one instance of this widget I am asking question
about. Everything is working great with full functionality. As an added
feature, I am now asked to have a progress bar widget which appears when
an operation is going on, to tell the user that he/she has to wait. So I am
running two threads - first one is the progressbar widget which has a
rectangular slab spinning sideways to indicate that the operation is going
on. The second thread is the one which is actually doing the operation . I
have a flag that the second thread sets after the job is done, which the
widget thread keeps checking in a loop and stops spinning and gets out of
the loop when the flag is set.  I have that working as well.
I also have a textEdit window on the Gui where I redirect all the standard
output using StringIO. For that I use the following code:
Before the operation starts, I call the following:
self.oldstdout = sys.stdout
sys.stdout = StringIO()

After the operation, I call the method:
  def setStdoutToTextEditWindowFw(self):
self.textEdit_fwcmdlineoutput.setText( sys.stdout.getvalue() )
sys.stdout = self.oldstdout
I need to call it from the thread after the job is done, so the text I want
to output on the command line will show up on the textEdit window on the
Gui.

The above method is defined on Ui_MainWindow class. The widget gets created
in the method setupUI which is defined under Ui_MainWindow class:
self.textEdit_fwcmdlineoutput = QtGui.QTextEdit(self.tab_fw)

Alan indicated that it should be called by __init__.
I tried doing it and the gui crashed!  (I am yet to see why and where it
crashed)
I am not sure I know what the problem or the solution is. Hence the email
Thanks for all your time, suggestions and help.

Thanks,
-SM



On Thu, Aug 8, 2013 at 6:30 PM, Alan Gauld alan.ga...@btinternet.comwrote:

 On 08/08/13 23:02, eryksun wrote:

  You are creating a new instance inside your run() method but
 the call in main() only sets it for the instance created in
 main. It won't set it up for any other instance. You need
 to call it every time you create a new object. Unless

 If you put it in init() it will be called every time you
 create a new instance. Much safer.


 I'm confused. Why does the OP want multiple instances of the user
 interface widgets?



 He may not, but he is creating them! But it is possible he does want
 multiple duplicate windows, one monitoring each thread. (eg progress
 dialogs on an FTP program). Since I don't know the context I'm
 assuming he knows how many windows he wants!

 If he does want just one then he needs to reference the global object in
 his run() method... But that brings us back into the land of
 synchronisation issues and threadsafe locks etc.


 --
 Alan G
 Author of the Learn to Program web site
 http://www.alan-g.me.uk/

 __**_
 Tutor maillist  -  Tutor@python.org
 To unsubscribe or change subscription options:
 http://mail.python.org/**mailman/listinfo/tutorhttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to access a method defined in one class from another class (which is a thread) in Python3?

2013-08-08 Thread Marc Tompkins
On Thu, Aug 8, 2013 at 7:15 PM, Joel Goldstick joel.goldst...@gmail.comwrote:

 On Thu, Aug 8, 2013 at 9:52 PM, SM sunith...@gmail.com wrote:

 
  OP is me? Not sure what it stands for, but I am a 'she' :)

 FYI (For you information) OP means Original Poster.  Although people
 do refer to names in replies here, the term OP is used quite often.
 As for the implication of he not she, I guess we are stuck with
 guessing in English usage. (They doesn't cut it with Language mavens!)
 Good to have shes' to get more diverse user base.  Best thing about
 user groups is that different backgrounds make for better discussions
 and interesting ways of solving problems

 You know the old joke: on the Internet, nobody knows you're a dog...
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor