From phil_lor at bigpond.com  Mon Apr  1 02:01:47 2013
From: phil_lor at bigpond.com (Phil)
Date: Mon, 01 Apr 2013 10:01:47 +1000
Subject: [Tutor] pyqt4 set horizontal header item - extra info
In-Reply-To: <CACL+1au3Go+OS3Reczzdw96sCM72Ywp2mwa9N-VXJ-Q9f-=FTQ@mail.gmail.com>
References: <5157BBC6.20408@bigpond.com> <5157E60C.9000601@bigpond.com>
	<kj8rqp$9h5$1@ger.gmane.org>
	<CACL+1au3Go+OS3Reczzdw96sCM72Ywp2mwa9N-VXJ-Q9f-=FTQ@mail.gmail.com>
Message-ID: <5158CE6B.2090502@bigpond.com>

On 31/03/13 21:43, eryksun wrote:
<cut>

>
> You can use setHorizontalHeaderItem(0, QTableWidgetItem('col 0'), and
> so on. It may be simpler to use setHorizontalHeaderLabels(['col 0',
> 'col 1', 'etc']).
>

Thanks Eryksun,

I had already tried your suggestion last night and this is the result;

"global name 'QTableWidgetItem' is not defined"

You are correct, I can easily set all of the labels at once but only one 
label needs to be modified according to it's cell contents. I'm sure I'm 
missing something very basic.

-- 
Regards,
Phil

From arwh at yahoo.com  Mon Apr  1 03:18:52 2013
From: arwh at yahoo.com (ah)
Date: Sun, 31 Mar 2013 18:18:52 -0700 (PDT)
Subject: [Tutor] is there a simple stand alone python app I can use on my
	Kindle fire?
Message-ID: <1364779132.91062.YahooMailNeo@web162401.mail.bf1.yahoo.com>

Hello,


I'm enjoying learning python, and would like to be able to study and practice on the go, using my kindle fire reader. (wifi enabled).


Amazon does have an app, Qpython lite, but requires a? live wifi connection to the internet to run. I'm looking for a simple python app, stand alone that i can run on my kindle, without an internet connection,? just to practice while i learn. (Just a simple terminal, and text editor, and python? like ubuntu offers.)


I've tried downloading portable python, and couldnt' get it to run ('can't run in DOS mode?'), I've tried downloading ubuntu to my kindle and couldn't, and tried downloading the whole 2.7 python app, but couldn't get it to run.

I tried to root my kindle, but as I'm inexperienced in things tech, i'm not sure if I was successful, and not sure how this helps (if I was successful.)


I have both windows 7 and ubuntu (dual boot) on my laptop, and can connect my kindle to the laptop via usb cable. I have "accept downloads from other applications" enabled on my kindle. On my kindle I have 'better terminal emulator pro' , ES file explorer, and droidedit.


Any help is appreciated, I'm willing to follow step by step instructions to get python running on my kindle. I will supply any other details required.


My kindle fire specs are : Model D01400



The Kindle Fire features a 7? display module from LG Display. The 
display is dual-sourced between LG Display and E Ink Holdings. The 
display touchscreen appears to be conventional capacitive glass on glass and the control IC on the touchscreen is from a previously unseen 
source. Meanwhile, the OMAP4430 applications processor from Texas 
Instruments is a dual-core RM Cortex-A9, 1GHz processor with IVA 3 
Hardware Accelerator, SGX540 3D Graphic Core, 1080P 2D, 720P 3D and is 
produced in 45nm process geometry. 

Other key features include a
 8GB eMMC NAND Flash Memory, 4Gbits of low power DDR2, a 3.7V battery 
with 4400mAh capacity (or about 16 Wh), and a module from Jorjin, which 
is based on Texas Instruments? WL1270. 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130331/dff1990d/attachment.html>

From phil_lor at bigpond.com  Mon Apr  1 02:13:00 2013
From: phil_lor at bigpond.com (Phil)
Date: Mon, 01 Apr 2013 10:13:00 +1000
Subject: [Tutor] pyqt4 set horizontal header item - solved
In-Reply-To: <CACL+1au3Go+OS3Reczzdw96sCM72Ywp2mwa9N-VXJ-Q9f-=FTQ@mail.gmail.com>
References: <5157BBC6.20408@bigpond.com> <5157E60C.9000601@bigpond.com>
	<kj8rqp$9h5$1@ger.gmane.org>
	<CACL+1au3Go+OS3Reczzdw96sCM72Ywp2mwa9N-VXJ-Q9f-=FTQ@mail.gmail.com>
Message-ID: <5158D10C.8080706@bigpond.com>

On 31/03/13 21:43, eryksun wrote:
<cut>

> You can use setHorizontalHeaderItem(0, QTableWidgetItem('col 0'), and
> so on. It may be simpler to use setHorizontalHeaderLabels(['col 0',
> 'col 1', 'etc']).
>

I have the answer (provided by a member of another list) and I was 
correct, it was something basic.

from PyQt4 import QtGui
QtGui.QTable etc

As I previously said, I had done this under C++ many years ago. The 
Python method is far simpler, especially once you know how.

-- 
Regards,
Phil

From steve at pearwood.info  Mon Apr  1 06:33:20 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 01 Apr 2013 15:33:20 +1100
Subject: [Tutor] is there a simple stand alone python app I can use on
 my Kindle fire?
In-Reply-To: <1364779132.91062.YahooMailNeo@web162401.mail.bf1.yahoo.com>
References: <1364779132.91062.YahooMailNeo@web162401.mail.bf1.yahoo.com>
Message-ID: <51590E10.2030202@pearwood.info>

On 01/04/13 12:18, ah wrote:
> Hello,
>
>
> I'm enjoying learning python, and would like to be able to study and practice on the go, using my kindle fire reader. (wifi enabled).
>
>
> Amazon does have an app, Qpython lite, but requires a  live wifi connection to the internet to run. I'm looking for a simple python app, stand alone that i can run on my kindle, without an internet connection,  just to practice while i learn. (Just a simple terminal, and text editor, and python? like ubuntu offers.)


This is a list for learning Python, not the details of arbitrary locked-down proprietary platforms. You might be lucky and have a response from somebody who knows how to get Python working on a Kindle, but probably not.

Your best bet is to ask on a Kindle forum, or failing that, try on the main Python mailing list:

python-list at python.org

also available on Usenet:

comp.lang.python

Because there are a lot more people on that list, you have a better chance of finding someone with a Kindle who knows how to get Python working on it.

The first step should be to try goggling:

https://www.google.com.au/search?q=running+python+on+kindle

If you do get an answer on some other forum, please post the answer here so anyone searching the archives will find the answer.



-- 
Steven

From eryksun at gmail.com  Mon Apr  1 11:47:36 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 1 Apr 2013 05:47:36 -0400
Subject: [Tutor] pyqt4 set horizontal header item - solved
In-Reply-To: <5158D10C.8080706@bigpond.com>
References: <5157BBC6.20408@bigpond.com> <5157E60C.9000601@bigpond.com>
	<kj8rqp$9h5$1@ger.gmane.org>
	<CACL+1au3Go+OS3Reczzdw96sCM72Ywp2mwa9N-VXJ-Q9f-=FTQ@mail.gmail.com>
	<5158D10C.8080706@bigpond.com>
Message-ID: <CACL+1attYSUJ-1tO-ax=1S8gkp_S0URiAvunc3xEXq=cfn22Yw@mail.gmail.com>

On Sun, Mar 31, 2013 at 8:13 PM, Phil <phil_lor at bigpond.com> wrote:
>
> I have the answer (provided by a member of another list) and I was correct,
> it was something basic.
>
> from PyQt4 import QtGui
> QtGui.QTable etc

Sorry, I assumed you were familiar with the package layout.

http://pyqt.sourceforge.net/Docs/PyQt4/qtablewidgetitem.html

Notice the subtitle that says "[QtGui module]".

http://pyqt.sourceforge.net/Docs/PyQt4/classes.html
http://pyqt.sourceforge.net/Docs/PyQt4/qtgui.html
http://pyqt.sourceforge.net/Docs/PyQt4/qtcore.html
http://pyqt.sourceforge.net/Docs/PyQt4/qt.html

From phil_lor at bigpond.com  Mon Apr  1 11:59:23 2013
From: phil_lor at bigpond.com (Phil)
Date: Mon, 01 Apr 2013 19:59:23 +1000
Subject: [Tutor] pyqt4 set horizontal header item - solved
In-Reply-To: <CACL+1attYSUJ-1tO-ax=1S8gkp_S0URiAvunc3xEXq=cfn22Yw@mail.gmail.com>
References: <5157BBC6.20408@bigpond.com> <5157E60C.9000601@bigpond.com>
	<kj8rqp$9h5$1@ger.gmane.org>
	<CACL+1au3Go+OS3Reczzdw96sCM72Ywp2mwa9N-VXJ-Q9f-=FTQ@mail.gmail.com>
	<5158D10C.8080706@bigpond.com>
	<CACL+1attYSUJ-1tO-ax=1S8gkp_S0URiAvunc3xEXq=cfn22Yw@mail.gmail.com>
Message-ID: <51595A7B.6010702@bigpond.com>

On 01/04/13 19:47, eryksun wrote:
> On Sun, Mar 31, 2013 at 8:13 PM, Phil <phil_lor at bigpond.com> wrote:
>>
>> I have the answer (provided by a member of another list) and I was correct,
>> it was something basic.
>>
>> from PyQt4 import QtGui
>> QtGui.QTable etc
>
> Sorry, I assumed you were familiar with the package layout.
>
> http://pyqt.sourceforge.net/Docs/PyQt4/qtablewidgetitem.html
>
> Notice the subtitle that says "[QtGui module]".
>
> http://pyqt.sourceforge.net/Docs/PyQt4/classes.html
> http://pyqt.sourceforge.net/Docs/PyQt4/qtgui.html
> http://pyqt.sourceforge.net/Docs/PyQt4/qtcore.html
> http://pyqt.sourceforge.net/Docs/PyQt4/qt.html

Thanks for the links Eryksun, it's all now starting to make sense.

-- 
Regards,
Phil

From fomcl at yahoo.com  Mon Apr  1 22:04:21 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Mon, 1 Apr 2013 13:04:21 -0700 (PDT)
Subject: [Tutor] tadaahh! But how to identify zLinux?
Message-ID: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com>

tadaah, I uploaded my first package some time ago: http://pypi.python.org/pypi/savReaderWriter
Let me use this opportunity to say THANKS to all of you for all your advise!

I'm still stuck with a question though. The program is supposed to work with zLinux (IBM system Z). But how do I know that this system is used? Here's my attempt:

# https://pic.dhe.ibm.com/infocenter/tivihelp/v10r1/index.jsp?topic=%2Fcom.ibm.tsam.doc_7.1%2Fc_prep_ms_for_lx_sysz.html
import sys, platform
if sys.platform.startswith("lin"):
?? #isSuSe = platform.linux_distribution() == "SuSe"
?? sysname, nodename, release, version, machine = os.uname()
?? isSLES = "suse linux enterprise server" in version.lower()
?? isRelease2dot6 = release.startswith("2.6")
?? isSystemZ = machine.startswith("s390")? # ????
?? isZLinux = isSLES and isRelease2dot6 and isSystemZ
?? if isZLinux:
????? pass

Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?

?~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?

From eryksun at gmail.com  Mon Apr  1 22:43:56 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 1 Apr 2013 16:43:56 -0400
Subject: [Tutor] tadaahh! But how to identify zLinux?
In-Reply-To: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com>
References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com>
Message-ID: <CACL+1avnX8HL+bYv_38y6OqGHEPxa6j1x8YtduqrEdu8NF8wXg@mail.gmail.com>

On Mon, Apr 1, 2013 at 4:04 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
> I'm still stuck with a question though. The program is supposed to work
> with zLinux (IBM system Z). But how do I know that this system is used?

Have a look at the platform module for info on the Python
version/implementation, machine, and OS (e.g. linux_distribution):

http://docs.python.org/2.6/library/platform

From alan.gauld at btinternet.com  Tue Apr  2 00:00:07 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 01 Apr 2013 23:00:07 +0100
Subject: [Tutor] tadaahh! But how to identify zLinux?
In-Reply-To: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com>
References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com>
Message-ID: <kjd013$rgh$1@ger.gmane.org>

On 01/04/13 21:04, Albert-Jan Roskam wrote:

> program is supposed to work with zLinux (IBM system Z). But how do I
 > know that this system is used?

I have no idea what the answer is but I'm curious why you would care?
Are you expecting that your code will be run on an IBM mainframe?

I'd have thought that in most cases those boxes would only be running 
Python  in situations where the admins have carefully controlled the 
code that's loaded - and by implication taken care of whatever you are 
trying to do - or, they would be running virtual machines that look like 
non-mainframes?

Now, I have no experience of either zLinux or of using Python on a 
mainframe so I don't know if my guesses are accurate, but I am curious 
why you are concerned? Is it a known issue or are you just being super 
careful?

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


From steve at pearwood.info  Tue Apr  2 00:42:54 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 02 Apr 2013 09:42:54 +1100
Subject: [Tutor] tadaahh! But how to identify zLinux?
In-Reply-To: <kjd013$rgh$1@ger.gmane.org>
References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com>
	<kjd013$rgh$1@ger.gmane.org>
Message-ID: <515A0D6E.5080609@pearwood.info>

On 02/04/13 09:00, Alan Gauld wrote:
> On 01/04/13 21:04, Albert-Jan Roskam wrote:
>
>> program is supposed to work with zLinux (IBM system Z). But how do I
>> know that this system is used?
>
> I have no idea what the answer is but I'm curious why you would care?
> Are you expecting that your code will be run on an IBM mainframe?

Perhaps he is :-)

Albert-Jan asks because his package is an interface to an external binary
library, and the location of that library differs according to the platform:

https://bitbucket.org/fomcl/savreaderwriter/src/09b9c82406e82d43223d6610ba9cbfbf234b16d4/savReaderWriter/generic.py?at=master



By the way, I don't know that changing directory is a good idea, if you can
avoid it at all. I for one would be *extremely* annoyed if, after calling
what otherwise seems like an innocent library routine, opening files suddenly
started failing (or worse, the wrong file was opened!) because the current
directory was different. Even though you do restore the current directory
when you are done, that makes your routines unsafe for threads.



-- 
Steven

From kendy at kendy.org  Tue Apr  2 02:31:10 2013
From: kendy at kendy.org (kendy at kendy.org)
Date: Mon, 01 Apr 2013 17:31:10 PDT
Subject: [Tutor] argparse iterable
Message-ID: <52285.1364862670@speakeasy.net>

Dear Tutor

I want to compare command line options, to options in a dictionary from a YAML
file. The command line will over-ride the options in my file. (The YAML file, and
its dictionary are not shown. That part works.)

My distilled code:

-------------------------------------------------------------------------
$ cat h.py
#!/usr/bin/python

import argparse
parser = argparse.ArgumentParser(description='Short sample app')

def GetArgs(parser):
    parser.add_argument('-a', action="store_true", default=False)
    parser.add_argument('-b', action="store", dest="b")
    parser.add_argument('-c', action="store", dest="c", type=int)
    return parser

GetArgs(parser)

print(parser.parse_args())
print("But this doesn't iter through a b and c:")
for k,v in parser.parse_args():
    print('This arg is %s %s' % k, k[str(v)])
$ 
-------------------------------------------------------------------------

My error:
$ h.py -a -b hi -c 42
Namespace(a=True, b='hi', c=42)
But this doesn't iter through a b and c:
Traceback (most recent call last):
  File "./h.py", line 16, in <module>
    for k,v in parser.parse_args():
TypeError: 'Namespace' object is not iterable
$ 

How can I get parser to be iterable?

After I get it to iter, I suppose that I'll be bitten by the boolean and integer
type conversions. I'm not sure how to handle that either. Will 'str()' save me?

Thanks a million (again!),
Ken


From jsf80238 at gmail.com  Tue Apr  2 03:24:04 2013
From: jsf80238 at gmail.com (Jason Friedman)
Date: Mon, 1 Apr 2013 19:24:04 -0600
Subject: [Tutor] argparse iterable
In-Reply-To: <52285.1364862670@speakeasy.net>
References: <52285.1364862670@speakeasy.net>
Message-ID: <CANy1k1jPuhRBGsMwfZJ=KHV2c3Xbn7xaFS4FV-SJGv0E0FOupg@mail.gmail.com>

#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(description='Short sample app')
parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)
parser.parse_args()
for k,v in parser.parse_args().__dict__.items():
    print('This arg is %s %s' % (k, v))



On Mon, Apr 1, 2013 at 6:31 PM, <kendy at kendy.org> wrote:

> Dear Tutor
>
> I want to compare command line options, to options in a dictionary from a
> YAML
> file. The command line will over-ride the options in my file. (The YAML
> file, and
> its dictionary are not shown. That part works.)
>
> My distilled code:
>
> -------------------------------------------------------------------------
> $ cat h.py
> #!/usr/bin/python
>
> import argparse
> parser = argparse.ArgumentParser(description='Short sample app')
>
> def GetArgs(parser):
>     parser.add_argument('-a', action="store_true", default=False)
>     parser.add_argument('-b', action="store", dest="b")
>     parser.add_argument('-c', action="store", dest="c", type=int)
>     return parser
>
> GetArgs(parser)
>
> print(parser.parse_args())
> print("But this doesn't iter through a b and c:")
> for k,v in parser.parse_args():
>     print('This arg is %s %s' % k, k[str(v)])
> $
> -------------------------------------------------------------------------
>
> My error:
> $ h.py -a -b hi -c 42
> Namespace(a=True, b='hi', c=42)
> But this doesn't iter through a b and c:
> Traceback (most recent call last):
>   File "./h.py", line 16, in <module>
>     for k,v in parser.parse_args():
> TypeError: 'Namespace' object is not iterable
> $
>
> How can I get parser to be iterable?
>
> After I get it to iter, I suppose that I'll be bitten by the boolean and
> integer
> type conversions. I'm not sure how to handle that either. Will 'str()'
> save me?
>
> Thanks a million (again!),
> Ken
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130401/22478f4d/attachment-0001.html>

From breamoreboy at yahoo.co.uk  Tue Apr  2 03:31:24 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 02 Apr 2013 02:31:24 +0100
Subject: [Tutor] argparse iterable
In-Reply-To: <52285.1364862670@speakeasy.net>
References: <52285.1364862670@speakeasy.net>
Message-ID: <kjdcat$73b$1@ger.gmane.org>

On 02/04/2013 01:31, kendy at kendy.org wrote:
> Dear Tutor
>
> I want to compare command line options, to options in a dictionary from a YAML
> file. The command line will over-ride the options in my file. (The YAML file, and
> its dictionary are not shown. That part works.)
>
> My distilled code:
>
> -------------------------------------------------------------------------
> $ cat h.py
> #!/usr/bin/python
>
> import argparse
> parser = argparse.ArgumentParser(description='Short sample app')
>
> def GetArgs(parser):
>      parser.add_argument('-a', action="store_true", default=False)
>      parser.add_argument('-b', action="store", dest="b")
>      parser.add_argument('-c', action="store", dest="c", type=int)
>      return parser
>
> GetArgs(parser)
>
> print(parser.parse_args())
> print("But this doesn't iter through a b and c:")
> for k,v in parser.parse_args():
>      print('This arg is %s %s' % k, k[str(v)])

for a in vars(parser.parse_args()):
     print('This arg is %s' % a)

http://docs.python.org/3/library/argparse.html#the-namespace-object

Please don't ask me for an explanation as it took me long enough to work 
this out from the docs :)

> $
> -------------------------------------------------------------------------
>
> My error:
> $ h.py -a -b hi -c 42
> Namespace(a=True, b='hi', c=42)
> But this doesn't iter through a b and c:
> Traceback (most recent call last):
>    File "./h.py", line 16, in <module>
>      for k,v in parser.parse_args():
> TypeError: 'Namespace' object is not iterable
> $
>
> How can I get parser to be iterable?
>
> After I get it to iter, I suppose that I'll be bitten by the boolean and integer
> type conversions. I'm not sure how to handle that either. Will 'str()' save me?
>
> Thanks a million (again!),
> Ken
>
>


-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From davea at davea.name  Tue Apr  2 03:37:16 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 01 Apr 2013 21:37:16 -0400
Subject: [Tutor] argparse iterable
In-Reply-To: <kjdcat$73b$1@ger.gmane.org>
References: <52285.1364862670@speakeasy.net> <kjdcat$73b$1@ger.gmane.org>
Message-ID: <515A364C.4040604@davea.name>

On 04/01/2013 09:31 PM, Mark Lawrence wrote:
> On 02/04/2013 01:31, kendy at kendy.org wrote:
>> Dear Tutor
>>
>> I want to compare command line options, to options in a dictionary
>> from a YAML
>> file. The command line will over-ride the options in my file. (The
>> YAML file, and
>> its dictionary are not shown. That part works.)
>>
>> My distilled code:
>>
>> -------------------------------------------------------------------------
>> $ cat h.py
>> #!/usr/bin/python
>>
>> import argparse
>> parser = argparse.ArgumentParser(description='Short sample app')
>>
>> def GetArgs(parser):
>>      parser.add_argument('-a', action="store_true", default=False)
>>      parser.add_argument('-b', action="store", dest="b")
>>      parser.add_argument('-c', action="store", dest="c", type=int)
>>      return parser
>>
>> GetArgs(parser)
>>
>> print(parser.parse_args())
>> print("But this doesn't iter through a b and c:")
>> for k,v in parser.parse_args():
>>      print('This arg is %s %s' % k, k[str(v)])
>
> for a in vars(parser.parse_args()):
>      print('This arg is %s' % a)
>
> http://docs.python.org/3/library/argparse.html#the-namespace-object
>
> Please don't ask me for an explanation as it took me long enough to work
> this out from the docs :)
>

http://docs.python.org/2/library/argparse.html

     see section 15.4.4.6 for a very brief explanation of vars()


>> $
>> -------------------------------------------------------------------------
>>
>> My error:
>> $ h.py -a -b hi -c 42
>> Namespace(a=True, b='hi', c=42)
>> But this doesn't iter through a b and c:
>> Traceback (most recent call last):
>>    File "./h.py", line 16, in <module>
>>      for k,v in parser.parse_args():
>> TypeError: 'Namespace' object is not iterable
>> $
>>
>> How can I get parser to be iterable?
>>
>> After I get it to iter, I suppose that I'll be bitten by the boolean
>> and integer
>> type conversions. I'm not sure how to handle that either. Will 'str()'
>> save me?
>>
>> Thanks a million (again!),
>> Ken
>>
>>
>
>


-- 
DaveA

From dfjennings at gmail.com  Tue Apr  2 03:56:16 2013
From: dfjennings at gmail.com (Don Jennings)
Date: Mon, 1 Apr 2013 21:56:16 -0400
Subject: [Tutor] argparse iterable
In-Reply-To: <52285.1364862670@speakeasy.net>
References: <52285.1364862670@speakeasy.net>
Message-ID: <EBCAB3F0-7667-467F-A693-057E9D1972C6@gmail.com>


On Apr 1, 2013, at 8:31 PM, <kendy at kendy.org> <kendy at kendy.org> wrote:

> <snip>
> 
> print("But this doesn't iter through a b and c:")
> for k,v in parser.parse_args():
>    print('This arg is %s %s' % k, k[str(v)])
> $ 
> -------------------------------------------------------------------------
> 
> My error:
> $ h.py -a -b hi -c 42
> Namespace(a=True, b='hi', c=42)
> But this doesn't iter through a b and c:
> Traceback (most recent call last):
>  File "./h.py", line 16, in <module>
>    for k,v in parser.parse_args():
> TypeError: 'Namespace' object is not iterable
> $ 
> 
> How can I get parser to be iterable?

Jason, Mark and Dave have addressed this part of your question already.

> 
> After I get it to iter, I suppose that I'll be bitten by the boolean and integer
> type conversions. I'm not sure how to handle that either. Will 'str()' save me?

What do you mean here? You're thinking that you have to convert them to strings before passing them to the print function? Actually, the string formatting operator, the percent sign, combined with the 's' will convert for you, using the str() method. So, the code above is redundant. Just use:

print('This arg is %s %s' % k, v)

Take care,
Don


From kendy at kendy.org  Tue Apr  2 04:28:53 2013
From: kendy at kendy.org (kendy at kendy.org)
Date: Mon, 01 Apr 2013 19:28:53 PDT
Subject: [Tutor] argparse iterable
Message-ID: <35358.1364869733@speakeasy.net>

You guys are awesome! You make it look easy and I learn every time.

Thank you
Ken

From breamoreboy at yahoo.co.uk  Tue Apr  2 04:34:26 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 02 Apr 2013 03:34:26 +0100
Subject: [Tutor] argparse iterable
In-Reply-To: <515A364C.4040604@davea.name>
References: <52285.1364862670@speakeasy.net> <kjdcat$73b$1@ger.gmane.org>
	<515A364C.4040604@davea.name>
Message-ID: <kjdfuj$7lg$1@ger.gmane.org>

On 02/04/2013 02:37, Dave Angel wrote:
> On 04/01/2013 09:31 PM, Mark Lawrence wrote:
>>
>> for a in vars(parser.parse_args()):
>>      print('This arg is %s' % a)
>>
>> http://docs.python.org/3/library/argparse.html#the-namespace-object
>>
>> Please don't ask me for an explanation as it took me long enough to work
>> this out from the docs :)
>>
>
> http://docs.python.org/2/library/argparse.html
>
>      see section 15.4.4.6 for a very brief explanation of vars()
>
>

Section 15.4.4.6. The Namespace object, but I can't for the life of me 
remember what my link referred to :)

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From breamoreboy at yahoo.co.uk  Tue Apr  2 04:37:04 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 02 Apr 2013 03:37:04 +0100
Subject: [Tutor] argparse iterable
In-Reply-To: <35358.1364869733@speakeasy.net>
References: <35358.1364869733@speakeasy.net>
Message-ID: <kjdg2p$7lg$2@ger.gmane.org>

On 02/04/2013 03:28, kendy at kendy.org wrote:
> You guys are awesome! You make it look easy and I learn every time.
>
> Thank you
> Ken

Think yourself lucky, I'm currently on the wagon or it'd cost you a 
couple of pints :)

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From eryksun at gmail.com  Tue Apr  2 04:57:16 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 1 Apr 2013 22:57:16 -0400
Subject: [Tutor] tadaahh! But how to identify zLinux?
In-Reply-To: <515A0D6E.5080609@pearwood.info>
References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com>
	<kjd013$rgh$1@ger.gmane.org> <515A0D6E.5080609@pearwood.info>
Message-ID: <CACL+1avZGgJn5OndB3MbXZ4GnvGjkxymRY_kRAdnBQYBZhpofA@mail.gmail.com>

On Mon, Apr 1, 2013 at 6:42 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> By the way, I don't know that changing directory is a good idea, if you can
> avoid it at all.

As far as loading linked libraries goes, changing the current
directory works on Windows, and I think OS X, but it doesn't work on
Linux. On Windows you can also add the directory to the system PATH at
run time.

I see 3 deb files in spssio/lin32. It doesn't seem like your plan is
to install these since you don't have them for lin64 as well. Is this
savReaderWriter supposed to be a self-contained system for
reading/writing IBM SPSS files, or dependent on an existing
installation of SPSS? (Not being a user of SPSS, I have no idea how
foolish that question may or may not sound. Oh well.)

Anyway, I downloaded and extracted the deb files to a temp directory
on a 32-bit Debian system. In addition to the libs that you've already
extracted, ldd determined that I also needed the following libs:

libimf.so          [intel-icc8-libs_8.0-1_i386.deb]
libcxaguard.so.5   [intel-icc8-libs_8.0-1_i386.deb
libstdc++.so.5.0.7 [libstdc++5_3.3.6-20_i386.deb]

and links for the ELF soname fields:

libstdc++.so.5    ->  libstdc++.so.5.0.7
libicudata.so.32  ->  libicudata.so.32.0
libicui18n.so.32  ->  libicui18n.so.32.0
libicuuc.so.32    ->  libicuuc.so.32.0

After setting up the above, I patched a runpath of $ORIGIN into
libspssdio.so.1. This instructs the loader to look for dependencies in
the same directory.

    $ patchelf --set-rpath '$ORIGIN' libspssdio.so.1

Now I can load the library with ctypes:

    >>> from ctypes import *
    >>> spssio = CDLL('spssio/lin32/libspssdio.so.1')
    >>> spssio.spssOpenRead
    <_FuncPtr object at 0xb753b094>

From davea at davea.name  Tue Apr  2 11:48:17 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 02 Apr 2013 05:48:17 -0400
Subject: [Tutor] argparse iterable
In-Reply-To: <kjdfuj$7lg$1@ger.gmane.org>
References: <52285.1364862670@speakeasy.net> <kjdcat$73b$1@ger.gmane.org>
	<515A364C.4040604@davea.name> <kjdfuj$7lg$1@ger.gmane.org>
Message-ID: <515AA961.1070909@davea.name>

On 04/01/2013 10:34 PM, Mark Lawrence wrote:
> On 02/04/2013 02:37, Dave Angel wrote:
>> On 04/01/2013 09:31 PM, Mark Lawrence wrote:
>>>
>>> for a in vars(parser.parse_args()):
>>>      print('This arg is %s' % a)
>>>
>>> http://docs.python.org/3/library/argparse.html#the-namespace-object
>>>
>>> Please don't ask me for an explanation as it took me long enough to work
>>> this out from the docs :)
>>>
>>
>> http://docs.python.org/2/library/argparse.html
>>
>>      see section 15.4.4.6 for a very brief explanation of vars()
>>
>>
>
> Section 15.4.4.6. The Namespace object, but I can't for the life of me
> remember what my link referred to :)
>

Whoops, sorry.  I didn't notice your link was equivalent to (better 
than) mine.  I had worked it out before your message showed up, then 
abandoned all of my message except for the link.

BTW, can you tell me how you get the #the-namespace-object part of your 
link?  Is there some technique (without actually looking in the source 
code for the page) for finding the nearest id= ?  I've now figured out 
how to do it for pages like this one with a TOC, but is there a more 
general way?

For others like me:
If there's a TOC (table of contents) for a page, you can right-click on 
the link to the particular section of the page, and COPY it to the 
clipboard.  It'll then have the form like:
   http://docs.python.org/3/library/argparse.html#the-namespace-object

where the last field specifies the particular section of the page desired.



-- 
DaveA

From davea at davea.name  Tue Apr  2 11:50:43 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 02 Apr 2013 05:50:43 -0400
Subject: [Tutor] argparse iterable
In-Reply-To: <35358.1364869733@speakeasy.net>
References: <35358.1364869733@speakeasy.net>
Message-ID: <515AA9F3.2010208@davea.name>

On 04/01/2013 10:28 PM, kendy at kendy.org wrote:
> You guys are awesome! You make it look easy and I learn every time.
>

Once you've got the two dicts, take a look into the update method.  It 
may make any loops unnecessary, except for debugging.


-- 
DaveA

From fomcl at yahoo.com  Tue Apr  2 12:44:22 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Tue, 2 Apr 2013 03:44:22 -0700 (PDT)
Subject: [Tutor] tadaahh! But how to identify zLinux?
In-Reply-To: <515A0D6E.5080609@pearwood.info>
References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com>
	<kjd013$rgh$1@ger.gmane.org> <515A0D6E.5080609@pearwood.info>
Message-ID: <1364899462.29381.YahooMailNeo@web163802.mail.gq1.yahoo.com>

> Subject: Re: [Tutor] tadaahh! But how to identify zLinux?
> 
> On 02/04/13 09:00, Alan Gauld wrote:
>> On 01/04/13 21:04, Albert-Jan Roskam wrote:
>> 
>>> program is supposed to work with zLinux (IBM system Z). But how do I
>>> know that this system is used?
>> 
>> I have no idea what the answer is but I'm curious why you would care?
>> Are you expecting that your code will be run on an IBM mainframe?
> 
> Perhaps he is :-)

Umm, well it'd be cool. And it's also kind of to satisfy my intellectual hunger/curiosity. I had never heard of zLinux before, but now I've read a thing or two about it.
?
> Albert-Jan asks because his package is an interface to an external binary
> library, and the location of that library differs according to the platform:

?
Yes, exactly right. It's cool if it just works for all supported platforms.
?
>https://bitbucket.org/fomcl/savreaderwriter/src/09b9c82406e82d43223d6610ba9cbfbf234b16d4/savReaderWriter/generic.py?at=master
> 
> By the way, I don't know that changing directory is a good idea, if you can
> avoid it at all. I for one would be *extremely* annoyed if, after calling
> what otherwise seems like an innocent library routine, opening files suddenly
> started failing (or worse, the wrong file was opened!) because the current
> directory was different. Even though you do restore the current directory
> when you are done, that makes your routines unsafe for threads.

?
That loadLibrary method has been kind of a challenge. The chdir may very well be only needed on Windows. I'd have to test this (in sofar as I've access to any of these platforms). I like the fact that, under Windows, things work out of the box, without needing to modify PATH.

From fomcl at yahoo.com  Tue Apr  2 13:19:06 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Tue, 2 Apr 2013 04:19:06 -0700 (PDT)
Subject: [Tutor] tadaahh! But how to identify zLinux?
In-Reply-To: <CACL+1avZGgJn5OndB3MbXZ4GnvGjkxymRY_kRAdnBQYBZhpofA@mail.gmail.com>
References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com>
	<kjd013$rgh$1@ger.gmane.org> <515A0D6E.5080609@pearwood.info>
	<CACL+1avZGgJn5OndB3MbXZ4GnvGjkxymRY_kRAdnBQYBZhpofA@mail.gmail.com>
Message-ID: <1364901546.38378.YahooMailNeo@web163804.mail.gq1.yahoo.com>

> From: eryksun <eryksun at gmail.com>
> To: Albert-Jan Roskam <fomcl at yahoo.com>
> Cc: tutor at python.org
> Sent: Tuesday, April 2, 2013 4:57 AM
> Subject: Re: [Tutor] tadaahh! But how to identify zLinux?
> 
> On Mon, Apr 1, 2013 at 6:42 PM, Steven D'Aprano <steve at pearwood.info> 
> wrote:
>> By the way, I don't know that changing directory is a good idea, if you 
> can
>> avoid it at all.
> 
> As far as loading linked libraries goes, changing the current
> directory works on Windows, and I think OS X, but it doesn't work on
> Linux. On Windows you can also add the directory to the system PATH at
> run time.

Ok, I'll improve that method and ditch the os.chdir calls.

> I see 3 deb files in spssio/lin32. It doesn't seem like your plan is
> to install these since you don't have them for lin64 as well. Is this
> savReaderWriter supposed to be a self-contained system for
> reading/writing IBM SPSS files, or dependent on an existing
> installation of SPSS? (Not being a user of SPSS, I have no idea how
> foolish that question may or may not sound. Oh well.)

Yes, savReaderWriter is supposed to be a self-contained system, without the need for an expensive license.
I put the?3 .deb files there as a convenience. I run Linux on a 32-bit system, so I thought I 'd just also include those files.
In the help I mentioned these specific dependencies: http://pythonhosted.org/savReaderWriter/

> Anyway, I downloaded and extracted the deb files to a temp directory
> on a 32-bit Debian system. In addition to the libs that you've already
> extracted, ldd determined that I also needed the following libs:
> 
> libimf.so? ? ? ? ? [intel-icc8-libs_8.0-1_i386.deb]
> libcxaguard.so.5? [intel-icc8-libs_8.0-1_i386.deb
> libstdc++.so.5.0.7 [libstdc++5_3.3.6-20_i386.deb]
> 
> and links for the ELF soname fields:
> 
> libstdc++.so.5? ? ->? libstdc++.so.5.0.7
> libicudata.so.32? ->? libicudata.so.32.0
> libicui18n.so.32? ->? libicui18n.so.32.0
> libicuuc.so.32? ? ->? libicuuc.so.32.0

How exactly did you do this?

> After setting up the above, I patched a runpath of $ORIGIN into
> libspssdio.so.1. This instructs the loader to look for dependencies in
> the same directory.
> 
> ? ? $ patchelf --set-rpath '$ORIGIN' libspssdio.so.1
> 
> Now I can load the library with ctypes:
> 
> ? ? >>> from ctypes import *
> ? ? >>> spssio = CDLL('spssio/lin32/libspssdio.so.1')
> ? ? >>> spssio.spssOpenRead
> ? ? <_FuncPtr object at 0xb753b094>

Awesome. I knew about patchelf but I didn't feel confident enough to use this (I believe I fainted when I did 'man ld' ;-). Moreover, as we discussed before, I wasn't sure whether patching the ELF header would somehow be in violation of the IBM license agreement. I guess that including as shell script with the savReaderWriter package with the patchelf code would be okay.

I'll look into this in more detail when I'm on a Linux box again. I might be back with more questions. ;-) 

May I ask if you run Linux 64 bit? I haven't been able to try the program on Linux 64 (only win32, win64, lin32, mac and, shortly, also aix64). I would be really pleased to know if this also works on Linux 64 (zLinux will?remain a surprise, for now ;-). This code should run without errors:

import tempfile, os
from savReaderWriter import *

?
savFileName = os.path.join(tempfile.gettempdir(), "someFile.sav")
records = [['Test1', 1, 1], ['Test2', 2, 1]] 
varNames = ['var1', 'v2', 'v3'] 
varTypes = {'var1': 5, 'v2': 0, 'v3': 0} 
with SavWriter(savFileName, varNames, varTypes) as writer: 
??? for record in records: 
??????? writer.writerow(record) 

with SavReader(savFileName, returnHeader=True) as reader: 
???? header = reader.next()
???? print header
???? for record in reader:
?????????print record?

Tutors, thanks again!
?
Albert-Jan

From eryksun at gmail.com  Tue Apr  2 13:23:06 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 2 Apr 2013 07:23:06 -0400
Subject: [Tutor] argparse iterable
In-Reply-To: <515AA961.1070909@davea.name>
References: <52285.1364862670@speakeasy.net> <kjdcat$73b$1@ger.gmane.org>
	<515A364C.4040604@davea.name> <kjdfuj$7lg$1@ger.gmane.org>
	<515AA961.1070909@davea.name>
Message-ID: <CACL+1atxdsfZrtjtL4EXSvseVZ2NkNPQLT9XOs3cDkm0YyZKMQ@mail.gmail.com>

On Tue, Apr 2, 2013 at 5:48 AM, Dave Angel <davea at davea.name> wrote:
>
> BTW, can you tell me how you get the #the-namespace-object part of your
> link?  Is there some technique (without actually looking in the source code
> for the page) for finding the nearest id= ?

    <h3>
    16.4.4.6. The Namespace object
      <a class="headerlink" href="#the-namespace-object"
         title="Permalink to this headline">
      ?
      </a>
    </h3>

The paragraph symbol (?) appears when you hover over the heading.
Click it to get the anchor. Here's the bit of CSS that makes the
headerlink visible when you hover:

    a.headerlink {
        visibility: hidden;
    }
    h1:hover > a.headerlink,
    h2:hover > a.headerlink,
    h3:hover > a.headerlink,
    h4:hover > a.headerlink,
    h5:hover > a.headerlink,
    h6:hover > a.headerlink,
    dt:hover > a.headerlink {
        visibility: visible;
    }

http://docs.python.org/3/_static/basic.css

From breamoreboy at yahoo.co.uk  Tue Apr  2 15:49:00 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 02 Apr 2013 14:49:00 +0100
Subject: [Tutor] argparse iterable
In-Reply-To: <515AA961.1070909@davea.name>
References: <52285.1364862670@speakeasy.net> <kjdcat$73b$1@ger.gmane.org>
	<515A364C.4040604@davea.name> <kjdfuj$7lg$1@ger.gmane.org>
	<515AA961.1070909@davea.name>
Message-ID: <kjenin$6t1$1@ger.gmane.org>

On 02/04/2013 10:48, Dave Angel wrote:
>
> BTW, can you tell me how you get the #the-namespace-object part of your
> link?  Is there some technique (without actually looking in the source
> code for the page) for finding the nearest id= ?  I've now figured out
> how to do it for pages like this one with a TOC, but is there a more
> general way?

I'm not aware of one, which obviously doesn't mean there's no such beast.

>
> For others like me:
> If there's a TOC (table of contents) for a page, you can right-click on
> the link to the particular section of the page, and COPY it to the
> clipboard.  It'll then have the form like:
>    http://docs.python.org/3/library/argparse.html#the-namespace-object
>
> where the last field specifies the particular section of the page desired.
>

I also go for the cut and paste approach.  Maybe we need Bicycle Repair 
Man to do some searching for us? :)

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From d_mitchell89 at hotmail.com  Tue Apr  2 18:49:32 2013
From: d_mitchell89 at hotmail.com (David Mitchell)
Date: Tue, 2 Apr 2013 12:49:32 -0400
Subject: [Tutor] Python help!!
Message-ID: <BAY174-W45401FBBB0CD4F0A953E53EBDF0@phx.gbl>

Hi!
How do I go through a text file, finding specific words/numbers/phrases and edit them to say different things? I do not want to edit the text file, I would rather open and read from the text file and write to a new file. 
I do NOT want to know how to replace a specific word with another every time it appears. There are some "OFF" 's that i would like to change to "ON" 's and some that I would like to change to "OPEN" for example. 
I am doing all this in Linux Fedora with gedit. It is a project assigned to me from my boss and I'm just a co-op student so I could really use the help. 
Any help would be greatly appreciated!!
Thanks,
David  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130402/a99b76df/attachment-0001.html>

From taserian at gmail.com  Tue Apr  2 19:13:13 2013
From: taserian at gmail.com (taserian)
Date: Tue, 2 Apr 2013 13:13:13 -0400
Subject: [Tutor] Python help!!
In-Reply-To: <BAY174-W45401FBBB0CD4F0A953E53EBDF0@phx.gbl>
References: <BAY174-W45401FBBB0CD4F0A953E53EBDF0@phx.gbl>
Message-ID: <CAOgHRJOhBH_TehBXNovbPPZ3OC_60NQkCURNNm_TLknc=se=Xw@mail.gmail.com>

On Tue, Apr 2, 2013 at 12:49 PM, David Mitchell <d_mitchell89 at hotmail.com>wrote:

> Hi!
>
> How do I go through a text file, finding specific words/numbers/phrases
> and edit them to say different things? I do not want to edit the text file,
> I would rather open and read from the text file and write to a new file.
>
> I do NOT want to know how to replace a specific word with another every
> time it appears. There are some "OFF" 's that i would like to change to
> "ON" 's and some that I would like to change to "OPEN" for example.
>

How would you know which ones to change to "ON" and which ones to change to
"OPEN"? Additionally, how would you describe those conditions in Python?


Antonio Rodriguez
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130402/462ee801/attachment.html>

From bodsda at googlemail.com  Tue Apr  2 19:15:55 2013
From: bodsda at googlemail.com (Bod Soutar)
Date: Tue, 2 Apr 2013 18:15:55 +0100
Subject: [Tutor] Python help!!
In-Reply-To: <BAY174-W45401FBBB0CD4F0A953E53EBDF0@phx.gbl>
References: <BAY174-W45401FBBB0CD4F0A953E53EBDF0@phx.gbl>
Message-ID: <CAG6Bxkcq18eCtUP2B+R02gMuHQ4v1LMUeGfWNNcEhNtM+vfd-g@mail.gmail.com>

On 2 April 2013 17:49, David Mitchell <d_mitchell89 at hotmail.com> wrote:
> Hi!
>
> How do I go through a text file, finding specific words/numbers/phrases and
> edit them to say different things? I do not want to edit the text file, I
> would rather open and read from the text file and write to a new file.
>
> I do NOT want to know how to replace a specific word with another every time
> it appears. There are some "OFF" 's that i would like to change to "ON" 's
> and some that I would like to change to "OPEN" for example.
>
> I am doing all this in Linux Fedora with gedit. It is a project assigned to
> me from my boss and I'm just a co-op student so I could really use the help.
>
> Any help would be greatly appreciated!!
>
> Thanks,
>
> David

Can you give us some idea of your skill level, and perhaps some code
that you've already tried?
Your general approach will be something like

open read_file
open write_file
read read_file into a list
close read_file
iterate over the list
    if you find a line you want to change
        make the change and write to write_file
    else
        write to write_file

close write_file

HTH,
Bodsda

From dipo.elegbede at dipoelegbede.com  Tue Apr  2 19:16:42 2013
From: dipo.elegbede at dipoelegbede.com (Elegbede Muhammed Oladipupo)
Date: Tue, 2 Apr 2013 17:16:42 +0000
Subject: [Tutor] Python help!!
In-Reply-To: <BAY174-W45401FBBB0CD4F0A953E53EBDF0@phx.gbl>
References: <BAY174-W45401FBBB0CD4F0A953E53EBDF0@phx.gbl>
Message-ID: <751666533-1364923002-cardhu_decombobulator_blackberry.rim.net-1888420087-@b12.c13.bise7.blackberry>


What exactly do you know how to do?

Can you read files?
Can you replace words?

This way, I can know how to help. 
What is hard for me to help with is the fact that you are planning to replace the same word with two different words depending on location e.g when you said you want to change off to either on or open. 

Let's see what you can do or have done, then help should be on the way. 

Regards. Regards. </div>
Sent from my BlackBerry?  PORSCHE? DESIGN wireless handheld from Glo Mobile.

-----Original Message-----
From: David Mitchell <d_mitchell89 at hotmail.com>
Sender: "Tutor" <tutor-bounces+dipo.elegbede=dipoelegbede.com at python.org>Date: Tue, 2 Apr 2013 12:49:32 
To: tutor at python.org<tutor at python.org>
Subject: [Tutor] Python help!!

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

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130402/7cf22f6f/attachment.html>

From alan.gauld at btinternet.com  Tue Apr  2 19:48:44 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 02 Apr 2013 18:48:44 +0100
Subject: [Tutor] Python help!!
In-Reply-To: <BAY174-W45401FBBB0CD4F0A953E53EBDF0@phx.gbl>
References: <BAY174-W45401FBBB0CD4F0A953E53EBDF0@phx.gbl>
Message-ID: <kjf5lo$brs$1@ger.gmane.org>

On 02/04/13 17:49, David Mitchell wrote:

> How do I go through a text file, finding specific words/numbers/phrases
> and edit them to say different things? I do not want to edit the text
> file, I would rather open and read from the text file and write to a new
> file.

OK That's easy, you just write the old file to the new file with the 
changes in place.

> I do NOT want to know how to replace a specific word with another every
> time it appears. There are some "OFF" 's that i would like to change to
> "ON" 's and some that I would like to change to "OPEN" for example.

OK so, instead of calling replace, you want to stop and ask the user for 
a replacement text? Is that the idea?

> I am doing all this in Linux Fedora with gedit.

I don't know gedit but both vim and emacs have interactive
replacement functions, maybe gedit has too. Both vi and
emacs can create macros and you can auto run macros when
you start the editor, so you could automate it all
using those tools.

But Python can work almost as easily (and probably the
finished article will be faster)

> Any help would be greatly appreciated!!

Why don't you tell us how you think it should work?
Its likely that all the bits you need are already
available to you with a little thought. Research
the string methods (and if you want to get (too) clever
the re module too).

(I'm assuming these files are short enough to read them
all into memory as a single string? If not we need to
get slightly smarter.)

Try a solution and tell us where you get stuck.
Even pseudo code if you aren't confident with
real Python.

If that's too hard at least try to produce a hypothetical
user session showing us what you expect the program
to look like in use.

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


From Ankesh.Pratap at cognizant.com  Tue Apr  2 20:19:34 2013
From: Ankesh.Pratap at cognizant.com (Ankesh.Pratap at cognizant.com)
Date: Tue, 2 Apr 2013 18:19:34 +0000
Subject: [Tutor] Need help on win32 application error
Message-ID: <F912AD61E07EBE4FA5E688BF2AD163FC010093EA@CTSINCHNSXMBU.cts.com>

Hi Team,
        I am facing folowing erro while executing python code:
            Win32 exception occurred releasing IUnknown at 0x03210eb8
Please let me know the resolution of the same.PFA the version details of python exe that I am using.


Thanks and Regards,
     Ankesh Pratap

Programmer Analyst
Mobile: 91-9884928733
This e-mail and any files transmitted with it are for the sole use of the intended recipient(s) and may contain confidential and privileged information. If you are not the intended recipient(s), please reply to the sender and destroy all copies of the original message. Any unauthorized review, use, disclosure, dissemination, forwarding, printing or copying of this email, and/or any action taken in reliance on the contents of this e-mail is strictly prohibited and may be unlawful.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: IdleVersion.JPG
Type: image/pjpeg
Size: 18776 bytes
Desc: IdleVersion.JPG
URL: <http://mail.python.org/pipermail/tutor/attachments/20130402/420e3491/attachment-0001.bin>

From bodsda at googlemail.com  Tue Apr  2 20:27:36 2013
From: bodsda at googlemail.com (Bod Soutar)
Date: Tue, 2 Apr 2013 19:27:36 +0100
Subject: [Tutor] Need help on win32 application error
In-Reply-To: <F912AD61E07EBE4FA5E688BF2AD163FC010093EA@CTSINCHNSXMBU.cts.com>
References: <F912AD61E07EBE4FA5E688BF2AD163FC010093EA@CTSINCHNSXMBU.cts.com>
Message-ID: <CAG6Bxke_CdsVSBQK_Quk+WtuTN6cWg7PGDvTtRXQotkbrqA6+g@mail.gmail.com>

On 2 April 2013 19:19,  <Ankesh.Pratap at cognizant.com> wrote:
> Hi Team,
>         I am facing folowing erro while executing python code:
>             Win32 exception occurred releasing IUnknown at 0x03210eb8
> Please let me know the resolution of the same.PFA the version details of python exe that I am using.
>
>
> Thanks and Regards,
>      Ankesh Pratap
>
> Programmer Analyst
> Mobile: 91-9884928733
> This e-mail and any files transmitted with it are for the sole use of the intended recipient(s) and may contain confidential and privileged information. If you are not the intended recipient(s), please reply to the sender and destroy all copies of the original message. Any unauthorized review, use, disclosure, dissemination, forwarding, printing or copying of this email, and/or any action taken in reliance on the contents of this e-mail is strictly prohibited and may be unlawful.
>
I'd say the Win32 module threw an exception when trying to release
something at the memory address 0x03210eb8......
But that's just a rough guess you understand.

Bodsda

From eryksun at gmail.com  Tue Apr  2 20:59:32 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 2 Apr 2013 14:59:32 -0400
Subject: [Tutor] tadaahh! But how to identify zLinux?
In-Reply-To: <1364901546.38378.YahooMailNeo@web163804.mail.gq1.yahoo.com>
References: <1364846661.14968.YahooMailNeo@web163803.mail.gq1.yahoo.com>
	<kjd013$rgh$1@ger.gmane.org> <515A0D6E.5080609@pearwood.info>
	<CACL+1avZGgJn5OndB3MbXZ4GnvGjkxymRY_kRAdnBQYBZhpofA@mail.gmail.com>
	<1364901546.38378.YahooMailNeo@web163804.mail.gq1.yahoo.com>
Message-ID: <CACL+1avJDTyO3j8Nhxmx-Gt+Tc8YPVObGh7+-EVFLvWiX0YeNg@mail.gmail.com>

On Tue, Apr 2, 2013 at 7:19 AM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>> On Windows you can also add the directory to the system PATH at
>> run time.
>
> Ok, I'll improve that method and ditch the os.chdir calls.

Win32 LoadLibrary searches system directories, the executable's
directory, the current directory, and finally PATH. It's simple to
update the PATH environment variable for the current process:

    os.environ['PATH'] = ';'.join([absolute_lib_path, os.environ['PATH']])

You can also call kernel32.SetDllDirectoryW(absolute_lib_path) to
insert a path to be searched immediately after the executable's
directory. Afterward call kernel32.SetDllDirectoryW(None) to restore
the normal safe search order.

>> Anyway, I downloaded and extracted the deb files
>> ....
>> and links for the ELF soname fields
>
> How exactly did you do this?

I extracted the debs:

    dpkg-deb -x <deb> <directory>

Then I copied the required .so files to the lin32 directory and
created the symbolic links with "ln".

> Moreover, as we discussed before, I wasn't sure whether patching
> the ELF header would somehow be in violation of the IBM license
> agreement. I guess that including as shell script with the
> savReaderWriter package with the patchelf code would be okay.

The Debian repo has ICU 4.8 (libicu48). It also has libstdc++5. I'm
sure the same applies to other Linux distros. That leaves only Intel's
C++ libraries to be installed: libimf.so, libirc.so, and
libcxaguard.so.5. I think Intel's license allows you to redistribute
these with an application. Anything less would be unreasonable. But...

Actually, the fact the lin32 and lin64 versions in your repo were
linked to different versions of ICU made me suspicious. I decided to
downloaded "IO_Module_for_SPSS_Statistics_21001.zip" (version 21) to
get the lin32 directory from the source. Turns out this version
doesn't depend on Intel's libs at all, and it's linked to the ICU 4.8
libs and libstdc++.so.6. It does add libzlib123spss.so, but that's
simple to preload.

In fact, if you'd rather not tinker with PATH on Windows, or install
libraries to the system, or patch the ELF runpath -- then you could
simply load the required libraries manually in the following sequence
(version 21):

    Linux                 Windows
    -------------------------------------
    libicudata.so.48.1    icudt48.dll
    libicuuc.so.48.1      icuuc48.dll
    libicui18n.so.48.1    icuin48.dll
    libzlib123spss.so     zlib123spss.dll
    libspssdio.so.1       spssio32.dll [spssio64.dll]

From kendy at kendy.org  Tue Apr  2 21:24:41 2013
From: kendy at kendy.org (kendy at kendy.org)
Date: Tue, 02 Apr 2013 12:24:41 PDT
Subject: [Tutor] argparse iterable
Message-ID: <24984.1364930681@speakeasy.net>

I forgot about update. It's nice and clean:

     a.update(b)

However, when 'a' has values and 'b' is None, the 'a' item gets clobbered with
None. I found this on stackoverflow.com:

------------------
old = {1: 'one', 2: 'two'}
new = {1: 'newone', 2: None, 3: 'new'}
old.update( (k,v) for k,v in new.iteritems() if v is not None)
------------------

Exactly what I need.

Thanks for the update hint!
Ken

On Tue Apr  2  2:50 , Dave Angel  sent:

>On 04/01/2013 10:28 PM, kendy at kendy.org wrote:
>> You guys are awesome! You make it look easy and I learn every time.
>>
>
>Once you've got the two dicts, take a look into the update method.  It 
>may make any loops unnecessary, except for debugging.
>
>
>-- 
>DaveA
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>To unsubscribe or change subscription options:
>http://mail.python.org/mailman/listinfo/tutor



From alan.gauld at btinternet.com  Tue Apr  2 21:45:03 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 02 Apr 2013 20:45:03 +0100
Subject: [Tutor] Need help on win32 application error
In-Reply-To: <F912AD61E07EBE4FA5E688BF2AD163FC010093EA@CTSINCHNSXMBU.cts.com>
References: <F912AD61E07EBE4FA5E688BF2AD163FC010093EA@CTSINCHNSXMBU.cts.com>
Message-ID: <kjfcfr$lc4$1@ger.gmane.org>

On 02/04/13 19:19, Ankesh.Pratap at cognizant.com wrote:
> Hi Team,
>          I am facing folowing erro while executing python code:
>              Win32 exception occurred releasing IUnknown at 0x03210eb8
> Please let me know the resolution of the same.PFA the version details of python exe that I am using.

The solution is that you need to fix an error in your code.

But without any clue as to what your code looks like how are we supposed 
to guess what caused the error?

I assume you don't get this just starting IDLE?

What code are you running?
How are you running it?
Do you get any other output - like a window displayed,
text in the shell window of IDLE? Anything?
Which version of windows are you using? From the screenshot
it looks like XP but that could just be a UI setting...

We need more detail.

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


From mail at timgolden.me.uk  Tue Apr  2 21:50:27 2013
From: mail at timgolden.me.uk (Tim Golden)
Date: Tue, 02 Apr 2013 20:50:27 +0100
Subject: [Tutor] Need help on win32 application error
In-Reply-To: <F912AD61E07EBE4FA5E688BF2AD163FC010093EA@CTSINCHNSXMBU.cts.com>
References: <F912AD61E07EBE4FA5E688BF2AD163FC010093EA@CTSINCHNSXMBU.cts.com>
Message-ID: <515B3683.4000500@timgolden.me.uk>

On 02/04/2013 19:19, Ankesh.Pratap at cognizant.com wrote:
>          I am facing folowing erro while executing python code:
>              Win32 exception occurred releasing IUnknown at 0x03210eb8

You need to give us a bit more of a clue as to what your code does. My 
guess is that you're using the pywin32 packages and, possibly, the MAPI 
COM interface? That occasionally throws up that sort of exception. 
Assuming I'm right, you're better off asking on the python-win32 mailing 
list, ideally with a reproducible code sample.

TJG

From doark at mail.com  Wed Apr  3 21:43:02 2013
From: doark at mail.com (frank ernest)
Date: Wed, 03 Apr 2013 15:43:02 -0400
Subject: [Tutor] Proper uses of classes
Message-ID: <20130403194302.327670@gmx.com>

Hi guys, it's been a while since I posted and I've learned a lot since then. Today I have a question on classes, I can't get mine to work.
class alist(list):
 def __init__(self, b, a):
 self = list()
 self.append(b)
 a = a + b
 def appendit(self):
 self.append(a)
?
print(alist(2,4))
[]
#It's blank!
c = alist(2,4)
c.appendit()
print(c)
[[...]]
#It's still blank!
If I add this:
 a = a + b
?
the last line of my deffinition I get:
c = alist(2,4)
c.appendit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in appendit
UnboundLocalError: local variable 'a' referenced before assignment
If I make a nonlocal I get
SyntaxError: name 'a' is parameter and nonlocal
I want it to get my list and all the members in it when printing for instance. I also would like to without making them global create two variables which I can use throughout the whole class as their value will not change.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130403/fbe79330/attachment.html>

From davea at davea.name  Wed Apr  3 23:16:15 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 03 Apr 2013 17:16:15 -0400
Subject: [Tutor] Proper uses of classes
In-Reply-To: <20130403194302.327670@gmx.com>
References: <20130403194302.327670@gmx.com>
Message-ID: <515C9C1F.3070600@davea.name>

On 04/03/2013 03:43 PM, frank ernest wrote:
> Hi guys, it's been a while since I posted and I've learned a lot since then. Today I have a question on classes, I can't get mine to work.

Welcome back.  I'll try.  First comment is that indentation ought to be 
4 columns, until you have enough experience to prefer something 
different.  Certainly one column makes the code nearly illegible to me.

Second comment is that deriving from a built-in class like list is 
tricky.  It won't be enough to define an __init__() method, and it turns 
out you're not using the inheritance anyway.  So please get this working 
using only object as your base.  You're probably using Python3.x, where 
object is implied, but it doesn't hurt to be specific.

class alist(object):

> class alist(list):
>   def __init__(self, b, a):
>   self = list()

You forgot to indent the body of the method.  That's an IndentationError 
during compile, so I suspect this code is NOT what you tried.  I'll 
assume you indent the lines from here through the 'def appendit' line.

Please use copy/paste to put your code into your email message.  If you 
retype it, you waste everybody's time.

Don't assign to 'self,' as once you do, you no longer have any access to 
the class instance.  It's a parameter, automatically passed to your 
method.  You probably want to add an attribute to hold the new list.

I'll assume you change it to:
     self.mylist = list()
     self.mylist.append(b)

>   self.append(b)

>   a = a + b
>   def appendit(self):
>   self.append(a)

You didn't indent again.  Further, you referenced a, which was a 
parameter to an entirely different method.  If you meant for it to be 
saved, you could have made it a new attribute in the first method, by using
     self.a = a

> ?
> print(alist(2,4))

You never added anything to the list, so of course it prints out as 
empty.  You created a new one inside your class.

> []
> #It's blank!
> c = alist(2,4)
> c.appendit()
> print(c)
> [[...]]
> #It's still blank!
> If I add this:
>   a = a + b
> ?
> the last line of my deffinition I get:
> c = alist(2,4)
> c.appendit()
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 7, in appendit
> UnboundLocalError: local variable 'a' referenced before assignment
> If I make a nonlocal I get
> SyntaxError: name 'a' is parameter and nonlocal
> I want it to get my list and all the members in it when printing for instance. I also would like to without making them global create two variables which I can use throughout the whole class as their value will not change.
>

If you want a custom printing behavior, you'd need to define a __str__() 
method in your class.  Since you don't, and since you inherit from list, 
you get its behavior.

I made the assumption throughout that it was a mistake to inherit from 
list.  Most of my answers could have been different if you were really 
deliberate about inheriting from list.  For example, you wouldn't be 
able to create your own list, but would have to use the one that you 
inherited from.  You'd have to define a __new__() method, and call 
list's __new__() method from it.   And if you created extra instances as 
your last sentence says, you'd have to define your own __str__() method, 
as the built in list logic wouldn't recognize anything you added.

In any case, I'd write a few successful plain classes before even 
beginning to do inheritance.

HTH

-- 
DaveA

From alan.gauld at btinternet.com  Thu Apr  4 00:09:17 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 03 Apr 2013 23:09:17 +0100
Subject: [Tutor] Proper uses of classes
In-Reply-To: <20130403194302.327670@gmx.com>
References: <20130403194302.327670@gmx.com>
Message-ID: <kji9a9$2tk$1@ger.gmane.org>

On 03/04/13 20:43, frank ernest wrote:
> Hi guys, it's been a while since I posted and I've learned a lot since
> then. Today I have a question on classes, I can't get mine to work.

Dave has already addressed many issues but there are a few more to consider

> class alist(list):
>
>      def __init__(self, b, a):
>      self = list()

This should be indented but it makes no sense. You are trying to create 
a subclass of list but by assigning self to list you no longer have a 
reference to your class, self now points at an instance of the builtin 
list. self is already a list by the time you get to __init__.

>          self.append(b)

This could work without the list() assignment above.

>          a = a + b

this makes no sense since a and b are arguments passed into the method 
and you don't store the result so it gets thrown away, I assume you intended

self.a = a+b

>      def appendit(self):
>          self.append(a)

Again I assume you meant

self.append(self.a)

And this is odd indeed since it can only ever keep adding the 'a' 
specified during initialization. Normally I'd expect an item to be 
appended to be included in the method call? But then you already have 
that with the inherited append method son maybe this odd behaviour is 
what distinguishes your list from the built in list?

> print(alist(2,4))
>
> []
>
> #It's blank!

Yes because you changed self to be a list and so your alist object had 
no changes made to it.

> c = alist(2,4)
> c.appendit()
> print(c)
> [[...]]
>
> #It's still blank!

No, it now has a list inside, although how that got there I'm not sure!


> If I add this:
>          a = a + b
> the last line of my deffinition I get:

Again you omit self so you are only redefining the local variables, 
except there is no 'a' or 'b' to refer to.


> c = alist(2,4)
>
> c.appendit()
>
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "<stdin>", line 7, in appendit
> UnboundLocalError: local variable 'a' referenced before assignment

Since you didn't pass an a into the method you can't assign it to a.

> If I make a nonlocal I get

What do you mean by making it non local?
What did you do?

> SyntaxError: name 'a' is parameter and nonlocal
>
> I want it to get my list and all the members in it when printing for
> instance. I also would like to without making them global create two
> variables which I can use throughout the whole class as their value will
> not change.

Your problems lie in how you build the class in init...
Get the initialisation right and the append/print methods
will be easy. But see Dave's comments re __str__...

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


From phil_lor at bigpond.com  Thu Apr  4 01:14:21 2013
From: phil_lor at bigpond.com (Phil)
Date: Thu, 04 Apr 2013 09:14:21 +1000
Subject: [Tutor] Classes in multiple files
Message-ID: <515CB7CD.2030506@bigpond.com>

Thank you for reading this.

The recent question relating to classes has prompted to ask this one.

I have a main window class and a dialog class and they are defined in 
separate files. I'm attempting to display the dialog when a menu item is 
selected in the main window but it doesn't work because, I think, the 
main window class isn't aware of the dialog class in another file.

This is the beginning of the main window class;

class MainWindow(QMainWindow, Ui_MainWindow):
     def __init__(self, parent = None):

And this is the beginning of the dialog class;

class SatelliteListDialog(QDialog, Ui_Dialog):
     def __init__(self, parent = None):

If this was C++ then I'd need to include a class header and so I'm 
thinking that an import statement is needed in the main window class 
referring to the dialog class. Import SatelliteListDialog isn't correct.

There are many on-line examples that deal with displaying dialogs, 
however, both classes are in the same file rather that being separated.

No doubt, this is a trivial question but, as yet, I have not found an 
answer.

-- 
Regards,
Phil

From alan.gauld at btinternet.com  Thu Apr  4 01:32:43 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 04 Apr 2013 00:32:43 +0100
Subject: [Tutor] Classes in multiple files
In-Reply-To: <515CB7CD.2030506@bigpond.com>
References: <515CB7CD.2030506@bigpond.com>
Message-ID: <kjie6n$fvk$1@ger.gmane.org>

On 04/04/13 00:14, Phil wrote:

> If this was C++ then I'd need to include a class header and so I'm
> thinking that an import statement is needed in the main window class
> referring to the dialog class. Import SatelliteListDialog isn't correct.

Reme,ber that in python its the file name you need to use to import

So if SatelliteListDialog is defined in satellite.py you need

import satellite

in your main window file.
And satellite.py has to be in your library path too...

Then in your main window class you need to access the dialog with

    self.sld = satellite.SatelliteListDialog(...)

or whatever. In other words you need the module name prefix.

If that still doesn't work post some code and any error messages.

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


From bessenkphilip at gmail.com  Thu Apr  4 03:29:02 2013
From: bessenkphilip at gmail.com (bessenkphilip)
Date: Thu, 04 Apr 2013 06:59:02 +0530
Subject: [Tutor] Doubt in for loop
Message-ID: <515CD75E.3030306@gmail.com>

Hi all,

I'm having a doubt in the below program's 2n'd "for" loop.

 >>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print n, 'equals', x, '*', n/x
...             break
...     else:
...         # loop fell through without finding a factor
...         print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

My doubt is that "will 'x' be always of value 2, if so why that for loop 
"for x in range(2, n):"
i don't know how the first output , as If 2%2==0:(this satisfies the if 
loop as x =2) , so how the else part came to output i.e 2 is a prime number.

Please educate me in this.

Thanks in advance,
  -Bessen

From phil_lor at bigpond.com  Thu Apr  4 02:22:11 2013
From: phil_lor at bigpond.com (Phil)
Date: Thu, 04 Apr 2013 10:22:11 +1000
Subject: [Tutor] Classes in multiple files
In-Reply-To: <kjie6n$fvk$1@ger.gmane.org>
References: <515CB7CD.2030506@bigpond.com> <kjie6n$fvk$1@ger.gmane.org>
Message-ID: <515CC7B3.20204@bigpond.com>

On 04/04/13 09:32, Alan Gauld wrote:
> On 04/04/13 00:14, Phil wrote:
>
>> If this was C++ then I'd need to include a class header and so I'm
>> thinking that an import statement is needed in the main window class
>> referring to the dialog class. Import SatelliteListDialog isn't correct.
>
> Reme,ber that in python its the file name you need to use to import
>
> So if SatelliteListDialog is defined in satellite.py you need
>
> import satellite
>
> in your main window file.
> And satellite.py has to be in your library path too...
>

That makes sense, much like a header file in C++. I haven't set a 
library path, so I'm using the default, what ever it may be. I'll 
investigate this.

> Then in your main window class you need to access the dialog with
>
>     self.sld = satellite.SatelliteListDialog(...)
>
> or whatever. In other words you need the module name prefix.
>
> If that still doesn't work post some code and any error messages.
>

At the moment I'm a little uncertain how I should proceed from here but 
I'll give it a go.

-- 
Regards,
Phil

From phil_lor at bigpond.com  Thu Apr  4 03:47:05 2013
From: phil_lor at bigpond.com (Phil)
Date: Thu, 04 Apr 2013 11:47:05 +1000
Subject: [Tutor] Classes in multiple files - code included
In-Reply-To: <kjie6n$fvk$1@ger.gmane.org>
References: <515CB7CD.2030506@bigpond.com> <kjie6n$fvk$1@ger.gmane.org>
Message-ID: <515CDB99.7010609@bigpond.com>

On 04/04/13 09:32, Alan Gauld wrote:
<cut>

> Reme,ber that in python its the file name you need to use to import
>
> So if SatelliteListDialog is defined in satellite.py you need
>
> import satellite
>
> in your main window file.
> And satellite.py has to be in your library path too...

The Eric IDE must take care of the path. All I had to do was import the 
file containing the dialog class.

> Then in your main window class you need to access the dialog with
>
>     self.sld = satellite.SatelliteListDialog(...)
>
> or whatever. In other words you need the module name prefix.
>
> If that still doesn't work post some code and any error messages.

I think I must be very close now so I'll post just the code that I think 
is relevant.

This the main window class:

from PyQt4.QtGui import QMainWindow
from PyQt4.QtCore import pyqtSignature

from Ui_mainwindow import Ui_MainWindow

from PyQt4 import QtGui

import satListDialog

class MainWindow(QMainWindow, Ui_MainWindow):

This is the function to show the dialog;

def on_actionList_triggered(self):

	self.dialog = Ui_satListDialog.SatelliteListDialog()
         self.dialog.show()

Finally, this is the dialog class;

from PyQt4.QtGui import QDialog
from PyQt4.QtCore import pyqtSignature

from Ui_satListDialog import Ui_Dialog

class SatelliteListDialog(QDialog, Ui_Dialog):

And this is the error message;

"global name 'Ui_satListDialog' is not defined"

I have tried just about every conceivable combination in the 
on_actionList_triggered(self) function but I still end up with a "not 
defined" error.

-- 
Regards,
Phil

From steve at pearwood.info  Thu Apr  4 03:53:41 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 04 Apr 2013 12:53:41 +1100
Subject: [Tutor] Doubt in for loop
In-Reply-To: <515CD75E.3030306@gmail.com>
References: <515CD75E.3030306@gmail.com>
Message-ID: <515CDD25.8050208@pearwood.info>

On 04/04/13 12:29, bessenkphilip wrote:
> Hi all,
>
> I'm having a doubt in the below program's 2n'd "for" loop.
>
>>>> for n in range(2, 10):
> ...     for x in range(2, n):
> ...         if n % x == 0:
> ...             print n, 'equals', x, '*', n/x
> ...             break
> ...     else:
> ...         # loop fell through without finding a factor
> ...         print n, 'is a prime number'
> ...
> 2 is a prime number
> 3 is a prime number
> 4 equals 2 * 2
> 5 is a prime number
> 6 equals 2 * 3
> 7 is a prime number
> 8 equals 2 * 4
> 9 equals 3 * 3
>
> My doubt is that "will 'x' be always of value 2, if so why that for loop "for x in range(2, n):"
> i don't know how the first output , as If 2%2==0:(this satisfies the if loop as x =2) , so how the else part came to output i.e 2 is a prime number.

I'm sorry, I don't understand your question.

x is *not* always of value 2. You can see with the last line,

9 equals 3 * 3

x has value 3.


The outer loop just checks 2, 3, 4, ... 9 to see whether they are prime. The inner loop actually does the checking:


for x in range(2, n):
     if n % x == 0:
         print n, 'equals', x, '*', n/x
         break


This tests whether n is divisible by 2, 3, 4, 5, 6, ... up to n-1. If n is divisible by any of those numbers, then n cannot be prime.

For example, with n = 9, the inner loop does this:

x = 2
Test if 2 is a factor: does 9/2 have remainder zero? No.
x = 3
Test if 3 is a factor: does 9/3 have remainder zero? Yes.
So 9 is not prime, and 9 = 3 * (9/3) = 3 * 3


If we test it with n = 35, the inner loop would do this:

x = 2
Test if 2 is a factor: does 35/2 have remainder zero? No.
x = 3
Test if 3 is a factor: does 35/3 have remainder zero? No.
x = 4
Test if 4 is a factor: does 35/4 have remainder zero? No.
x = 5
Test if 5 is a factor: does 35/5 have remainder zero? Yes.
So 35 is not prime, and 35 = 5 * (35/5) = 5 * 7



Notice that this does more work than necessary! Can you see what work it does that is unnecessary?

(Hint: what even numbers are prime?)




-- 
Steven

From steve at pearwood.info  Thu Apr  4 03:58:09 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 04 Apr 2013 12:58:09 +1100
Subject: [Tutor] Classes in multiple files - code included
In-Reply-To: <515CDB99.7010609@bigpond.com>
References: <515CB7CD.2030506@bigpond.com> <kjie6n$fvk$1@ger.gmane.org>
	<515CDB99.7010609@bigpond.com>
Message-ID: <515CDE31.9010301@pearwood.info>

On 04/04/13 12:47, Phil wrote:

> And this is the error message;
>
> "global name 'Ui_satListDialog' is not defined"

On its own, that is almost useless.

Python gives you more debugging information than that: it gives you a complete traceback, which includes the actual line of code causing the problem. We don't even know which file gives the error, let alone which line of code!

When you try to run the program, you will get an error. Please copy and paste the *complete* traceback, starting with the line "Traceback (most recent call last)" all the way to the bottom. It will show you which file contains the error, what type of error it is, and which line fails.


Thank you.




-- 
Steven

From davea at davea.name  Thu Apr  4 04:53:15 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 03 Apr 2013 22:53:15 -0400
Subject: [Tutor] Doubt in for loop
In-Reply-To: <515CDD25.8050208@pearwood.info>
References: <515CD75E.3030306@gmail.com> <515CDD25.8050208@pearwood.info>
Message-ID: <515CEB1B.30004@davea.name>

On 04/03/2013 09:53 PM, Steven D'Aprano wrote:
> On 04/04/13 12:29, bessenkphilip wrote:
>> Hi all,
>>
>> I'm having a doubt in the below program's 2n'd "for" loop.
>>
>>>>> for n in range(2, 10):
>> ...     for x in range(2, n):
>> ...         if n % x == 0:
>> ...             print n, 'equals', x, '*', n/x
>> ...             break
>> ...     else:
>> ...         # loop fell through without finding a factor
>> ...         print n, 'is a prime number'
>> ...
>> 2 is a prime number
>> 3 is a prime number
>> 4 equals 2 * 2
>> 5 is a prime number
>> 6 equals 2 * 3
>> 7 is a prime number
>> 8 equals 2 * 4
>> 9 equals 3 * 3
>>
>> My doubt is that "will 'x' be always of value 2, if so why that for
>> loop "for x in range(2, n):"
>> i don't know how the first output , as If 2%2==0:(this satisfies the
>> if loop as x =2) , so how the else part came to output i.e 2 is a
>> prime number.
>
> I'm sorry, I don't understand your question.
>
> x is *not* always of value 2. You can see with the last line,
>
> 9 equals 3 * 3
>
> x has value 3.
>
>
> The outer loop just checks 2, 3, 4, ... 9 to see whether they are prime.
> The inner loop actually does the checking:
>
>
> for x in range(2, n):
>      if n % x == 0:
>          print n, 'equals', x, '*', n/x
>          break
>
>
> This tests whether n is divisible by 2, 3, 4, 5, 6, ... up to n-1. If n
> is divisible by any of those numbers, then n cannot be prime.
>
> For example, with n = 9, the inner loop does this:
>
> x = 2
> Test if 2 is a factor: does 9/2 have remainder zero? No.
> x = 3
> Test if 3 is a factor: does 9/3 have remainder zero? Yes.
> So 9 is not prime, and 9 = 3 * (9/3) = 3 * 3
>
>
> If we test it with n = 35, the inner loop would do this:
>
> x = 2
> Test if 2 is a factor: does 35/2 have remainder zero? No.
> x = 3
> Test if 3 is a factor: does 35/3 have remainder zero? No.
> x = 4
> Test if 4 is a factor: does 35/4 have remainder zero? No.
> x = 5
> Test if 5 is a factor: does 35/5 have remainder zero? Yes.
> So 35 is not prime, and 35 = 5 * (35/5) = 5 * 7
>
>
>
> Notice that this does more work than necessary! Can you see what work it
> does that is unnecessary?
>
> (Hint: what even numbers are prime?)
>
>
>
>

I don't understand the questions either, but I can point out one thing 
that might be puzzling the OP:

When n is 2, the inner loop does nothing, it just skips to the else 
clause.  The reason is that range(2,2) is a null iterator.  range(i,j) 
produces values from i to j-1, or to put it another way values for which
    i <= n < j

If i and j are identical, there's nothing to match it.


-- 
DaveA

From antipode0 at gmail.com  Thu Apr  4 05:34:10 2013
From: antipode0 at gmail.com (antipode0)
Date: Wed, 3 Apr 2013 22:34:10 -0500
Subject: [Tutor] Doubt in for loop
In-Reply-To: <515CEB1B.30004@davea.name>
References: <515CD75E.3030306@gmail.com> <515CDD25.8050208@pearwood.info>
	<515CEB1B.30004@davea.name>
Message-ID: <CA+DELmOu=szvi9b5U-qBMUU53w3XXxcQmFxswcvfcfCUjGoEVQ@mail.gmail.com>

I believe Dave answered the OP's intended question.
On Apr 3, 2013 9:54 PM, "Dave Angel" <davea at davea.name> wrote:

> On 04/03/2013 09:53 PM, Steven D'Aprano wrote:
>
>> On 04/04/13 12:29, bessenkphilip wrote:
>>
>>> Hi all,
>>>
>>> I'm having a doubt in the below program's 2n'd "for" loop.
>>>
>>>  for n in range(2, 10):
>>>>>>
>>>>> ...     for x in range(2, n):
>>> ...         if n % x == 0:
>>> ...             print n, 'equals', x, '*', n/x
>>> ...             break
>>> ...     else:
>>> ...         # loop fell through without finding a factor
>>> ...         print n, 'is a prime number'
>>> ...
>>> 2 is a prime number
>>> 3 is a prime number
>>> 4 equals 2 * 2
>>> 5 is a prime number
>>> 6 equals 2 * 3
>>> 7 is a prime number
>>> 8 equals 2 * 4
>>> 9 equals 3 * 3
>>>
>>> My doubt is that "will 'x' be always of value 2, if so why that for
>>> loop "for x in range(2, n):"
>>> i don't know how the first output , as If 2%2==0:(this satisfies the
>>> if loop as x =2) , so how the else part came to output i.e 2 is a
>>> prime number.
>>>
>>
>> I'm sorry, I don't understand your question.
>>
>> x is *not* always of value 2. You can see with the last line,
>>
>> 9 equals 3 * 3
>>
>> x has value 3.
>>
>>
>> The outer loop just checks 2, 3, 4, ... 9 to see whether they are prime.
>> The inner loop actually does the checking:
>>
>>
>> for x in range(2, n):
>>      if n % x == 0:
>>          print n, 'equals', x, '*', n/x
>>          break
>>
>>
>> This tests whether n is divisible by 2, 3, 4, 5, 6, ... up to n-1. If n
>> is divisible by any of those numbers, then n cannot be prime.
>>
>> For example, with n = 9, the inner loop does this:
>>
>> x = 2
>> Test if 2 is a factor: does 9/2 have remainder zero? No.
>> x = 3
>> Test if 3 is a factor: does 9/3 have remainder zero? Yes.
>> So 9 is not prime, and 9 = 3 * (9/3) = 3 * 3
>>
>>
>> If we test it with n = 35, the inner loop would do this:
>>
>> x = 2
>> Test if 2 is a factor: does 35/2 have remainder zero? No.
>> x = 3
>> Test if 3 is a factor: does 35/3 have remainder zero? No.
>> x = 4
>> Test if 4 is a factor: does 35/4 have remainder zero? No.
>> x = 5
>> Test if 5 is a factor: does 35/5 have remainder zero? Yes.
>> So 35 is not prime, and 35 = 5 * (35/5) = 5 * 7
>>
>>
>>
>> Notice that this does more work than necessary! Can you see what work it
>> does that is unnecessary?
>>
>> (Hint: what even numbers are prime?)
>>
>>
>>
>>
>>
> I don't understand the questions either, but I can point out one thing
> that might be puzzling the OP:
>
> When n is 2, the inner loop does nothing, it just skips to the else
> clause.  The reason is that range(2,2) is a null iterator.  range(i,j)
> produces values from i to j-1, or to put it another way values for which
>    i <= n < j
>
> If i and j are identical, there's nothing to match it.
>
>
> --
> DaveA
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130403/b3d35915/attachment-0001.html>

From phil_lor at bigpond.com  Thu Apr  4 04:12:04 2013
From: phil_lor at bigpond.com (Phil)
Date: Thu, 04 Apr 2013 12:12:04 +1000
Subject: [Tutor] Classes in multiple files - code included
In-Reply-To: <515CDE31.9010301@pearwood.info>
References: <515CB7CD.2030506@bigpond.com> <kjie6n$fvk$1@ger.gmane.org>
	<515CDB99.7010609@bigpond.com> <515CDE31.9010301@pearwood.info>
Message-ID: <515CE174.9000602@bigpond.com>

On 04/04/13 11:58, Steven D'Aprano wrote:
> On 04/04/13 12:47, Phil wrote:
>
>> And this is the error message;
>>
>> "global name 'Ui_satListDialog' is not defined"
>
> On its own, that is almost useless.
>
> Python gives you more debugging information than that: it gives you a
> complete traceback, which includes the actual line of code causing the
> problem. We don't even know which file gives the error, let alone which
> line of code!
>
> When you try to run the program, you will get an error. Please copy and
> paste the *complete* traceback, starting with the line "Traceback (most
> recent call last)" all the way to the bottom. It will show you which
> file contains the error, what type of error it is, and which line fails.
>

Thank you for your reply Steven,

As useless as the error message may be it's the only one given.

phil at Asus:~/Eric/Pest$ python pest.py
Traceback (most recent call last):
   File "/home/phil/Eric/Pest/ui/mainwindow.py", line 57, in 
on_actionList_triggered
     dialog = Ui_satListDialog.SatelliteListDialog(self)
NameError: global name 'Ui_satListDialog' is not defined
^CTraceback (most recent call last):
   File "pest.py", line 9, in <module>
     sys.exit(app.exec_())

-- 
Regards,
Phil

From __peter__ at web.de  Thu Apr  4 08:58:01 2013
From: __peter__ at web.de (Peter Otten)
Date: Thu, 04 Apr 2013 08:58:01 +0200
Subject: [Tutor] Classes in multiple files - code included
References: <515CB7CD.2030506@bigpond.com> <kjie6n$fvk$1@ger.gmane.org>
	<515CDB99.7010609@bigpond.com>
Message-ID: <kjj87j$8n3$1@ger.gmane.org>

Phil wrote:

> I think I must be very close now so I'll post just the code that I think
> is relevant.
> 
> This the main window class:

> import satListDialog

Here you are importing the module "satListDialog"
 
> class MainWindow(QMainWindow, Ui_MainWindow):
> 
> This is the function to show the dialog;
> 
>     def on_actionList_triggered(self):
> 
>         self.dialog = Ui_satListDialog.SatelliteListDialog()
>         self.dialog.show()

and here you are referring to the module "Ui_satListDialog". I'd guess that 
should be

        self.dialog = satListDialog.SatelliteListDialog()

instead.


From phil_lor at bigpond.com  Thu Apr  4 09:51:02 2013
From: phil_lor at bigpond.com (Phil)
Date: Thu, 04 Apr 2013 17:51:02 +1000
Subject: [Tutor] Classes in multiple files - code included
In-Reply-To: <kjj87j$8n3$1@ger.gmane.org>
References: <515CB7CD.2030506@bigpond.com> <kjie6n$fvk$1@ger.gmane.org>
	<515CDB99.7010609@bigpond.com> <kjj87j$8n3$1@ger.gmane.org>
Message-ID: <515D30E6.3040803@bigpond.com>

On 04/04/13 16:58, Peter Otten wrote:
> Phil wrote:
>
>> I think I must be very close now so I'll post just the code that I think
>> is relevant.
>>
>> This the main window class:
>
>> import satListDialog
>
> Here you are importing the module "satListDialog"
>
>> class MainWindow(QMainWindow, Ui_MainWindow):
>>
>> This is the function to show the dialog;
>>
>>      def on_actionList_triggered(self):
>>
>>          self.dialog = Ui_satListDialog.SatelliteListDialog()
>>          self.dialog.show()
>
> and here you are referring to the module "Ui_satListDialog". I'd guess that
> should be
>
>          self.dialog = satListDialog.SatelliteListDialog()
>
> instead.

Thanks Peter,

This one of those times when I wish I could cancel a question. I 
discovered the answer, mostly through trial and error, a couple of hours 
ago. I had also accidentally commented out a line in the dialog class. 
Anyway, I've made some headway with PyQt today.

By the way, I notice that it can take several hours for my postings to 
appear on the list. Possibly due to moderation?

-- 
Regards,
Phil

From steve at pearwood.info  Thu Apr  4 11:40:46 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 04 Apr 2013 20:40:46 +1100
Subject: [Tutor] Classes in multiple files - code included
In-Reply-To: <515CE174.9000602@bigpond.com>
References: <515CB7CD.2030506@bigpond.com> <kjie6n$fvk$1@ger.gmane.org>
	<515CDB99.7010609@bigpond.com> <515CDE31.9010301@pearwood.info>
	<515CE174.9000602@bigpond.com>
Message-ID: <515D4A9E.9060005@pearwood.info>

On 04/04/13 13:12, Phil wrote:
> On 04/04/13 11:58, Steven D'Aprano wrote:
>> On 04/04/13 12:47, Phil wrote:
>>
>>> And this is the error message;
>>>
>>> "global name 'Ui_satListDialog' is not defined"
>>
>> On its own, that is almost useless.
>>
>> Python gives you more debugging information than that: it gives you a
>> complete traceback, which includes the actual line of code causing the
>> problem. We don't even know which file gives the error, let alone which
>> line of code!
>>
>> When you try to run the program, you will get an error. Please copy and
>> paste the *complete* traceback, starting with the line "Traceback (most
>> recent call last)" all the way to the bottom. It will show you which
>> file contains the error, what type of error it is, and which line fails.
>>
>
> Thank you for your reply Steven,
>
> As useless as the error message may be it's the only one given.


You have misunderstood me. In your email, quoted above, you pasted ONLY the
error message "global name 'Ui_satListDialog' is not defined".

But now, following my prompting, you pasted the ENTIRE traceback:

> phil at Asus:~/Eric/Pest$ python pest.py
> Traceback (most recent call last):
>    File "/home/phil/Eric/Pest/ui/mainwindow.py", line 57, in on_actionList_triggered
>      dialog = Ui_satListDialog.SatelliteListDialog(self)
> NameError: global name 'Ui_satListDialog' is not defined
> ^CTraceback (most recent call last):
>    File "pest.py", line 9, in <module>
>      sys.exit(app.exec_())

Notice how much more information there is? We learn:

* the error is occurring in your mainwindow.py file

* on line 57

* in the function or method "on_actionList_triggered"

* with the exact line "dialog = Ui_satListDialog.SatelliteListDialog(self)"

* which gives a NameError (as apposed to any of dozens of different sorts of error)

* with the specific error message "global name 'Ui_satListDialog' is not defined"

(and then there is a further error when you try to quit the app with Ctrl-C, but one thing at a time).

One of the most critical skills for a programmer is to learn how to diagnose errors. Trying to diagnose the error from just the error message is a bit like telling the doctor you have a pain, but refusing to tell where the pain is, what sort of pain, how long you've had it, or under what circumstances it comes and goes.

Debugging, at times, is hard enough even with the assistance of full tracebacks. You'll soon learn to appreciate them.



-- 
Steven

From alan.gauld at btinternet.com  Thu Apr  4 14:45:04 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 04 Apr 2013 13:45:04 +0100
Subject: [Tutor] Classes in multiple files - code included
In-Reply-To: <515D30E6.3040803@bigpond.com>
References: <515CB7CD.2030506@bigpond.com> <kjie6n$fvk$1@ger.gmane.org>
	<515CDB99.7010609@bigpond.com> <kjj87j$8n3$1@ger.gmane.org>
	<515D30E6.3040803@bigpond.com>
Message-ID: <kjjskc$uu3$1@ger.gmane.org>

On 04/04/13 08:51, Phil wrote:

> By the way, I notice that it can take several hours for my postings to
> appear on the list. Possibly due to moderation?

Nope, the only posts that get moderated are the ones where the poster 
has not subscribed to the list (or is using a different email address 
than the one they signed up with!)

Remember email is not a high priority message type on the internet. The 
suggested SLA for delivery used to be 48 hours but I believe current 
recommendations say 24 hours. So even though mail usually gets there 
much faster than that you shouldn't count on it. (Note that if you are 
using corporate "email" like Microsoft Exchange that's not really email 
at all, just corporate messaging which is nearly instant!).

And of course email is not guaranteed delivery either so it might
never get there - if a server gets busy it's quite within its rights to 
just throw all the email messages away...! And the nature of the 
internet is that your mail may be routing through somebody's old
50MHz 486 PC server somewhere in Uzbekistan or Mongolia...

Having said all that, I rarely see a post to tutor take more than 20 
minutes to get onto the gmane newsfeed that I use from the list server.

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


From cevyne at gmail.com  Mon Apr  1 21:08:00 2013
From: cevyne at gmail.com (cevyn e)
Date: Mon, 1 Apr 2013 15:08:00 -0400
Subject: [Tutor] os.system() with imbeded quotes
Message-ID: <CAK7xEK9zA6pyn=35OAZJhooRVjpofAM_iARcatVk7nVXHDBePA@mail.gmail.com>

I get the example os.system('ls -al')     no problem.

i'm trying to create a variable with my command built but needs to include
quotes.
Portion of code is as follows:
someip = '192.168.01.01'

var1 = 'lynx -dump http://' + someip +
'/cgi-bin/xxxx.log&.submit=+++Go%21+++  > junk'

print  var1

os.system(var1)


If I print var1 it looks right .  If I use the os.system(var1) as above it
seems to have a problem near the end of the string with msg
sh: .submit=+++Go%21+++: command not found

clearly there is some escape sequence that I don't understand .

I tried combinations of single and double quotes and mixed around var1, but
that generates command not found.

I need it to look like how I enter it manually and works
lynx -dump 'http://192.168.01.01/cgi-bin/xxxx.log&.submit=+++Go%21+++  >
junk'

Probably obvious to many but i'm spinning my wheels.  many thanks for help .
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130401/513752ee/attachment.html>

From moshiri.ehsan.ns at gmail.com  Tue Apr  2 05:01:55 2013
From: moshiri.ehsan.ns at gmail.com (EnkidU Moshiri)
Date: Tue, 2 Apr 2013 11:01:55 +0800
Subject: [Tutor] chat-server python
Message-ID: <CAPEjUQnnQ4E4o_cdb-Xz_Lpbvhup16AQOvxp-1UxLkUcg+Fp0g@mail.gmail.com>

Hello there,
am beginner in python. i want start my first project with chat-server.
i want create a messenger which encodes msg, hides it in a
image(steganography) and send it to second user. i want this messenger be
available also by internet and non static ips,so i want use chat server.
also i want filter incoming packets,which only trusted MAC addresses can
communicate with mesenger
may i get some help from u?
any chat-server messenger source code for python?
after i finish encoding and steganography part,i will upload my job in your
site
thank u
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130402/28c3689b/attachment.html>

From alan.gauld at btinternet.com  Thu Apr  4 14:59:48 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 04 Apr 2013 13:59:48 +0100
Subject: [Tutor] moderation queue flushed - may be old/duplicates coming
	through
Message-ID: <kjjtg0$9bj$1@ger.gmane.org>

I've just flushed the queue so there will be some old or duplicate 
messages coming through.

Apologies, but I hadn't looked in there for a couple of weeks!
Oops.

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


From msirenef at lightbird.net  Thu Apr  4 15:25:19 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Thu, 04 Apr 2013 09:25:19 -0400
Subject: [Tutor] File Import
In-Reply-To: <CACpSQX2YYF+1pSMohgribCvYsWS4ok25oKGTNLxAHsVe=Q7kJA@mail.gmail.com>
References: <CACpSQX2YYF+1pSMohgribCvYsWS4ok25oKGTNLxAHsVe=Q7kJA@mail.gmail.com>
Message-ID: <515D7F3F.6050700@lightbird.net>

On 03/18/2013 11:14 PM, Clark, Tristan wrote:
> Hi,
>
> I am importing data produced from an external code. The data is 
> organized into columns. I would like to be able to assign each column 
> to a variable or array. How would you recommend doing this? I have 
> been looking into the pickle function, as well as "f.readline" and 
> "for line in f:" and I got all of those ideas from the Python 
> Tutorial. I am a little new to python.
>
> Thank you,
>
> Tristan Clark
>

Take a look at csv module (for Py2, see drop down version choice for Py3):

http://docs.python.org/2/library/csv.html

Is the data going to be ASCII? There are some issues in regard to csv / 
unicode
handling.   -m


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/


From msirenef at lightbird.net  Thu Apr  4 15:26:47 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Thu, 04 Apr 2013 09:26:47 -0400
Subject: [Tutor] Help required
In-Reply-To: <OF7271B190.E279D323-ON65257B34.0021B8C4-65257B34.002222D9@tcs.com>
References: <OF7271B190.E279D323-ON65257B34.0021B8C4-65257B34.002222D9@tcs.com>
Message-ID: <515D7F97.2060107@lightbird.net>

On 03/20/2013 02:12 AM, Arijit Ukil wrote:
> I am new to python. My intention is to read the file digi.txt and 
> store in separate arrays all the values of each columns. However, the 
> following program prints only the last value, i.e. 1350696500.0.
> Please help to rectify this.
>
> f = open (/"digi.txt"/, /"r+"/)
>
> datafile = f.readlines()
>
> list_of_lists = datafile
> fordata inlist_of_lists:
>     lstval = data.split (/','/)
>     timest = float(lstval[0])
>     energy = float(lstval[1])
>
> f.close()
> printtimest
>
> Regards,
> Arijit Ukil


You would want to create an empty list and then
append values to it inside the loop. E.g. lst=[]; lst.append(val)

  -m

-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/


From msirenef at lightbird.net  Thu Apr  4 15:32:33 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Thu, 04 Apr 2013 09:32:33 -0400
Subject: [Tutor] Tutor Digest, Vol 109, Issue 71
In-Reply-To: <-1797977811238906169@unknownmsgid>
References: <mailman.18675.1363825634.2938.tutor@python.org>
	<-1797977811238906169@unknownmsgid>
Message-ID: <515D80F1.3020601@lightbird.net>

On 03/20/2013 09:14 PM, Matthew Johnson wrote:
> I recently asked a question on SO: 
> http://stackoverflow.com/questions/15180767/subset-list-based-on-value-of-dictionary-element
>
> and got very confused when trying to generalise the answer.
>
> The problem is as follows:
>
> say i have this list, and would like to get the value at each date 
> that has the largest value for realtime_start (date) value.
>
> obs = [{'date': '2012-10-01',
> 'realtime_end': '2013-02-18',
> 'realtime_start': '2012-11-15',
> 'value': '231.751'},
>  {'date': '2012-10-01',
> 'realtime_end': '9999-12-31',
> 'realtime_start': '2012-12-19',
> 'value': '231.623'},
>  {'date': '2012-11-01',
> 'realtime_end': '2013-02-18',
> 'realtime_start': '2012-12-14',
> 'value': '231.025'},
>  {'date': '2012-11-01',
> 'realtime_end': '9999-12-31',
> 'realtime_start': '2013-01-19',
> 'value': '231.071'},
>  {'date': '2012-12-01',
> 'realtime_end': '2013-02-18',
> 'realtime_start': '2013-01-16',
> 'value': '230.979'},
>  {'date': '2012-12-01',
> 'realtime_end': '9999-12-31',
> 'realtime_start': '2013-02-19',
> 'value': '231.137'},
>  {'date': '2012-12-01',
> 'realtime_end': '9999-12-31',
> 'realtime_start': '2013-03-19',
> 'value': '231.197'},
>  {'date': '2013-01-01',
> 'realtime_end': '9999-12-31',
> 'realtime_start': '2013-02-21',
> 'value': '231.198'},
>  {'date': '2013-01-01',
> 'realtime_end': '9999-12-31',
> 'realtime_start': '2013-03-21',
> 'value': '231.222'}]
>
> maxDate = "2013-02-21"
>
> The answer suggested itertools, and it worked for the exact maxDate 
> that's above.
> However, when i move the date (say to "2013-01-21") it throws the error:
>
> ValueError: max() arg is an empty sequence.
>
> I can see from the list that there are elements
> that have realtime_start values that are lower than 2013-01-21 so this 
> is a bug.
>
> I have read the documents for itertools, but cannot quite work out 
> this groupby stuff.
>
> there's a snip of the SO solution below -- help understanding as well 
> as the bug fix would be much appreciated.
>
> thanks in advance,
>
> Matt Johnson


You should refer to my earlier answer using groupby -- where
I sorted the list before using groupby on it; you can read some
notes on this in python groupby documentation.

I'm not sure why you insist on using groupby for this problem.

I would also try to stay away from packing so much in a single
list comp as the SO answer does, and instead split things into
separate steps where each step is simple and clear, then
you'd be able to print out intermediate results and see what
exactly is happening.

  -m



-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/


From sayanchatterjee at gmail.com  Thu Apr  4 15:40:33 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Thu, 4 Apr 2013 19:10:33 +0530
Subject: [Tutor] TypeError: can't multiply sequence by non-int of type
	'float'
Message-ID: <CAAT-4ORd5aedzszZHOOBd94Np98+ZE+61oVQeoGMz8=DQdHuWw@mail.gmail.com>

Dear All,

I know this error occurs when one tries to multiply a string with a
fraction i.e float. In my case , I can't figure out how can a numpy
floating point array be a string.  Interestingly, the concerned expression
gets printed in the loop for the first time but on the second go it fails.

The concerned snippet of code is given below :

for t in t_range(0,1,0.1):
  print t
  p_za=[]
  pv_za=[]

  # Opening file in file_t format
  fname = 'file_' + str(t) + '.dat'
  fo = open(fname,'w')

  # p_za.append(p_initial - t*K*np.sin(K*p_initial))
  print 'K=',K
  print 'pv_za_temp =',pv_za_temp
  print '- t*K*np.sin(K*p_initial) = ',- t*K*np.sin(K*p_initial)
  print '-K*np.sin(K*pv_za_temp) = ',-K*np.sin(K*pv_za_temp)
  pv_za.append(-K*np.sin(K*pv_za_temp))
  pv_za_temp = []
  pv_za_temp.append(np.array(pv_za))


Here is paste the output,which clearly  shows that the concerned expression
i.e -K*np.sin(K*pv_za_temp) prints perfectly for the first looping. Also
see the error that comes on the second looping. I'm clueless.

0
K= 3.14159265359
pv_za_temp = [ 0.   0.5  1.   1.5  2. ]
- t*K*np.sin(K*p_initial) =  [ 0.  0. -0. -0.  0.]
*-K*np.sin(K*pv_za_temp) =  [ -0.00000000e+00  -3.14159265e+00
6.49753967e-13   3.14159265e+00*
*  -1.29950793e-12] PRINTS PERFECTLY*
*
*
0.1
K= 3.14159265359
pv_za_temp = [array([[ -0.00000000e+00,  -3.14159265e+00,   6.49753967e-13,
          3.14159265e+00,  -1.29950793e-12]])]
- t*K*np.sin(K*p_initial) =  [ -0.00000000e+00  -3.14159265e-01
6.49753967e-14   3.14159265e-01
  -1.29950793e-13]
-K*np.sin(K*pv_za_temp) = *ERROR*
Traceback (most recent call last):
  File "ZA.py", line 45, in <module>
    print '-K*np.sin(K*pv_za_temp) = ',-K*np.sin(K*pv_za_temp)
*TypeError: can't multiply sequence by non-int of type 'float'*

Please Help!!!!


Cheers,
Sayan


-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130404/ece43175/attachment-0001.html>

From sayanchatterjee at gmail.com  Thu Apr  4 15:41:21 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Thu, 4 Apr 2013 19:11:21 +0530
Subject: [Tutor] TypeError: can't multiply sequence by non-int of type
	'float'
In-Reply-To: <CAAT-4ORd5aedzszZHOOBd94Np98+ZE+61oVQeoGMz8=DQdHuWw@mail.gmail.com>
References: <CAAT-4ORd5aedzszZHOOBd94Np98+ZE+61oVQeoGMz8=DQdHuWw@mail.gmail.com>
Message-ID: <CAAT-4OS+XFuSh2gRSYkuACUQKsZ8roCzNddsoLdSZuOHKgGLPQ@mail.gmail.com>

I attach the script herewith.


On 4 April 2013 19:10, Sayan Chatterjee <sayanchatterjee at gmail.com> wrote:

> Dear All,
>
> I know this error occurs when one tries to multiply a string with a
> fraction i.e float. In my case , I can't figure out how can a numpy
> floating point array be a string.  Interestingly, the concerned expression
> gets printed in the loop for the first time but on the second go it fails.
>
> The concerned snippet of code is given below :
>
> for t in t_range(0,1,0.1):
>   print t
>   p_za=[]
>   pv_za=[]
>
>   # Opening file in file_t format
>   fname = 'file_' + str(t) + '.dat'
>   fo = open(fname,'w')
>
>   # p_za.append(p_initial - t*K*np.sin(K*p_initial))
>   print 'K=',K
>   print 'pv_za_temp =',pv_za_temp
>   print '- t*K*np.sin(K*p_initial) = ',- t*K*np.sin(K*p_initial)
>   print '-K*np.sin(K*pv_za_temp) = ',-K*np.sin(K*pv_za_temp)
>   pv_za.append(-K*np.sin(K*pv_za_temp))
>   pv_za_temp = []
>   pv_za_temp.append(np.array(pv_za))
>
>
> Here is paste the output,which clearly  shows that the concerned
> expression i.e -K*np.sin(K*pv_za_temp) prints perfectly for the first
> looping. Also see the error that comes on the second looping. I'm clueless.
>
> 0
> K= 3.14159265359
> pv_za_temp = [ 0.   0.5  1.   1.5  2. ]
> - t*K*np.sin(K*p_initial) =  [ 0.  0. -0. -0.  0.]
> *-K*np.sin(K*pv_za_temp) =  [ -0.00000000e+00  -3.14159265e+00
> 6.49753967e-13   3.14159265e+00*
> *  -1.29950793e-12] PRINTS PERFECTLY*
> *
> *
> 0.1
> K= 3.14159265359
> pv_za_temp = [array([[ -0.00000000e+00,  -3.14159265e+00,   6.49753967e-13,
>           3.14159265e+00,  -1.29950793e-12]])]
> - t*K*np.sin(K*p_initial) =  [ -0.00000000e+00  -3.14159265e-01
> 6.49753967e-14   3.14159265e-01
>   -1.29950793e-13]
> -K*np.sin(K*pv_za_temp) = *ERROR*
> Traceback (most recent call last):
>   File "ZA.py", line 45, in <module>
>     print '-K*np.sin(K*pv_za_temp) = ',-K*np.sin(K*pv_za_temp)
> *TypeError: can't multiply sequence by non-int of type 'float'*
>
> Please Help!!!!
>
>
> Cheers,
> Sayan
>
>
> --
>
>
> --------------------------------------------------------------------------
> *Sayan  Chatterjee*
> Dept. of Physics and Meteorology
> IIT Kharagpur
> Lal Bahadur Shastry Hall of Residence
> Room AB 205
> Mob: +91 9874513565
> blog: www.blissprofound.blogspot.com
>
> Volunteer , Padakshep
> www.padakshep.org
>



-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130404/8e20a916/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: ZA.py
Type: application/octet-stream
Size: 2068 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20130404/8e20a916/attachment.obj>

From talk-noreply at google.com  Thu Apr  4 15:54:27 2013
From: talk-noreply at google.com (Google Talk)
Date: Thu, 4 Apr 2013 06:54:27 -0700
Subject: [Tutor] Invitation to use Google Talk
Message-ID: <CAAT-4OQw4noNKsoW8d0E=-L6rPG_mYU1j+YCTbOa4WprUjQ8Ow@mail.gmail.com>

-----------------------------------------------------------------------

You've been invited by Sayan Chatterjee to use Google Talk.

If you already have a Google account, log in to Gmail and accept this
chat invitation:
http://mail.google.com/mail/b-8dcd51705-090ef095ef-tIz_r28PffY3z4wTZmz--hUlRBY

To sign up for a Google account and get started with Google Talk, you can visit:
http://mail.google.com/mail/a-8dcd51705-090ef095ef-tIz_r28PffY3z4wTZmz--hUlRBY?pc=en_gb-rf---a

Learn more at:
http://www.google.com/intl/en/landing/accounts/


Thanks,
The Google Team

From bodsda at googlemail.com  Thu Apr  4 16:04:46 2013
From: bodsda at googlemail.com (Bod Soutar)
Date: Thu, 4 Apr 2013 15:04:46 +0100
Subject: [Tutor] Help required
In-Reply-To: <OF7271B190.E279D323-ON65257B34.0021B8C4-65257B34.002222D9@tcs.com>
References: <OF7271B190.E279D323-ON65257B34.0021B8C4-65257B34.002222D9@tcs.com>
Message-ID: <CAG6Bxkc4bwmxrAiibHeDsS1UokaC4RsNJyEL8Wa5VozK==aOZQ@mail.gmail.com>

On 20 March 2013 06:12, Arijit Ukil <arijit.ukil at tcs.com> wrote:
> I am new to python. My intention is to read the file digi.txt and store in
> separate arrays all the values of each columns. However, the following
> program prints only the last value, i.e. 1350696500.0.
> Please help to rectify this.
>
> f = open ("digi.txt", "r+")
>
> datafile = f.readlines()
>
> list_of_lists = datafile
> for data in list_of_lists:
>     lstval = data.split (',')
>     timest = float(lstval[0])
>     energy = float(lstval[1])
>
> f.close()
> print timest
>
A few questions to ask yourself.

Is 'f' a descriptive name, equivalent to your other variable names?
What does your third line do, and do you think it's actually required?
What implications would it cause if you removed it?
How do you overcome those issues?
What value is stored in 'timest' the first iteration of the loop, the
second, the third? (Put a print statement in the loop to find out)
Are you actually doing anything with 'energy'?
Do you need to wait until after the loop to close your file?

HTH,
Bodsda

From oscar.j.benjamin at gmail.com  Thu Apr  4 16:30:26 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Thu, 4 Apr 2013 15:30:26 +0100
Subject: [Tutor] TypeError: can't multiply sequence by non-int of type
	'float'
In-Reply-To: <CAAT-4ORd5aedzszZHOOBd94Np98+ZE+61oVQeoGMz8=DQdHuWw@mail.gmail.com>
References: <CAAT-4ORd5aedzszZHOOBd94Np98+ZE+61oVQeoGMz8=DQdHuWw@mail.gmail.com>
Message-ID: <CAHVvXxTHWXjcCMRVCcc3eRfBGLfaYKGAFig+eSGObRGJZOr_XA@mail.gmail.com>

On 4 April 2013 14:40, Sayan Chatterjee <sayanchatterjee at gmail.com> wrote:
> Dear All,
>
> I know this error occurs when one tries to multiply a string with a fraction
> i.e float. In my case , I can't figure out how can a numpy floating point
> array be a string.  Interestingly, the concerned expression gets printed in
> the loop for the first time but on the second go it fails.
>
> The concerned snippet of code is given below :
>
> for t in t_range(0,1,0.1):
>   print t
>   p_za=[]
>   pv_za=[]
>
>   # Opening file in file_t format
>   fname = 'file_' + str(t) + '.dat'
>   fo = open(fname,'w')
>
>   # p_za.append(p_initial - t*K*np.sin(K*p_initial))
>   print 'K=',K

K is somewhere above set to a float with the value 3.14...

>   print 'pv_za_temp =',pv_za_temp

pv_za_temp is somewhere above set to a list containing an array as
it's only element.

>   print '- t*K*np.sin(K*p_initial) = ',- t*K*np.sin(K*p_initial)
>   print '-K*np.sin(K*pv_za_temp) = ',-K*np.sin(K*pv_za_temp)

Here you try to multiply the two. The error can be achieved like so:

>>> import numpy
>>> a = numpy.array([[1, 2], [3, 4]])
>>> a
array([[1, 2],
       [3, 4]])
>>> 3.14 * a
array([[  3.14,   6.28],
       [  9.42,  12.56]])
>>> 3.14 * [a]

Perhaps what you want is to multiply K with pv_za_temp[0]?

[SNIP]
> K= 3.14159265359
> pv_za_temp = [array([[ -0.00000000e+00,  -3.14159265e+00,   6.49753967e-13,
>           3.14159265e+00,  -1.29950793e-12]])]


Oscar

From andipersti at gmail.com  Thu Apr  4 16:42:39 2013
From: andipersti at gmail.com (Andreas Perstinger)
Date: Thu, 4 Apr 2013 16:42:39 +0200
Subject: [Tutor] TypeError: can't multiply sequence by non-int of type
 'float'
In-Reply-To: <CAAT-4ORd5aedzszZHOOBd94Np98+ZE+61oVQeoGMz8=DQdHuWw@mail.gmail.com>
References: <CAAT-4ORd5aedzszZHOOBd94Np98+ZE+61oVQeoGMz8=DQdHuWw@mail.gmail.com>
Message-ID: <20130404164239.fe2fdc5db4da7503ff9a1de8@gmail.com>

Sayan Chatterjee <sayanchatterjee at gmail.com> wrote:

>I know this error occurs when one tries to multiply a string with a
>fraction i.e float. In my case , I can't figure out how can a numpy
>floating point array be a string.

The problem is not that the numpy array is a string but that you append
the array to a python list:

>  pv_za=[]
>  pv_za.append(-K*np.sin(K*pv_za_temp))
>  pv_za_temp = []
>  pv_za_temp.append(np.array(pv_za))

Both "pv_za" and "pv_za_temp" are python lists to which you append a
numpy array. But since you delete both lists in each iteration I assume
you want to just assign a new numpy array to both names:

pv_za = -K * np.sin(K * pv_za_temp)
pv_za_temp = pv_za # "pv_za" is already a numpy array

Bye, Andreas

From davea at davea.name  Thu Apr  4 16:55:38 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 04 Apr 2013 10:55:38 -0400
Subject: [Tutor] The game of nim in python
In-Reply-To: <DUB101-W21B80DA1016D14E43EA4EE9D10@phx.gbl>
References: <DUB101-W21B80DA1016D14E43EA4EE9D10@phx.gbl>
Message-ID: <515D946A.90705@davea.name>

On 03/27/2013 08:30 AM, Yasin El Guennouni wrote:
>
> Hello,
>
> I am trying to modify a game of nim code. The game in the code works as:
> "You need to remove from 1 to 3 straws from the pile.
> The player that removes the final straw is the loser."
>
> But I would like it to be like the classic game, where you have 4 piles containing 1,3,5 and 7 sticks
> where the drawer of the last stick is the winner. It would be awsome if I could print how
> many sticks there are left in each pile, e.g. : I III IIIII IIIIIII.
>

In my opinion, you'd have to modify so much that you'd probably be 
better off starting from scratch.



-- 
DaveA

From breamoreboy at yahoo.co.uk  Thu Apr  4 18:00:47 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Thu, 04 Apr 2013 17:00:47 +0100
Subject: [Tutor] Help required
In-Reply-To: <OF7271B190.E279D323-ON65257B34.0021B8C4-65257B34.002222D9@tcs.com>
References: <OF7271B190.E279D323-ON65257B34.0021B8C4-65257B34.002222D9@tcs.com>
Message-ID: <kjk80v$7u4$1@ger.gmane.org>

First up please give a sensible subject, say "problem parsing csv file".

I'm assuming the crud shown below is due to you posting in html, please 
use plain text instead.

On 20/03/2013 06:12, Arijit Ukil wrote:
> I am new to python. My intention is to read the file digi.txt and store
> in separate arrays all the values of each columns. However, the
> following program prints only the last value, i.e. 1350696500.0.
> Please help to rectify this.
>
> f = open (/"digi.txt"/, /"r+"/)

You might like to use the with statement as it saves the explicit close 
later.  Do you really need update mode?  I'll assume not.

with open('digi.txt', 'r') as f:

>
> datafile = f.readlines()

datafile is a poor name, it's the contents of the file here not the file 
itself.

>
> list_of_lists = datafile

This gives another name for datafile which you only use in the for loop, 
you can use datafile directly.

> fordata inlist_of_lists:
>      lstval = data.split (/','/)

The csv module from the standard library can look after this for you.

>      timest = float(lstval[0])
>      energy = float(lstval[1])

You do nothing with timest and energy within the for loop.

>
> f.close()
> printtimest

You're printing the last value for timest here.

So you need something like the following, I'll leave you to look up the 
csv module if you're interested.

with open('digi.txt', 'r') as f:
     lines = f.readlines()
     timestamps = []
     energies = []
     for line in lines:
         splits = line.split(',') # I'll admit not the best name
         timestamps.append(float(splits[0]))
         energies.append(float(splits[1]))

     # process timestamps and energies to your heart's content

>
> Regards,
> Arijit Ukil

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From doark at mail.com  Thu Apr  4 19:01:45 2013
From: doark at mail.com (frank ernest)
Date: Thu, 04 Apr 2013 13:01:45 -0400
Subject: [Tutor] Proper uses of classes
Message-ID: <20130404170145.327670@gmx.com>

Sorry about the indentation guys my mail service atomatically removed it when I pasted the text (I tried to fix it by hand but it was hard to tell if I was sucessful.)
I was tring to create a list object (self) and change it using the list methods and some additional ones I will define in my class.
I wanted to create some varibles which I pass to most if not all of my methods. Two of my variables are to be passed to the class apon creation of the object and then they in turn are to be passed to all or most of the methods I create (a, b in this case.) If I make a, b nonlocal I get the message that they are already nonlocal.
I will need for debuging purposes to print my object in random places in my class.
If I did this:
> self.a = aWhat would that create (I'm thinking local variable?)?

class alist(): def __init__(self, b, a): self.mylist = list() self.mylist.append(b) self.a = a + b def appendit(self): #I need to get a in hear without passing  #it in; it must come from the init method. self.mylist.append(self.a) #(I hope I've updated the code well, I can't test it from this computer.)PS: This is not the real code that I'm Emailing: I thought I'd be better off with some simpler code that produces the same errors.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130404/da96592b/attachment.html>

From kushal.kumaran+python at gmail.com  Thu Apr  4 19:11:14 2013
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Thu, 04 Apr 2013 22:41:14 +0530
Subject: [Tutor] os.system() with imbeded quotes
In-Reply-To: <CAK7xEK9zA6pyn=35OAZJhooRVjpofAM_iARcatVk7nVXHDBePA@mail.gmail.com>
References: <CAK7xEK9zA6pyn=35OAZJhooRVjpofAM_iARcatVk7nVXHDBePA@mail.gmail.com>
Message-ID: <515db43e.06dd440a.60f5.0e66@mx.google.com>

cevyn e <cevyne at gmail.com> writes:

> I get the example os.system('ls -al')     no problem.
>
> i'm trying to create a variable with my command built but needs to include
> quotes.
> Portion of code is as follows:
> someip = '192.168.01.01'
>
> var1 = 'lynx -dump http://' + someip +
> '/cgi-bin/xxxx.log&.submit=+++Go%21+++  > junk'
>
> print  var1
>
> os.system(var1)
>
>
> If I print var1 it looks right .  If I use the os.system(var1) as above it
> seems to have a problem near the end of the string with msg
> sh: .submit=+++Go%21+++: command not found
>
> clearly there is some escape sequence that I don't understand .
>
> I tried combinations of single and double quotes and mixed around var1, but
> that generates command not found.
>
> I need it to look like how I enter it manually and works
> lynx -dump 'http://192.168.01.01/cgi-bin/xxxx.log&.submit=+++Go%21+++  >
> junk'
>
> Probably obvious to many but i'm spinning my wheels.  many thanks for help .

There's a pipes.quote function (in python2, available as shlex.quote in
python3.3) that you can use in these circumstances.  Your problem is
because os.system passes the command to a shell, and the '&' character
in your argument terminates the command line.

Here's a transcript that shows the use of pipes.quote:

In [1]: import os

In [2]: os.system('echo a&b')
sh: 1: b: not found
a
Out[2]: 32512

In [5]: os.system('echo %s' % (pipes.quote('a&b'),))
a&b
Out[5]: 0

You should be able to get the effect you want by doing this:

cmd = 'lynx -dump %s > junk' % (pipes.quote(url),)

That said, you should take a look at the subprocess module.  The
functions in that module can invoke commands without invoking a shell,
which avoids such problems.

Untested example:

with open('junk', 'wb') as output_stream:
    p = subprocess.Popen(['lynx', '-dump', url], stdout=output_stream)
    p.communicate()

In this case, no quoting of the "url" argument is required.

Finally, you can also look at higher level ways of doing whatever it is
you're trying.  See the urllib2 standard module (assuming python2
because of your print statement), or the requests module
(http://docs.python-requests.org/en/v1.1.0/) which provide facilities to
access different kinds of urls with varying degrees of automation.

-- 
regards,
kushal

From bessenkphilip at gmail.com  Thu Apr  4 23:51:09 2013
From: bessenkphilip at gmail.com (bessenkphilip)
Date: Fri, 05 Apr 2013 03:21:09 +0530
Subject: [Tutor] Doubt in for loop
In-Reply-To: <515CEB1B.30004@davea.name>
References: <515CD75E.3030306@gmail.com> <515CDD25.8050208@pearwood.info>
	<515CEB1B.30004@davea.name>
Message-ID: <515DF5CD.9020209@gmail.com>

On 04/04/2013 08:23 AM, Dave Angel wrote:
> On 04/03/2013 09:53 PM, Steven D'Aprano wrote:
>> On 04/04/13 12:29, bessenkphilip wrote:
>>> Hi all,
>>>
>>> I'm having a doubt in the below program's 2n'd "for" loop.
>>>
>>>>>> for n in range(2, 10):
>>> ...     for x in range(2, n):
>>> ...         if n % x == 0:
>>> ...             print n, 'equals', x, '*', n/x
>>> ...             break
>>> ...     else:
>>> ...         # loop fell through without finding a factor
>>> ...         print n, 'is a prime number'
>>> ...
>>> 2 is a prime number
>>> 3 is a prime number
>>> 4 equals 2 * 2
>>> 5 is a prime number
>>> 6 equals 2 * 3
>>> 7 is a prime number
>>> 8 equals 2 * 4
>>> 9 equals 3 * 3
>>>
>>> My doubt is that "will 'x' be always of value 2, if so why that for
>>> loop "for x in range(2, n):"
>>> i don't know how the first output , as If 2%2==0:(this satisfies the
>>> if loop as x =2) , so how the else part came to output i.e 2 is a
>>> prime number.
>>
>> I'm sorry, I don't understand your question.
>>
>> x is *not* always of value 2. You can see with the last line,
>>
>> 9 equals 3 * 3
>>
>> x has value 3.
>>
>>
>> The outer loop just checks 2, 3, 4, ... 9 to see whether they are prime.
>> The inner loop actually does the checking:
>>
>>
>> for x in range(2, n):
>>      if n % x == 0:
>>          print n, 'equals', x, '*', n/x
>>          break
>>
>>
>> This tests whether n is divisible by 2, 3, 4, 5, 6, ... up to n-1. If n
>> is divisible by any of those numbers, then n cannot be prime.
>>
>> For example, with n = 9, the inner loop does this:
>>
>> x = 2
>> Test if 2 is a factor: does 9/2 have remainder zero? No.
>> x = 3
>> Test if 3 is a factor: does 9/3 have remainder zero? Yes.
>> So 9 is not prime, and 9 = 3 * (9/3) = 3 * 3
>>
>>
>> If we test it with n = 35, the inner loop would do this:
>>
>> x = 2
>> Test if 2 is a factor: does 35/2 have remainder zero? No.
>> x = 3
>> Test if 3 is a factor: does 35/3 have remainder zero? No.
>> x = 4
>> Test if 4 is a factor: does 35/4 have remainder zero? No.
>> x = 5
>> Test if 5 is a factor: does 35/5 have remainder zero? Yes.
>> So 35 is not prime, and 35 = 5 * (35/5) = 5 * 7
>>
>>
>>
>> Notice that this does more work than necessary! Can you see what work it
>> does that is unnecessary?
>>
>> (Hint: what even numbers are prime?)
>>
>>
>>
>>
>
> I don't understand the questions either, but I can point out one thing 
> that might be puzzling the OP:
>
> When n is 2, the inner loop does nothing, it just skips to the else 
> clause.  The reason is that range(2,2) is a null iterator. range(i,j) 
> produces values from i to j-1, or to put it another way values for which
>    i <= n < j
>
> If i and j are identical, there's nothing to match it.
>
>
Thank you  very much Steven for explaining this. Yes,Dave, i was having 
doubt how n=2 came to else part, cleared that too, thank you .


From breamoreboy at yahoo.co.uk  Fri Apr  5 10:48:37 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Fri, 05 Apr 2013 09:48:37 +0100
Subject: [Tutor] Proper uses of classes
In-Reply-To: <20130404170145.327670@gmx.com>
References: <20130404170145.327670@gmx.com>
Message-ID: <kjm30f$u4i$1@ger.gmane.org>

On 04/04/2013 18:01, frank ernest wrote:
> Sorry about the indentation guys my mail service atomatically removed it
> when I pasted the text (I tried to fix it by hand but it was hard to
> tell if I was sucessful.)
> I  was tring to create a list object (self) and change it using the list
> methods and some additional ones I will define in my class.
> I wanted to create some varibles which I pass to most if not all of my
> methods. Two of my variables are to be passed to the class apon creation
> of the object and then they in turn are to be passed to all or most of
> the methods I create (a, b in this case.) If I make a, b nonlocal I get
> the message that they are already nonlocal.
> I will need for debuging purposes to print my object in random places in
> my class.
> If I did this:
>
>>     self.a = a
>
> What would that create (I'm thinking local variable?)?

If the line is in a class method you'd create a (using Python speak) 
name 'a' for every instance of your class.

>
> class alist():
>     def __init__(self, b, a):
>         self.mylist = list()
>         self.mylist.append(b)
>         self.a = a + b
>     def appendit(self):
>
>         #I need to get a in hear without passing
>
>         #it in; it must come from the init method.
>         self.mylist.append(self.a)
>
>         #(I hope I've updated the code well, I can't test it from this computer.)
>
> PS: This is not the real code that I'm Emailing: I thought I'd be better off with some simpler code that produces the same errors.
>

As I see it all you gain from the appendit method is the ability to 
delay adding 'a' to mylist until you've done some other processing.  Is 
this what you're trying to achieve, if not can you give us more detail? 
  That way we can help you code up your requirements.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From davea at davea.name  Fri Apr  5 11:42:46 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 05 Apr 2013 05:42:46 -0400
Subject: [Tutor] Proper uses of classes
In-Reply-To: <20130404170145.327670@gmx.com>
References: <20130404170145.327670@gmx.com>
Message-ID: <515E9C96.4040308@davea.name>

On 04/04/2013 01:01 PM, frank ernest wrote:
> Sorry about the indentation guys my mail service atomatically removed it when I pasted the text (I tried to fix it by hand but it was hard to tell if I was sucessful.)
> I was tring to create a list object (self) and change it using the list methods and some additional ones I will define in my class.
> I wanted to create some varibles which I pass to most if not all of my methods. Two of my variables are to be passed to the class apon creation of the object and then they in turn are to be passed to all or most of the methods I create (a, b in this case.) If I make a, b nonlocal I get the message that they are already nonlocal.
> I will need for debuging purposes to print my object in random places in my class.
> If I did this:
>> self.a = aWhat would that create (I'm thinking local variable?)?

No.  a is a local variable, since it was passed as an argument.  self.a 
is an attribute of the alist instance.
>
> class alist(): def __init__(self, b, a): self.mylist = list() self.mylist.append(b) self.a = a + b def appendit(self): #I need to get a in hear without passing  #it in; it must come from the init method. self.mylist.append(self.a) #(I hope I've updated the code well, I can't test it from this computer.)PS: This is not the real code that I'm Emailing: I thought I'd be better off with some simpler code that produces the same errors.
>
>

Your mail service is just broken, at least for use here.  This is a text 
forum, and your mail has an empty text body.  So each of our mail 
readers has to try to reconstruct the text from html nonsense.  You can 
see the result above of what Thunderbird does.

The following is what I think you posted.

class alist():
    def __init__(self, b, a):
        self.mylist = list()
        self.mylist.append(b)
        self.a = a + b
    def appendit(self):

        #I need to get a in hear without passing

        #it in; it must come from the init method.
        self.mylist.append(self.a)

        #(I hope I've updated the code well, I can't test it from this 
computer.)

There are lots of terminology problems which will stop you from 
understanding what's going on.

"I wanted to create some varibles which I pass to most if not all of my 
methods"

"Variables" passed to methods are called arguments, or parameters, and 
that's NOT what you're trying to do.  You're trying to have the 
__init__() method "remember" those values.  When you write "self.a =" 
you are creating an "instance attribute" which is visible to all methods 
on that instance.  Other methods can access that instance attribute by 
referring to it as  self.a   Not by "global" not by "nonlocal".  Those 
are very different.  A local variable is also different, as is a class 
attribute.  You need to study up on each of these terms, and see what 
the differences are in terms of lifetime, visibility, duplication, etc. 
  More on that later.

Now, the appendit() method is nonsensical, but perhaps it was just a 
sample.  Each time it's called, it'll append the same value a to the list.

Perhaps you'd be more comfortable if you wrote a __str__() method.  That 
way, when you try to print an instance, it'll do what you say, rather 
than some default.  Typically, it should do something with each 
attribute that was initialized by __init__().  (untested)

     def __str__(self):
         res = "mylist attribute is" + str(self.mylist) + "\n"
         res += "a is " + str(a) + "\n"
         return res

Now you can exercise your class, and print out the results as often as 
you like:  (untested)

obj1 = alist(3, 47)   # creates an instance of alist
print(obj1)           # prints it
obj2 = alist(12, 9)   # creates a second instance of alist, with its own 
self.mylist and self.a,  different from those in obj1
print(obj2)

obj1.append()   #will take the particular list in obj1, and append the 
saved self.a value
print(obj1)

obj2.append()
obj2.append()
print(obj)


Now, a brief, informal summary of all the different kinds of 
"variables."  A global variable is defined at the outer scope of a 
module, and should mostly be constants, for sound engineering reasons. 
The global keyword, used only inside a function, declares that a 
particular variable that looks like it ought to be local, in fact is 
global.  The keyword applies only to that particular function.

A local variable is defined and used within a function (or method), and 
vanishes entirely when the function returns.  The formal parameters of 
the function are locals as well.

A class attribute belongs to the class, and there's only one of them, 
regardless of how many instances that class has.

An instance attribute exists separately in each instance of a class.  It 
should (my preference) be initialized in the __init__() method so that 
every instance has the same attributes, even if it's just
      self.att = None

A nonlocal variable is probably beyond what you need to know at the 
present, but it's one that's either global, or in some other function.

When you say   xxxx.yyyy   the meaning of that depends entirely on what 
  xxxx is defined as.  If xxxx is a class, then yyyy is an attribute of 
that class.  If xxxx is an instance, then yyyy might be an instance 
attribute (usually) or a class attribute (if no instance attribute by 
that name).  If xxxx is a module, then yyyy is a global in that other 
module.

The name self is a convention, but a very useful one there's no 
advantage in breaking.  Most methods take self as their first argument, 
and it refers to the object that method is called with.  In the specific 
case of __init__() method, that object is newly created.  In nearly all 
other cases, it's the object specified to the left of the method name, 
like  obj1.appendit()

There are a few other tricks that might matter, but this should get you 
going.  Play with all these concepts, and become attuned to it.  Only 
then should you try to do things like inherit from list.



-- 
DaveA

From mousumi251 at gmail.com  Fri Apr  5 12:47:54 2013
From: mousumi251 at gmail.com (Mousumi Basu)
Date: Fri, 5 Apr 2013 16:17:54 +0530
Subject: [Tutor] Socket Programming
Message-ID: <CACQ6Q4HXvCacP_1fS0-rSTq9iUt3Rw6zevEMQo+Jib5mptQ5Dg@mail.gmail.com>

I want to perform bind function for  socket programming between two
computers of ip addresses- 172.18.2.11 and 172.18.2.95 using the following
command(on the computer having IP address 172.18.2.95):

s=socket.socket(socket.AF_INIT,socket.SCK_DGRM))
s.bind(('172.18.2.11',8032))

But error is occurring showing "bind not done"

The ping operation of command prompt is showing that the computers are
connected.

Please help me.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130405/16dfa986/attachment.html>

From ausnajm at yahoo.com.au  Fri Apr  5 14:05:40 2013
From: ausnajm at yahoo.com.au (Najam Us Saqib)
Date: Fri, 5 Apr 2013 05:05:40 -0700 (PDT)
Subject: [Tutor] basic question
Message-ID: <1365163540.19153.YahooMailNeo@web161804.mail.bf1.yahoo.com>

Hi,

My name is Najam, I am very new to Python Programming. Would you please help me with the following question?

The question/problem is,

Write a Car salesman program where the user enters the base price of a car. The program should add a bunch of extra fees such as tax, license, dealer prep, and destination charge.Make tax and license a percent of the base price. The other fees should be set values. Display the actual price of the car once all the extras are applied.

I am not sure whether I have entered the right code for "Make tax and license a percent of the base price." or not.

My program is;

price = float(raw_input("Enter the base price of the car $ "))

tax = float(raw_input("Enter the tax $ "))
licence = float(raw_input("Enter the licence fees $ "))
dealer_prep = float(raw_input("Enter the dealer prep fees $ "))
des_charge = float(raw_input("Enter the destination charge $ "))

percent = (tax * 0.01 + licence * 0.01) / price ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # ?????

print "\nA percent of the base price is: $ " , percent

total = price + tax + licence + dealer_prep + des_charge

print "\nThe actual price of the car is: $ " , total

raw_input("\nPress Enter key to Exit, thank you.")



Thank you.
Najam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130405/59b820ca/attachment.html>

From davea at davea.name  Fri Apr  5 14:22:48 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 05 Apr 2013 08:22:48 -0400
Subject: [Tutor] basic question
In-Reply-To: <1365163540.19153.YahooMailNeo@web161804.mail.bf1.yahoo.com>
References: <1365163540.19153.YahooMailNeo@web161804.mail.bf1.yahoo.com>
Message-ID: <515EC218.8080800@davea.name>

On 04/05/2013 08:05 AM, Najam Us Saqib wrote:
> Hi,
>
> My name is Najam, I am very new to Python Programming.

Welcome.

>  Would you please help me with the following question?
>
> The question/problem is,
>
> Write a Car salesman program where the user enters the base price of a car. The program should add a bunch of extra fees such as tax, license, dealer prep, and destination charge.Make tax and license a percent of the base price. The other fees should be set values. Display the actual price of the car once all the extras are applied.
>

Is this exactly the way the assignment reads, or did you paraphrase it?

> I am not sure whether I have entered the right code for "Make tax and license a percent of the base price." or not.
>
> My program is;
>
> price = float(raw_input("Enter the base price of the car $ "))
>
> tax = float(raw_input("Enter the tax $ "))
> licence = float(raw_input("Enter the licence fees $ "))
> dealer_prep = float(raw_input("Enter the dealer prep fees $ "))
> des_charge = float(raw_input("Enter the destination charge $ "))
>
> percent = (tax * 0.01 + licence * 0.01) / price                                   # ?????
>
> print "\nA percent of the base price is: $ " , percent
>
> total = price + tax + licence + dealer_prep + des_charge
>
> print "\nThe actual price of the car is: $ " , total
>
> raw_input("\nPress Enter key to Exit, thank you.")
>
>

The way I expect the assignment was intended is that the user should 
enter (with raw_input) the tax and license as percentages, and you 
convert them to dollars, rather than the other way around.


-- 
DaveA

From woody544 at gmail.com  Fri Apr  5 14:34:53 2013
From: woody544 at gmail.com (Woody 544)
Date: Fri, 5 Apr 2013 08:34:53 -0400
Subject: [Tutor] basic question
In-Reply-To: <CAPwGs2rAMaDo0n4tPPi1oVB0UfffhQnhWXaNJdop6gHyHM-d=w@mail.gmail.com>
References: <1365163540.19153.YahooMailNeo@web161804.mail.bf1.yahoo.com>
	<CAPwGs2rAMaDo0n4tPPi1oVB0UfffhQnhWXaNJdop6gHyHM-d=w@mail.gmail.com>
Message-ID: <CAPwGs2qRBadZeAM9vvZF5cW1WmSe4wOMppMRH=YdKV0j7fyM0A@mail.gmail.com>

On 4/5/13, Woody 544 <woody544 at gmail.com> wrote:
> Dear Najam
>
> The tax and license amounts should not need to be entered, as I would
> think the only variable is the base price, with tax and license
> calculated as their rate times the base price. For example, if the
> sales tax rate for the area is 6% for example:
>
> tax = price * 0.06
>
> Since the other fees are fixed, there is no need for raw input from
> the user on those either and the rates can be hard coded in.  If the
> tax rate = 6% and the license rate = 1% then:
>
> total = price + (price*.06) + (price * .01) + dealer_prep + des_charge
>
> Thus the only input from the user would be to enter the base price.
> Of course, if the intent is for more than just one dealership with
> varied rates and fees, it may make sense for the other values to be
> entered by a user.
>
> MJ
>
> On 4/5/13, Najam Us Saqib <ausnajm at yahoo.com.au> wrote:
>> Hi,
>>
>> My name is Najam, I am very new to Python Programming. Would you please
>> help
>> me with the following question?
>>
>> The question/problem is,
>>
>> Write a Car salesman program where the user enters the base price of a
>> car.
>> The program should add a bunch of extra fees such as tax, license, dealer
>> prep, and destination charge.Make tax and license a percent of the base
>> price. The other fees should be set values. Display the actual price of
>> the
>> car once all the extras are applied.
>>
>> I am not sure whether I have entered the right code for "Make tax and
>> license a percent of the base price." or not.
>>
>> My program is;
>>
>> price = float(raw_input("Enter the base price of the car $ "))
>>
>> tax = float(raw_input("Enter the tax $ "))
>> licence = float(raw_input("Enter the licence fees $ "))
>> dealer_prep = float(raw_input("Enter the dealer prep fees $ "))
>> des_charge = float(raw_input("Enter the destination charge $ "))
>>
>> percent = (tax * 0.01 + licence * 0.01) / price
>>       # ?????
>>
>> print "\nA percent of the base price is: $ " , percent
>>
>> total = price + tax + licence + dealer_prep + des_charge
>>
>> print "\nThe actual price of the car is: $ " , total
>>
>> raw_input("\nPress Enter key to Exit, thank you.")
>>
>>
>>
>> Thank you.
>> Najam.
>>
>

From steve at pearwood.info  Fri Apr  5 15:28:12 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 06 Apr 2013 00:28:12 +1100
Subject: [Tutor] Socket Programming
In-Reply-To: <CACQ6Q4HXvCacP_1fS0-rSTq9iUt3Rw6zevEMQo+Jib5mptQ5Dg@mail.gmail.com>
References: <CACQ6Q4HXvCacP_1fS0-rSTq9iUt3Rw6zevEMQo+Jib5mptQ5Dg@mail.gmail.com>
Message-ID: <515ED16C.6070207@pearwood.info>

On 05/04/13 21:47, Mousumi Basu wrote:
> I want to perform bind function for  socket programming between two
> computers of ip addresses- 172.18.2.11 and 172.18.2.95 using the following
> command(on the computer having IP address 172.18.2.95):
>
> s=socket.socket(socket.AF_INIT,socket.SCK_DGRM))


I get THREE errors with that line:

* SyntaxError due to an extra closing parenthesis;

* after fixing that problem, I get an AttributeError:
   'module' object has no attribute 'AF_INIT'

* after guessing what you mean instead of AF_INIT, I get another AttributeError:
   'module' object has no attribute 'SCK_DGRM'


Could you show us the code you are actually using, and save us from having to guess?


> s.bind(('172.18.2.11',8032))
>
> But error is occurring showing "bind not done"

Please copy and paste the complete traceback, starting with the line:


Traceback (most recent call last)


and going all the way to the end of the error message.





-- 
Steven

From cfuller084 at thinkingplanet.net  Fri Apr  5 18:29:46 2013
From: cfuller084 at thinkingplanet.net (Chris Fuller)
Date: Fri, 5 Apr 2013 11:29:46 -0500
Subject: [Tutor] Socket Programming
In-Reply-To: <CACQ6Q4HXvCacP_1fS0-rSTq9iUt3Rw6zevEMQo+Jib5mptQ5Dg@mail.gmail.com>
References: <CACQ6Q4HXvCacP_1fS0-rSTq9iUt3Rw6zevEMQo+Jib5mptQ5Dg@mail.gmail.com>
Message-ID: <201304051129.47021.cfuller084@thinkingplanet.net>


Have you checked out the socket HOWTO?
http://docs.python.org/2/howto/sockets.html

Cheers

On Friday, April 05, 2013, Mousumi Basu wrote:
> I want to perform bind function for  socket programming between two
> computers of ip addresses- 172.18.2.11 and 172.18.2.95 using the following
> command(on the computer having IP address 172.18.2.95):
> 
> s=socket.socket(socket.AF_INIT,socket.SCK_DGRM))
> s.bind(('172.18.2.11',8032))
> 
> But error is occurring showing "bind not done"
> 
> The ping operation of command prompt is showing that the computers are
> connected.
> 
> Please help me.


From sayanchatterjee at gmail.com  Fri Apr  5 21:06:55 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Sat, 6 Apr 2013 00:36:55 +0530
Subject: [Tutor] TypeError: can't multiply sequence by non-int of type
	'float'
In-Reply-To: <20130404164239.fe2fdc5db4da7503ff9a1de8@gmail.com>
References: <CAAT-4ORd5aedzszZHOOBd94Np98+ZE+61oVQeoGMz8=DQdHuWw@mail.gmail.com>
	<20130404164239.fe2fdc5db4da7503ff9a1de8@gmail.com>
Message-ID: <CAAT-4OTvA4219Zg1Z1Rv0Y6SJ2vwMf82ifUhWtUxV8hdGHqi4A@mail.gmail.com>

Thanks all...I realized my mistake!!...:)


On 4 April 2013 20:12, Andreas Perstinger <andipersti at gmail.com> wrote:

> Sayan Chatterjee <sayanchatterjee at gmail.com> wrote:
>
> >I know this error occurs when one tries to multiply a string with a
> >fraction i.e float. In my case , I can't figure out how can a numpy
> >floating point array be a string.
>
> The problem is not that the numpy array is a string but that you append
> the array to a python list:
>
> >  pv_za=[]
> >  pv_za.append(-K*np.sin(K*pv_za_temp))
> >  pv_za_temp = []
> >  pv_za_temp.append(np.array(pv_za))
>
> Both "pv_za" and "pv_za_temp" are python lists to which you append a
> numpy array. But since you delete both lists in each iteration I assume
> you want to just assign a new numpy array to both names:
>
> pv_za = -K * np.sin(K * pv_za_temp)
> pv_za_temp = pv_za # "pv_za" is already a numpy array
>
> Bye, Andreas
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130406/b9cc1d3f/attachment.html>

From alan.gauld at btinternet.com  Sat Apr  6 20:22:28 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 06 Apr 2013 19:22:28 +0100
Subject: [Tutor] Socket Programming
In-Reply-To: <CACQ6Q4HXvCacP_1fS0-rSTq9iUt3Rw6zevEMQo+Jib5mptQ5Dg@mail.gmail.com>
References: <CACQ6Q4HXvCacP_1fS0-rSTq9iUt3Rw6zevEMQo+Jib5mptQ5Dg@mail.gmail.com>
Message-ID: <kjpp50$eiu$1@ger.gmane.org>

On 05/04/13 11:47, Mousumi Basu wrote:

>
> s=socket.socket(socket.AF_INIT,socket.SCK_DGRM))

There is a double )) at the end of the line.
That should give a different error so I assume this is
not cut 'n paste code, but just in case I thought
I'd point it out...

> s.bind(('172.18.2.11',8032))

Because I can't see anything wrong here.

> But error is occurring showing "bind not done"

Can you send the full error text via cut 'n paste please?

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


From ysoliman at uncc.edu  Sun Apr  7 00:00:01 2013
From: ysoliman at uncc.edu (Soliman, Yasmin)
Date: Sat, 6 Apr 2013 22:00:01 +0000
Subject: [Tutor] loop questions
Message-ID: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com>

I have two questions on these simple programs:

1st why does this loop keep repeating after I enter 'Quit'?

import calendar
m = raw_input(?Enter a year: ?)
while m != ?Quit?:
 if calendar.isleap(int(m)):
  print ?%d is a leap year? % (int(m))
 else:
  print ?%d is not a leap year? % (int(m)) 


2nd  How can I make this program not crash when a user enters a non integer?

m = raw_input(?Enter an integer: ?)
while not m.isdigit():
 m = raw_input(?Enter an integer: ?)
 num = int(m)

From msirenef at lightbird.net  Sun Apr  7 00:23:05 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Sat, 06 Apr 2013 18:23:05 -0400
Subject: [Tutor] loop questions
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <5160A049.5040205@lightbird.net>

On 04/06/2013 06:00 PM, Soliman, Yasmin wrote:
> I have two questions on these  simple programs:
 >
 > 1st why does this loop keep repeating after I enter 'Quit'?
 >
 > import calendar
 > m = raw_input(?Enter a year: ?)
 > while m != ?Quit?:
 >  if calendar.isleap(int(m)):
 >   print ?%d is a leap year? % (int(m))
 >  else:
 >   print ?%d is not a leap year? % (int(m))
 >
 >
 > 2nd  How can I make this program not crash when a user enters a non 
integer?
 >
 > m = raw_input(?Enter an integer: ?)
 > while not m.isdigit():
 >  m = raw_input(?Enter an integer: ?)
 >  num = int(m)
 > _______________________________________________
 > Tutor maillist  -  Tutor at python.org
 > To unsubscribe or change subscription options:
 > http://mail.python.org/mailman/listinfo/tutor
 >


In pseudocode, you need to do something like this:

- loop forever
     inp = user input
     if inp is Quit: break
     try to convert inp to int
     if success:
         print if inp is leap year or not
     else:
         print error


I have written a small function that handles a more general case of
asking user for a certain kind of input (e.g. number, text, yes/no, etc)
and keeps asking it until the answer in right format is given. Here it
is:

import re

def simpleinp(pattern, prompt="> ", convert=None, errmsg="Invalid 
Input", blank=False):
     """Keep asking user for input until it matches `pattern`."""
     if pattern == "%d": pattern = "\d+"; convert = int
     if pattern == "%s": pattern = ".+"

     while True:
         i = input(prompt).strip()
         if blank and not i: return None

         if re.match('^'+pattern+'$', i):
             return convert(i) if convert and i else i
         else:
             print(errmsg)

# print( simpleinp("%d", "integer: ") )
# print( simpleinp("%s", "string: ") )
# print( simpleinp(".*", "string or blank: ") )
# print( simpleinp("[ynYN]", "y/n: ") )


HTH, -m


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

True friends stab you in the front.
Oscar Wilde


From breamoreboy at yahoo.co.uk  Sun Apr  7 00:40:11 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 06 Apr 2013 23:40:11 +0100
Subject: [Tutor] loop questions
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <kjq84a$mgj$1@ger.gmane.org>

On 06/04/2013 23:00, Soliman, Yasmin wrote:
> I have two questions on these simple programs:
>
> 1st why does this loop keep repeating after I enter 'Quit'?
>
> import calendar
> m = raw_input(?Enter a year: ?)
> while m != ?Quit?:
>   if calendar.isleap(int(m)):
>    print ?%d is a leap year? % (int(m))
>   else:
>    print ?%d is not a leap year? % (int(m))
>

Already answered by Mitya Sirenef.

>
> 2nd  How can I make this program not crash when a user enters a non integer?

The program doesn't crash, it raises an exception.

>
> m = raw_input(?Enter an integer: ?)
> while not m.isdigit():
>   m = raw_input(?Enter an integer: ?)
>   num = int(m)

try:
     num = int(m)
except ValueError:
     doSomething

I'll leave you to restructure the loop.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From ysoliman at uncc.edu  Sun Apr  7 01:10:29 2013
From: ysoliman at uncc.edu (Soliman, Yasmin)
Date: Sat, 6 Apr 2013 23:10:29 +0000
Subject: [Tutor] (no subject)
Message-ID: <211A029E048A2245A6E00BA02FEFF88A673AFF67@BL2PRD0310MB373.namprd03.prod.outlook.com>

How can I fix this loop so that it multiplies the two intergers and if user types in 'quit' for either number it stops? if not it keeps going.



def multiply_integers(int1,int2):
    print int1*int2

int1=float(input('Please enter 1st integer: '))
int2=float(input('Please enter 2nd integer: '))

while True:
            multiply_integers= int("int1, int2")
            print int1*int2

            if multiply_integers == 'Quit':
                        print '\nThank you for using this program! Bye.'
                        break
            else:
                        print 'Not quitting'
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130406/617b5dd9/attachment.html>

From steve at pearwood.info  Sun Apr  7 01:49:52 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 07 Apr 2013 09:49:52 +1000
Subject: [Tutor] loop questions
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <5160B4A0.2060809@pearwood.info>

On 07/04/13 08:00, Soliman, Yasmin wrote:
> I have two questions on these simple programs:
>
> 1st why does this loop keep repeating after I enter 'Quit'?

The code you give below is not valid Python code. Please copy and paste *actual* the code you use, do not retype it from memory. I know that it is not valid code because it uses fancy quotes ? ? which do not work in Python, instead of ordinary quotes (actually inch marks) " "


> import calendar
> m = raw_input(?Enter a year: ?)
> while m != ?Quit?:
>   if calendar.isleap(int(m)):
>    print ?%d is a leap year? % (int(m))
>   else:
>    print ?%d is not a leap year? % (int(m))


Fixing the above error, it is *not correct* that the loop repeats after entering "Quit". If you enter Quit, the loop will not run at all, not even once. If you enter something else, *anything* else include "quit" or "QUIT" or "Quit " (notice the space at the end), then it will loop forever.

The problem is that your code only asks for a year *once*. The raw_input is outside of the loop, so it only happens once. To get the opportunity to enter a year, or quit, more than once, it needs to be inside the loop.

Also, you should be more forgiving of user input. Instead of checking whether the user enters exactly CAPITAL Q lower u i t you should accept anything that looks like "quit". Use m.strip() to remove any accidental spaces at the beginning or end of the word, and m.lower() to convert to lowercase, then compare against "quit".

(remember that strings are *immutable*, and re-assign the result of the method calls to m)




> 2nd  How can I make this program not crash when a user enters a non integer?
>
> m = raw_input(?Enter an integer: ?)
> while not m.isdigit():
>   m = raw_input(?Enter an integer: ?)
>   num = int(m)


There are two ways. You can either catch the exception that happens, or avoid calling int. Here's the first way:


# This will work with negative numbers too.
response = raw_input("Enter an integer: ")
try:
     num = int(response)
except ValueError:
     print "%r is not an integer, please try again" % response


Here's the second way:


# This will not work with negative numbers.
response = raw_input("Enter an integer: ")
response = response.strip()  # get rid of any leading or trailing spaces
if response.isdigit():
     num = int(response)
else:
     print "%r is not an integer, please try again" % response



If you want these to repeat multiple times, you need to put them inside a loop.




-- 
Steven

From steve at pearwood.info  Sun Apr  7 02:02:44 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 07 Apr 2013 10:02:44 +1000
Subject: [Tutor] (no subject)
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF67@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A673AFF67@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <5160B7A4.2060406@pearwood.info>

On 07/04/13 09:10, Soliman, Yasmin wrote:
> How can I fix this loop so that it multiplies the two intergers and if user types in 'quit' for either number it stops? if not it keeps going.


How would you solve this problem in real life? Right down the steps you would do, as if you were explaining it to a child, or an idiot. Remember that computers are dumber than any child, so make the steps as simple as you can.

* Ask the user for a value
* if the first value is "Quit", then stop
* Ask the user for a second value
* If the second value is "Quit", then stop
* Convert the first value to an int (instead of a string)
* Convert the second value to an int (instead of a string)
* Multiply the two ints

Now put that into Python code. Get it working. If you have *specific* questions, please ask, but this question is so broad and general that you're basically asking us to do everything.

Once it works, then put it inside a loop.

The secret to programming is to break tasks up into smaller tasks, smaller and simpler, until they are so small and simple that even a computer can do them. Then put the pieces together, in the right order.


P.S. Please use a sensible subject line.


-- 
Steven

From breamoreboy at yahoo.co.uk  Sun Apr  7 02:57:23 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sun, 07 Apr 2013 01:57:23 +0100
Subject: [Tutor] (no subject)
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF67@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A673AFF67@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <kjqfv1$kq6$1@ger.gmane.org>

On 07/04/2013 00:10, Soliman, Yasmin wrote:

To quote John McEnroe "You cannot be serious".  Thankfully Steven 
D'Aprano has already given you a roadmap to follow.  I'll point out a 
few things that should assist.

> How can I fix this loop so that it multiplies the two intergers and if
> user types in 'quit' for either number it stops? if not it keeps going.
>
> def multiply_integers(int1,int2):
>      print int1*int2

multiply_integers will return None, the Python default.

>
> int1=float(input('Please enter 1st integer: '))
> int2=float(input('Please enter 2nd integer: '))

Are you trying to get integers from the input by calling float?  Or 
could that be interest?  Or what?  The print statement later on tells me 
you're using Python 2.x.  Therefore you should be using raw_input above 
and *NOT* input, the latter is highly dangerous.

>
>
> while True:
>              multiply_integers= int("int1, int2")

Having defined a function you now try to reassign its name, obviously 
not what you want.  But that won't work as the call to int will fail as 
you're passing a single string "int1, int2" to it.

>              print int1*int2

Why print this here when your function multiply_integers already does 
exactly that?

>
>              if multiply_integers == 'Quit':

You now try to compare your function to a string.  Or should 
multiply_integers be an int here?

>                          print '\nThank you for using this program! Bye.'
>                          break
>              else:
>                          print 'Not quitting'
>

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From ausnajm at yahoo.com.au  Sun Apr  7 05:23:57 2013
From: ausnajm at yahoo.com.au (Najam Us Saqib)
Date: Sat, 6 Apr 2013 20:23:57 -0700 (PDT)
Subject: [Tutor] While loop
Message-ID: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com>

Hi,

Would you please help me by explaining that why " 5 " is skipped and not printed in the following program?

Thank you.
Najam.

count = 0
while True:
? ? count += 1
? ? # end loop if count is greater than 10
? ? if count > 10:
? ? ? ? break # means "break out of the loop"
? ? # skip 5
? ? if count == 5:
? ? ? ? continue # means "Jump back to the top of the looop"
? ? print count

raw_input("\n\nPress the enter key to exit.")

Output:

1
2
3
4
6
7
8
9
10


Press the enter key to exit.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130406/0a6281d6/attachment.html>

From davea at davea.name  Sun Apr  7 06:09:42 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 07 Apr 2013 00:09:42 -0400
Subject: [Tutor] While loop
In-Reply-To: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com>
References: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com>
Message-ID: <5160F186.5070701@davea.name>

On 04/06/2013 11:23 PM, Najam Us Saqib wrote:
> Hi,
>
> Would you please help me by explaining that why " 5 " is skipped and not printed in the following program?
>

Seems to me the comments say it pretty well.  The continue statement 
causes execution to continue at the while statement, which has the 
effect of skipping the print.  Like Monopoly:  go directly to jail, do 
not pass go.


> Thank you.
> Najam.
>
> count = 0
> while True:
>      count += 1
>      # end loop if count is greater than 10
>      if count > 10:
>          break # means "break out of the loop"
>      # skip 5
>      if count == 5:
>          continue # means "Jump back to the top of the looop"
>      print count
>
> raw_input("\n\nPress the enter key to exit.")
>
> Output:
>
> 1
> 2
> 3
> 4
> 6
> 7
> 8
> 9
> 10
>
>
> Press the enter key to exit.

Incidentally, this looks like a transliteration of something written for 
some other language.  An experienced Python programmer would never write 
it this way.

I'd use something like (untested):

for count in xrange(11):
     if count != 5:
         print count

On the other hand, a course --teaching a C programmer to use Python-- 
might well use this as an early example, showing you later how much 
elegantly it can be done.


-- 
DaveA

From davea at davea.name  Sun Apr  7 06:10:09 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 07 Apr 2013 00:10:09 -0400
Subject: [Tutor] While loop
In-Reply-To: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com>
References: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com>
Message-ID: <5160F1A1.9060702@davea.name>

On 04/06/2013 11:23 PM, Najam Us Saqib wrote:
> Hi,
>
> Would you please help me by explaining that why " 5 " is skipped and not printed in the following program?
>

Seems to me the comments say it pretty well.  The continue statement 
causes execution to continue at the while statement, which has the 
effect of skipping the print.  Like Monopoly:  go directly to jail, do 
not pass go.


> Thank you.
> Najam.
>
> count = 0
> while True:
>      count += 1
>      # end loop if count is greater than 10
>      if count > 10:
>          break # means "break out of the loop"
>      # skip 5
>      if count == 5:
>          continue # means "Jump back to the top of the looop"
>      print count
>
> raw_input("\n\nPress the enter key to exit.")
>
> Output:
>
> 1
> 2
> 3
> 4
> 6
> 7
> 8
> 9
> 10
>
>
> Press the enter key to exit.

Incidentally, this looks like a transliteration of something written for 
some other language.  An experienced Python programmer would never write 
it this way.

I'd use something like (untested):

for count in xrange(11):
     if count != 5:
         print count

On the other hand, a course --teaching a C programmer to use Python-- 
might well use this as an early example, showing you later how much 
elegantly it can be done.


-- 
DaveA

From sayanchatterjee at gmail.com  Sun Apr  7 07:12:35 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Sun, 7 Apr 2013 10:42:35 +0530
Subject: [Tutor] While loop
In-Reply-To: <5160F1A1.9060702@davea.name>
References: <1365305037.70564.YahooMailNeo@web161805.mail.bf1.yahoo.com>
	<5160F1A1.9060702@davea.name>
Message-ID: <CAAT-4OR-Wz+7Z-B_6fT168F_Sk1s9wge+XnugSfQGtPijk0=sQ@mail.gmail.com>

# skip 5
    if count == 5:
        continue # means "Jump back to the top of the looop"

It is the reason. You yourself have mentioned it right inside the code!


On 7 April 2013 09:40, Dave Angel <davea at davea.name> wrote:

> On 04/06/2013 11:23 PM, Najam Us Saqib wrote:
>
>> Hi,
>>
>> Would you please help me by explaining that why " 5 " is skipped and not
>> printed in the following program?
>>
>>
> Seems to me the comments say it pretty well.  The continue statement
> causes execution to continue at the while statement, which has the effect
> of skipping the print.  Like Monopoly:  go directly to jail, do not pass go.
>
>
>  Thank you.
>> Najam.
>>
>> count = 0
>> while True:
>>      count += 1
>>      # end loop if count is greater than 10
>>      if count > 10:
>>          break # means "break out of the loop"
>>      # skip 5
>>      if count == 5:
>>          continue # means "Jump back to the top of the looop"
>>      print count
>>
>> raw_input("\n\nPress the enter key to exit.")
>>
>> Output:
>>
>> 1
>> 2
>> 3
>> 4
>> 6
>> 7
>> 8
>> 9
>> 10
>>
>>
>> Press the enter key to exit.
>>
>
> Incidentally, this looks like a transliteration of something written for
> some other language.  An experienced Python programmer would never write it
> this way.
>
> I'd use something like (untested):
>
> for count in xrange(11):
>     if count != 5:
>         print count
>
> On the other hand, a course --teaching a C programmer to use Python--
> might well use this as an early example, showing you later how much
> elegantly it can be done.
>
>
> --
> DaveA
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130407/e47d068e/attachment-0001.html>

From alan.gauld at btinternet.com  Sun Apr  7 10:24:10 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 07 Apr 2013 09:24:10 +0100
Subject: [Tutor] loop questions
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A673AFF4B@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <kjraf6$vqn$1@ger.gmane.org>

On 06/04/13 23:00, Soliman, Yasmin wrote:
> I have two questions on these simple programs:
>
> 1st why does this loop keep repeating after I enter 'Quit'?
>
> import calendar
> m = raw_input(?Enter a year: ?)
> while m != ?Quit?:
>   if calendar.isleap(int(m)):
>    print ?%d is a leap year? % (int(m))
>   else:
>    print ?%d is not a leap year? % (int(m))
>

I don't understand why it even starts repeating since
the only user input is before the loop. However you
need to enter exactly "Quit" and not QUIT or quit
or any other combination... It usually better to
force the user input to upper or lower case, eg:

while m.lower() != "quit":

> 2nd  How can I make this program not crash when a user enters a non integer?
>
> m = raw_input(?Enter an integer: ?)
> while not m.isdigit():
>   m = raw_input(?Enter an integer: ?)
>   num = int(m)

Moving the last line out of the loop will help.
But there are other things to check in addition to isdigit().
That's why Python tends towards exception handling rather
than pre-validation.

eg.

while True:
    try: m = int(raw_input(....))
    except ValueError,TypeError: continue

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


From chigga101 at gmail.com  Sun Apr  7 17:07:52 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 7 Apr 2013 16:07:52 +0100
Subject: [Tutor] urllib.urlretrieve ?
Message-ID: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>

Im following a tutorial on what i believe is using Python 2 and i'm a
bit confused. I use Python 3 on windows vista. I believe
urlretrieve() is a python 2 function that isnt in 3, but why is the
tutorial using urllib instead of urllib2? Also when i run the program
on Python 3, it says:

AttributeError: 'module' object has no attribute 'urlretrieve'

so Python 3 doesnt recognize this function, i want to ask if there is
an equivalent function to 'urlretrieve' in Python 3? the program uses
this function to download a file as so:

urllib.urlretrieve(self._url, self._filename, reporthook)

the 3rd argument is a function that is called to track progress of the
current download status. i dont really need help with the program, i
understand its code, but i need to know if this function has one
similar in Python 3? or do you have any examples of how i could add
its functionality to Python 3.

From eryksun at gmail.com  Sun Apr  7 17:16:22 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 7 Apr 2013 11:16:22 -0400
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
Message-ID: <CACL+1at=8=7voXJv9dzBMPt8VBhoFPq4FTXM7pecrsrXYpR4Dg@mail.gmail.com>

On Sun, Apr 7, 2013 at 11:07 AM, Matthew Ngaha <chigga101 at gmail.com> wrote:
> so Python 3 doesnt recognize this function, i want to ask if there is
> an equivalent function to 'urlretrieve' in Python 3?

The documentation is indexed:

http://docs.python.org/3/genindex-U.html

From alan.gauld at btinternet.com  Sun Apr  7 17:31:14 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 07 Apr 2013 16:31:14 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
Message-ID: <kjs3fu$ocg$1@ger.gmane.org>

On 07/04/13 16:07, Matthew Ngaha wrote:

> an equivalent function to 'urlretrieve' in Python 3? the program uses
> this function to download a file as so:
>
> urllib.urlretrieve(self._url, self._filename, reporthook)
>

Looking in the V3 documents on the Python web site it says:

==============
The following functions and classes are ported from the Python 2 module 
urllib (as opposed to urllib2). They might become deprecated at some 
point in the future.

urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None)

Copy a network object denoted by a URL to a local file...

===============

Look in the module docs for urlib.request.


HTH

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


From chigga101 at gmail.com  Sun Apr  7 17:32:04 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 7 Apr 2013 16:32:04 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <CACL+1at=8=7voXJv9dzBMPt8VBhoFPq4FTXM7pecrsrXYpR4Dg@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<CACL+1at=8=7voXJv9dzBMPt8VBhoFPq4FTXM7pecrsrXYpR4Dg@mail.gmail.com>
Message-ID: <CACzNyA2h8+BSH_27+yNny4ijDQJ-f6t9BRWh2gNh6ow51neGrw@mail.gmail.com>

the whole program depends on the urlretrieve 3rd argument, the
function to be called.. is there no options to include a callback?

def _download(self):

        def reporthook(pos, block, total):
            if self.size != total:
                self._size = total
                self.on_size.emit()
            self.progress = float(pos*block)/float(total)

        urllib.urlretrieve(self._url, self._filename, reporthook)
##3rd arg calls inner function
        self.running = False

From chigga101 at gmail.com  Sun Apr  7 18:20:50 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 7 Apr 2013 17:20:50 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <kjs3fu$ocg$1@ger.gmane.org>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<kjs3fu$ocg$1@ger.gmane.org>
Message-ID: <CACzNyA13URg45Qb9u_7Sj96146dnQzg60xuWWfbtqPuC3VmS-w@mail.gmail.com>

> Look in the module docs for urlib.request.
>

Hi. Ive never used the urllib before unless it was typing in something
from an unrelated tutorial. I've also never done anything related to
web programming. I'm looking at the urllib.request page and i really
don't understand what i'm looking at. I'm confused as to what i should
be looking for.

From joel.goldstick at gmail.com  Sun Apr  7 18:23:37 2013
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Sun, 7 Apr 2013 12:23:37 -0400
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <CACzNyA2h8+BSH_27+yNny4ijDQJ-f6t9BRWh2gNh6ow51neGrw@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<CACL+1at=8=7voXJv9dzBMPt8VBhoFPq4FTXM7pecrsrXYpR4Dg@mail.gmail.com>
	<CACzNyA2h8+BSH_27+yNny4ijDQJ-f6t9BRWh2gNh6ow51neGrw@mail.gmail.com>
Message-ID: <CAPM-O+x+3M4uZqCnO0Eq=sDfKNeg13Gmuv7-_HNsXbN4GgQDTg@mail.gmail.com>

On Sun, Apr 7, 2013 at 11:32 AM, Matthew Ngaha <chigga101 at gmail.com> wrote:

> the whole program depends on the urlretrieve 3rd argument, the
> function to be called.. is there no options to include a callback?
>
> def _download(self):
>
>         def reporthook(pos, block, total):
>             if self.size != total:
>                 self._size = total
>                 self.on_size.emit()
>             self.progress = float(pos*block)/float(total)
>
>         urllib.urlretrieve(self._url, self._filename, reporthook)
> ##3rd arg calls inner function
>         self.running = False
>

You might want to look at requests module:
http://docs.python-requests.org/en/latest/
Many people think it is easier to use than the native python support.


> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130407/bd74fcec/attachment.html>

From chigga101 at gmail.com  Sun Apr  7 18:58:33 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 7 Apr 2013 17:58:33 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <CAPM-O+x+3M4uZqCnO0Eq=sDfKNeg13Gmuv7-_HNsXbN4GgQDTg@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<CACL+1at=8=7voXJv9dzBMPt8VBhoFPq4FTXM7pecrsrXYpR4Dg@mail.gmail.com>
	<CACzNyA2h8+BSH_27+yNny4ijDQJ-f6t9BRWh2gNh6ow51neGrw@mail.gmail.com>
	<CAPM-O+x+3M4uZqCnO0Eq=sDfKNeg13Gmuv7-_HNsXbN4GgQDTg@mail.gmail.com>
Message-ID: <CACzNyA21cNxYW9xcAbaWJC2v+6G6X8_PU5nymVxoY9ygDxui=g@mail.gmail.com>

>
> You might want to look at requests module:
> http://docs.python-requests.org/en/latest/
> Many people think it is easier to use than the native python support.
>

are all of these modules related to web programming like clients and
(HTTP)servers? I've come across urllib a lot of times but only
followed along, maybe its best i just learn about HTTP and its
concepts etc so i can understand the request module better then come
back to my problem.. Thanks

From alan.gauld at btinternet.com  Sun Apr  7 20:10:06 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 07 Apr 2013 19:10:06 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <CACzNyA13URg45Qb9u_7Sj96146dnQzg60xuWWfbtqPuC3VmS-w@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<kjs3fu$ocg$1@ger.gmane.org>
	<CACzNyA13URg45Qb9u_7Sj96146dnQzg60xuWWfbtqPuC3VmS-w@mail.gmail.com>
Message-ID: <kjscpq$gk5$1@ger.gmane.org>

On 07/04/13 17:20, Matthew Ngaha wrote:
>> Look in the module docs for urlib.request.
>>
>
> Hi. Ive never used the urllib before

In Python 3 urllib combines (the best) features of
urllib and urllib2 from Python 2.

> web programming. I'm looking at the urllib.request page and i really
> don't understand what i'm looking at. I'm confused as to what i should
> be looking for.

You were asking about urllib.urlretrieve.
It's documented on that page.

Now, beyond that, what else are you confused about?
The more specific the question the more specific the answer.

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


From chigga101 at gmail.com  Sun Apr  7 20:49:58 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 7 Apr 2013 19:49:58 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <kjscpq$gk5$1@ger.gmane.org>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<kjs3fu$ocg$1@ger.gmane.org>
	<CACzNyA13URg45Qb9u_7Sj96146dnQzg60xuWWfbtqPuC3VmS-w@mail.gmail.com>
	<kjscpq$gk5$1@ger.gmane.org>
Message-ID: <CACzNyA0icv6o3uFQnxZNgQj4XWPgkPZbgCZRvRsjex5NK3TyzA@mail.gmail.com>

yeah, sadly urlretrieve doesnt exist on my version of python. i just
need a function to put in the same line that replaces this one with
the same arguments in order to see the results of my tutorial.

urllib.urlretrieve(self._url, self._filename, reporthook)

On Sun, Apr 7, 2013 at 7:10 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 07/04/13 17:20, Matthew Ngaha wrote:
>>>
>>> Look in the module docs for urlib.request.
>>>
>>
>> Hi. Ive never used the urllib before
>
>
> In Python 3 urllib combines (the best) features of
> urllib and urllib2 from Python 2.
>
>
>> web programming. I'm looking at the urllib.request page and i really
>> don't understand what i'm looking at. I'm confused as to what i should
>> be looking for.
>
>
> You were asking about urllib.urlretrieve.
> It's documented on that page.
>
> Now, beyond that, what else are you confused about?
> The more specific the question the more specific the answer.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

From breamoreboy at yahoo.co.uk  Sun Apr  7 21:09:23 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sun, 07 Apr 2013 20:09:23 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <CACzNyA0icv6o3uFQnxZNgQj4XWPgkPZbgCZRvRsjex5NK3TyzA@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<kjs3fu$ocg$1@ger.gmane.org>
	<CACzNyA13URg45Qb9u_7Sj96146dnQzg60xuWWfbtqPuC3VmS-w@mail.gmail.com>
	<kjscpq$gk5$1@ger.gmane.org>
	<CACzNyA0icv6o3uFQnxZNgQj4XWPgkPZbgCZRvRsjex5NK3TyzA@mail.gmail.com>
Message-ID: <kjsg7k$gjm$1@ger.gmane.org>

On 07/04/2013 19:49, Matthew Ngaha wrote:

Please don't top post.

> yeah, sadly urlretrieve doesnt exist on my version of python. i just
> need a function to put in the same line that replaces this one with
> the same arguments in order to see the results of my tutorial.
>
> urllib.urlretrieve(self._url, self._filename, reporthook)
>
> On Sun, Apr 7, 2013 at 7:10 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>> On 07/04/13 17:20, Matthew Ngaha wrote:
>>>>
>>>> Look in the module docs for urlib.request.
>>>>
>>>
>>> Hi. Ive never used the urllib before
>>
>> In Python 3 urllib combines (the best) features of
>> urllib and urllib2 from Python 2.
>>
>>> web programming. I'm looking at the urllib.request page and i really
>>> don't understand what i'm looking at. I'm confused as to what i should
>>> be looking for.
>>
>> You were asking about urllib.urlretrieve.
>> It's documented on that page.
>>
>> Now, beyond that, what else are you confused about?
>> The more specific the question the more specific the answer.
>>
>> --
>> Alan G
>> Author of the Learn to Program web site
>> http://www.alan-g.me.uk/
>>

See either 
http://docs.python.org/2/library/urllib.html#urllib.urlretrieve or
http://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve


-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From chigga101 at gmail.com  Sun Apr  7 21:59:53 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 7 Apr 2013 20:59:53 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <kjsg7k$gjm$1@ger.gmane.org>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<kjs3fu$ocg$1@ger.gmane.org>
	<CACzNyA13URg45Qb9u_7Sj96146dnQzg60xuWWfbtqPuC3VmS-w@mail.gmail.com>
	<kjscpq$gk5$1@ger.gmane.org>
	<CACzNyA0icv6o3uFQnxZNgQj4XWPgkPZbgCZRvRsjex5NK3TyzA@mail.gmail.com>
	<kjsg7k$gjm$1@ger.gmane.org>
Message-ID: <CACzNyA1uVm3tCTtMLgs_A5dsFb0CGJ=NabMpfWSEfTjh5r9gjw@mail.gmail.com>

>org/2/library/urllib.html#urllib.urlretrieve
> or
> http://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve
sorry about the top posting gmail has changed the way their messages
are done, it gave me a blank field i didnt realize i was writing above
the message.

i must have missed it but your 2nd link was exactly what i needed. ive
got the program to run without the module error. However i'm out of
luck as i now get this error:

urllib.error.HTTPError: HTTP Error 404: Not Found

i guess the tutorial is very old that the site doesnt exist anymore:(
Thanks for the help

From bodsda at googlemail.com  Sun Apr  7 23:14:51 2013
From: bodsda at googlemail.com (Bod Soutar)
Date: Sun, 7 Apr 2013 22:14:51 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <CACzNyA1uVm3tCTtMLgs_A5dsFb0CGJ=NabMpfWSEfTjh5r9gjw@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<kjs3fu$ocg$1@ger.gmane.org>
	<CACzNyA13URg45Qb9u_7Sj96146dnQzg60xuWWfbtqPuC3VmS-w@mail.gmail.com>
	<kjscpq$gk5$1@ger.gmane.org>
	<CACzNyA0icv6o3uFQnxZNgQj4XWPgkPZbgCZRvRsjex5NK3TyzA@mail.gmail.com>
	<kjsg7k$gjm$1@ger.gmane.org>
	<CACzNyA1uVm3tCTtMLgs_A5dsFb0CGJ=NabMpfWSEfTjh5r9gjw@mail.gmail.com>
Message-ID: <CAG6Bxkd+js+cCbqn59f0gV=7zM9-XY2X+N2a+Yxr=Q0OL4FB9g@mail.gmail.com>

On 7 April 2013 20:59, Matthew Ngaha <chigga101 at gmail.com> wrote:
>>org/2/library/urllib.html#urllib.urlretrieve
>> or
>> http://docs.python.org/3/library/urllib.request.html#urllib.request.urlretrieve
> sorry about the top posting gmail has changed the way their messages
> are done, it gave me a blank field i didnt realize i was writing above
> the message.
>
> i must have missed it but your 2nd link was exactly what i needed. ive
> got the program to run without the module error. However i'm out of
> luck as i now get this error:
>
> urllib.error.HTTPError: HTTP Error 404: Not Found
>
> i guess the tutorial is very old that the site doesnt exist anymore:(
> Thanks for the help

Unless you're looking for something specific from the URL that the
tutorial uses, then you could use any address

Bodsda

From chigga101 at gmail.com  Mon Apr  8 00:09:51 2013
From: chigga101 at gmail.com (Matthew Ngaha)
Date: Sun, 7 Apr 2013 23:09:51 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <CAG6Bxkd+js+cCbqn59f0gV=7zM9-XY2X+N2a+Yxr=Q0OL4FB9g@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<kjs3fu$ocg$1@ger.gmane.org>
	<CACzNyA13URg45Qb9u_7Sj96146dnQzg60xuWWfbtqPuC3VmS-w@mail.gmail.com>
	<kjscpq$gk5$1@ger.gmane.org>
	<CACzNyA0icv6o3uFQnxZNgQj4XWPgkPZbgCZRvRsjex5NK3TyzA@mail.gmail.com>
	<kjsg7k$gjm$1@ger.gmane.org>
	<CACzNyA1uVm3tCTtMLgs_A5dsFb0CGJ=NabMpfWSEfTjh5r9gjw@mail.gmail.com>
	<CAG6Bxkd+js+cCbqn59f0gV=7zM9-XY2X+N2a+Yxr=Q0OL4FB9g@mail.gmail.com>
Message-ID: <CACzNyA0bAFo30SEA7fAWCJMjAGw7woPy+gm_AmKSZm5=TjhUkQ@mail.gmail.com>

> Unless you're looking for something specific from the URL that the
> tutorial uses, then you could use any address
>
> Bodsda

thanks i did that and to my suprise an extra file showed up in my
folder, of the page i just visited:) thanks

From alan.gauld at btinternet.com  Mon Apr  8 00:13:13 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 07 Apr 2013 23:13:13 +0100
Subject: [Tutor] urllib.urlretrieve ?
In-Reply-To: <CACzNyA0icv6o3uFQnxZNgQj4XWPgkPZbgCZRvRsjex5NK3TyzA@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>
	<kjs3fu$ocg$1@ger.gmane.org>
	<CACzNyA13URg45Qb9u_7Sj96146dnQzg60xuWWfbtqPuC3VmS-w@mail.gmail.com>
	<kjscpq$gk5$1@ger.gmane.org>
	<CACzNyA0icv6o3uFQnxZNgQj4XWPgkPZbgCZRvRsjex5NK3TyzA@mail.gmail.com>
Message-ID: <kjsr1l$acm$1@ger.gmane.org>

On 07/04/13 19:49, Matthew Ngaha wrote:
> yeah, sadly urlretrieve doesnt exist on my version of python.

I just told you where to find it on Python 3.

It's just been moved that's all.


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


From mousumi251 at gmail.com  Mon Apr  8 09:06:19 2013
From: mousumi251 at gmail.com (Mousumi Basu)
Date: Mon, 8 Apr 2013 12:36:19 +0530
Subject: [Tutor] Socket Programming
Message-ID: <CACQ6Q4Ev5t617wcdv0e-_VEmQ5GEg0AQFM+Atnxp1fiLnOVKFg@mail.gmail.com>

I want to perform binding between two computers having ip addresses
172.18.2.11 and  172.18.2.95.So i wrote the following code(on the computer
having IP address 172.18.2.95):-


import socket
import sys
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
try:
    s=s.bind(('172.18.2.11',2213))
    print 'socket bind is complete'
except socket.error,msg:
    print 'bind failed'
    sys.exit()


The output is :-
bind failed


but when i am writting;-

s=s.bind(('localhost',2213))

the output is;-
socket bind is complete



Can you please tell me where i am making the error?
(The computers are connected as the ping operation is executing properly in
command prompt)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130408/6a39b3fd/attachment.html>

From timomlists at gmail.com  Mon Apr  8 11:19:41 2013
From: timomlists at gmail.com (Timo)
Date: Mon, 08 Apr 2013 11:19:41 +0200
Subject: [Tutor] Socket Programming
In-Reply-To: <CACQ6Q4Ev5t617wcdv0e-_VEmQ5GEg0AQFM+Atnxp1fiLnOVKFg@mail.gmail.com>
References: <CACQ6Q4Ev5t617wcdv0e-_VEmQ5GEg0AQFM+Atnxp1fiLnOVKFg@mail.gmail.com>
Message-ID: <51628BAD.7030909@gmail.com>

Op 08-04-13 09:06, Mousumi Basu schreef:
> I want to perform binding between two computers having ip addresses  
> 172.18.2.11 and 172.18.2.95.So <http://172.18.2.95.So> i wrote the 
> following code(on the computer having IP address 172.18.2.95):-
>
>
> import socket
> import sys
> s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
> try:
>     s=s.bind(('172.18.2.11',2213))
>     print 'socket bind is complete'
> except socket.error,msg:
>     print 'bind failed'
>     sys.exit()
You are hiding the error message here. Just print msg and see why it fails.

Timo

>
>
> The output is :-
> bind failed
>
>
> but when i am writting;-
>
> s=s.bind(('localhost',2213))
>
> the output is;-
> socket bind is complete
>
>
>
> Can you please tell me where i am making the error?
> (The computers are connected as the ping operation is executing 
> properly in command prompt)
>
>
>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From sibannac.ms at gmail.com  Mon Apr  8 12:21:57 2013
From: sibannac.ms at gmail.com (Max Smith)
Date: Mon, 8 Apr 2013 12:21:57 +0200
Subject: [Tutor] if statement problems(noob question)
Message-ID: <CANSMJux_Dr7zqqFQ0+A1s6uqm-3eedrADW+4n7Tv8cerWfbT=Q@mail.gmail.com>

Hi, everyone whom might read this, im Max and i am really new to coding,
been going at it for about two weeks using codeacademy and the book "think
python".
when i decided to experiment a little with if statements i ran into the
following problem:

def plus(x,y):
    if x and y == int or float:
        print "The answer is: " + str(x+y)

    else:
        print "not a number"


plus(2,2)
plus("one","two")

concatenates one and two insted of printing "not a number"

i have tried to simplify by not cheacking for float values an i have also
tried.

def plus(x,y):
    if x and y == int or float:
        print "The answer is: " + str(x+y)

    elif x or y != int or float:
        print "not a number"

Am i perhaps missing something with the logic gates?

Any help is greatly appreciated !
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130408/9862e576/attachment.html>

From woody544 at gmail.com  Mon Apr  8 12:37:41 2013
From: woody544 at gmail.com (Woody 544)
Date: Mon, 8 Apr 2013 06:37:41 -0400
Subject: [Tutor] if statement problems(noob question)
In-Reply-To: <CANSMJux_Dr7zqqFQ0+A1s6uqm-3eedrADW+4n7Tv8cerWfbT=Q@mail.gmail.com>
References: <CANSMJux_Dr7zqqFQ0+A1s6uqm-3eedrADW+4n7Tv8cerWfbT=Q@mail.gmail.com>
Message-ID: <CAPwGs2ruiHJ6XaUdtmGeE-MvWSVhVW+Q4aJwgPiOK-x4mDieYg@mail.gmail.com>

Max,

You've made the arguments a string (so never a number) in:

print "The answer is: " + str(x+y)

MJ
On Apr 8, 2013 6:23 AM, "Max Smith" <sibannac.ms at gmail.com> wrote:

> Hi, everyone whom might read this, im Max and i am really new to coding,
> been going at it for about two weeks using codeacademy and the book "think
> python".
> when i decided to experiment a little with if statements i ran into the
> following problem:
>
> def plus(x,y):
>     if x and y == int or float:
>         print "The answer is: " + str(x+y)
>
>     else:
>         print "not a number"
>
>
> plus(2,2)
> plus("one","two")
>
> concatenates one and two insted of printing "not a number"
>
> i have tried to simplify by not cheacking for float values an i have also
> tried.
>
> def plus(x,y):
>     if x and y == int or float:
>         print "The answer is: " + str(x+y)
>
>     elif x or y != int or float:
>         print "not a number"
>
> Am i perhaps missing something with the logic gates?
>
> Any help is greatly appreciated !
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130408/456af2ba/attachment.html>

From davea at davea.name  Mon Apr  8 12:45:59 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 08 Apr 2013 06:45:59 -0400
Subject: [Tutor] if statement problems(noob question)
In-Reply-To: <CANSMJux_Dr7zqqFQ0+A1s6uqm-3eedrADW+4n7Tv8cerWfbT=Q@mail.gmail.com>
References: <CANSMJux_Dr7zqqFQ0+A1s6uqm-3eedrADW+4n7Tv8cerWfbT=Q@mail.gmail.com>
Message-ID: <51629FE7.2030809@davea.name>

On 04/08/2013 06:21 AM, Max Smith wrote:
> Hi, everyone whom might read this, im Max and i am really new to coding,
> been going at it for about two weeks using codeacademy and the book "think
> python".
> when i decided to experiment a little with if statements i ran into the
> following problem:
>
> def plus(x,y):
>      if x and y == int or float:

What is it you expect this to do?  Have you tried a similar, simpler 
expression to get acquainted?
     x = 2
     if x == int:

will always fail, since the integer 2 is not equal to the type int.  In 
Python 2.x, when you compare objects of different types, you generally 
get unequal.  (Exception, if you define your own classes, you can define 
how they compare to others)  In Python 3, you'd get an exception.

The way you should test an object to see if it's an instance of a class 
is to use isinstance()
    http://docs.python.org/2/library/functions.html#isinstance

isinstance(x, int)
And if you need to test more than one type or class, use a tuple of the 
types:

isinstance(x, (int, float))

Now you can combine more than one such test:

if  isinstance(x, (int, float)) and isinstance(y, (int, float)):



-- 
DaveA

From davea at davea.name  Mon Apr  8 12:49:22 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 08 Apr 2013 06:49:22 -0400
Subject: [Tutor] if statement problems(noob question)
In-Reply-To: <CAPwGs2ruiHJ6XaUdtmGeE-MvWSVhVW+Q4aJwgPiOK-x4mDieYg@mail.gmail.com>
References: <CANSMJux_Dr7zqqFQ0+A1s6uqm-3eedrADW+4n7Tv8cerWfbT=Q@mail.gmail.com>
	<CAPwGs2ruiHJ6XaUdtmGeE-MvWSVhVW+Q4aJwgPiOK-x4mDieYg@mail.gmail.com>
Message-ID: <5162A0B2.7040707@davea.name>

On 04/08/2013 06:37 AM, Woody 544 wrote:
> Max,
>
> You've made the arguments a string (so never a number) in:
>
> print "The answer is: " + str(x+y)
>
> MJ

That has nothing to do with the issue.  The str() function call is 
unnecessary, but harmless.  If the two values x and y are ints or 
floats, they will get added in the obvious way long before being 
converted to str().

If they are already strings, they'll be concatenated long before str() 
does a null conversion on the resultant string.

The problem, as I stated in my own response, is that the if statement 
does nothing useful for checking of types.


-- 
DaveA

From steve at pearwood.info  Mon Apr  8 13:55:17 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 08 Apr 2013 21:55:17 +1000
Subject: [Tutor] if statement problems(noob question)
In-Reply-To: <51629FE7.2030809@davea.name>
References: <CANSMJux_Dr7zqqFQ0+A1s6uqm-3eedrADW+4n7Tv8cerWfbT=Q@mail.gmail.com>
	<51629FE7.2030809@davea.name>
Message-ID: <5162B025.20709@pearwood.info>

On 08/04/13 20:45, Dave Angel wrote:
>
> will always fail, since the integer 2 is not equal to the type int.  In Python 2.x, when you compare objects of different types, you generally get unequal.  (Exception, if you define your own classes, you can define how they compare to others)  In Python 3, you'd get an exception.


Not so. Equality testing is always allowed.

In Python 3:


py> 25 == "hello world"
False


exactly the same as in Python 2. It's only ordering comparisons, < <= >= > that raise an error with incompatible types:

py> 25 <= "hello world"
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: unorderable types: int() <= str()



-- 
Steven

From steve at pearwood.info  Mon Apr  8 14:18:06 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 08 Apr 2013 22:18:06 +1000
Subject: [Tutor] if statement problems(noob question)
In-Reply-To: <CANSMJux_Dr7zqqFQ0+A1s6uqm-3eedrADW+4n7Tv8cerWfbT=Q@mail.gmail.com>
References: <CANSMJux_Dr7zqqFQ0+A1s6uqm-3eedrADW+4n7Tv8cerWfbT=Q@mail.gmail.com>
Message-ID: <5162B57E.1050409@pearwood.info>

On 08/04/13 20:21, Max Smith wrote:
> Hi, everyone whom might read this, im Max and i am really new to coding,
> been going at it for about two weeks using codeacademy and the book "think
> python".
> when i decided to experiment a little with if statements i ran into the
> following problem:
>
> def plus(x,y):
>      if x and y == int or float:
>          print "The answer is: " + str(x+y)
>      else:
>          print "not a number"


Your problem here is that you've let Python's friendly syntax fool you into
thinking you can program in English. Python's good, but it's not that good!


In English, I might say to you:

"If x and y are ints, or floats, then do this ..."

which you've translated into Python as:

if x and y == int or float: ...


But that's not what it means to Python. What Python does is quite different.
Translating the above:

if x is a truthy value,
    and y equals the function "int",
    or the function "float" is a truthy value,
then ...


What do I mean by "is a truthy value"?

Python has a rule that *every* value, numbers, strings, lists, etc, everything,
can be considered "true-like" or "false-like". The rules are:

- values which are considered "empty" or "nothing" in some sense are treated
   as false-like:

   zero numbers: 0, 0.0
   empty string: ''
   empty containers (lists, dicts, tuples)
   None
   False

   are all "false-like" or "falsey" values.


- values which are considered non-empty, or "something", are treated as
   true-like:

   every number except zero, e.g. 0.0001, 42, -17.4
   every non-empty string, e.g. "hello world"
   every non-empty container, e.g. [1, 2, 3]
   True
   functions
   modules
   etc.

   are all "true-like" or "truthy" values.


So let's go back to your code:

if x and y == int or float: ...


1) First, Python checks whether x is a truthy value. In the examples you give,
it is, so the if-clause starts to look like this:

     if True and y == int or float: ...


2) Next, Python checks whether y equals the int function. In this case, it does
not, so the if-clause looks like this:

     if True and False or float: ...

and Python can simplify "True and False" to just False:

     if False or float: ...


3) Next, Python checks whether the float function is a truthy value. Since
functions are "something" rather than "nothing", it is considered truthy, and
the if-clause looks like this:

     if False or True: ...

which Python simplifies to:

     if True: ...


and so the if-clause *always* evaluates as True.



So what do you have to write instead?

Firstly, you can't check the type of a value with equals. You use the isinstance
function instead. To check if x is an int:

if isinstance(x, int): ...


To check if x is an int, or a float, make the second argument a tuple of types:


if isinstance(x, (int, float)): ...


To check is x *and* y are ints, or floats, you have to check each one separately:


number = (int, float)  # tuple of two types
if isinstance(x, number) and isinstance(y, number): ...




Try that, and see how your code works.





-- 
Steven

From steve at pearwood.info  Mon Apr  8 14:26:28 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 08 Apr 2013 22:26:28 +1000
Subject: [Tutor] Socket Programming
In-Reply-To: <CACQ6Q4Ev5t617wcdv0e-_VEmQ5GEg0AQFM+Atnxp1fiLnOVKFg@mail.gmail.com>
References: <CACQ6Q4Ev5t617wcdv0e-_VEmQ5GEg0AQFM+Atnxp1fiLnOVKFg@mail.gmail.com>
Message-ID: <5162B774.7040201@pearwood.info>

On 08/04/13 17:06, Mousumi Basu wrote:
> I want to perform binding between two computers having ip addresses
> 172.18.2.11 and  172.18.2.95.So i wrote the following code(on the computer
> having IP address 172.18.2.95):-
>
>
> import socket
> import sys
> s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
> try:
>      s=s.bind(('172.18.2.11',2213))
>      print 'socket bind is complete'
> except socket.error,msg:
>      print 'bind failed'
>      sys.exit()



Why are you throwing away the useful information Python gives you to debug the
problem? That's like trying to find your lost keys by deliberately putting on a
blindfold.

Never, never, never catch an exception only to print a useless message that
tells you nothing. "Bind failed"? Why did it fail? Who knows! You threw that
information away. You might as well have said "An error occurred".

Instead, use this code:


import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s = s.bind(('172.18.2.11', 2213))
print 'socket bind is complete'


If an error occurs, Python will automatically print a full traceback showing
you exactly:

* what went wrong
* where it went wrong
* what line of code caused the problem
* what type of problem it was

instead of just a useless "an error occurred" message.


Once you have a proper traceback, and you can see the actual error message,
then and only then can we begin to solve the problem.




-- 
Steven

From davea at davea.name  Mon Apr  8 14:27:31 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 08 Apr 2013 08:27:31 -0400
Subject: [Tutor] if statement problems(noob question)
In-Reply-To: <5162B025.20709@pearwood.info>
References: <CANSMJux_Dr7zqqFQ0+A1s6uqm-3eedrADW+4n7Tv8cerWfbT=Q@mail.gmail.com>
	<51629FE7.2030809@davea.name> <5162B025.20709@pearwood.info>
Message-ID: <5162B7B3.4050909@davea.name>

On 04/08/2013 07:55 AM, Steven D'Aprano wrote:
> On 08/04/13 20:45, Dave Angel wrote:
>>
>> will always fail, since the integer 2 is not equal to the type int.
>> In Python 2.x, when you compare objects of different types, you
>> generally get unequal.  (Exception, if you define your own classes,
>> you can define how they compare to others)  In Python 3, you'd get an
>> exception.
>
>
> Not so. Equality testing is always allowed.
>

Right.  Thanks for the correction.  I should know better by now.

I knew I should have left that part off, since the OP is using version 2 
anyway.

-- 
DaveA

From s.shall at virginmedia.com  Mon Apr  8 14:40:17 2013
From: s.shall at virginmedia.com (Sydney Shall)
Date: Mon, 08 Apr 2013 13:40:17 +0100
Subject: [Tutor] How to extract a float from an instancemethod call
Message-ID: <5162BAB1.8010700@virginmedia.com>

Hi,
I am  learning Python.

I use MAC OSX 10.6.8
Python 2.7.3

I have been given a project to write a program involving random walks.
I have drafted a program which has passed all the static tests, but on 
testing my program i get the following error message:


Traceback (most recent call last):
   File "/Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py", line 303, in <module>
     testRobotMovement(StandardRobot, RectangularRoom)
   File "ps7_verify_movement.py", line 12, in testRobotMovement
   File "/Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean
     while self.room.isPositionInRoom(self.position) == False:
   File "/Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom
     return self.room[(x,y)] in self.room
KeyError: (<bound method Position.getX of <__main__.Position object at 
0x4699490>>, <bound method Position.getY of <__main__.Position object at 
0x4699490>>)
 >>>

The program text referred to is the following, I give the whole module, 
which is part of a larger program.
  def isPositionInRoom(self, pos):
         """
         Return True if pos is inside the room.

         pos: a Position object.
         returns: True if pos is in the room, False otherwise.
         """
         x = pos.getX
         y = pos.getY
         return self.room[(x,y)] in self.room

The module that made the call is;
  def updatePositionAndClean(self):
         """
         Simulate the raise passage of a single time-step.

         Move the robot to a new position and mark the tile it is on as 
having
         been cleaned.
         """
         steps = 0
         self.position = self.room.getRandomPosition()
         print self.position

         self.x = self.position.getX
         self.y = self.position.getY
         print self.room

         self.room.cleanTileAtPosition((self.x, self.y))

         self.direction = self.getRobotDirection()

         print 'Initial direction in degrees is ' , self.direction

         self.position = self.position.getNewPosition(self.direction, 
self.speed)
         steps += 1
         while self.room.isPositionInRoom(self.position) == False:
             self.direction = Robot.getRobotDirection()
             self.position = Position.getNewPosition(self.direction, 
self.speed)
             steps += 1
         self.x = self.position.getX
         self.y = self.position.getY


         print 'Current position is x,y ', self.x, self.y
         print 'Current direction is ' , self.direction + 'Degrees.'

         self.room.cleanTileAtPosition((self.x, self.y))

         print self.room.isTileCleaned((self.x, self.y))

I do not understand how one extracts a number from an instance method 
that should return a number.
I need to convert this number a float to an int to avoid the key error.
But I do not know how to extract the float.

This conclusion I derive from this earlier error message;

Traceback (most recent call last):
   File "/Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py", line 303, in <module>
     testRobotMovement(StandardRobot, RectangularRoom)
   File "ps7_verify_movement.py", line 12, in testRobotMovement
   File "/Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean
     while self.room.isPositionInRoom(self.position) == False:
   File "/Users/Sydney/Documents/6.00x Files/Problem 
Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom
     return self.room[(int(x), int(y))] in self.room
TypeError: int() argument must be a string or a number, not 'instancemethod'
 >>> ================================ RESTART 
================================

I would be grateful for any guidance.






-- 
Sydney Shall

From davea at davea.name  Mon Apr  8 14:52:21 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 08 Apr 2013 08:52:21 -0400
Subject: [Tutor] How to extract a float from an instancemethod call
In-Reply-To: <5162BAB1.8010700@virginmedia.com>
References: <5162BAB1.8010700@virginmedia.com>
Message-ID: <5162BD85.7070207@davea.name>

On 04/08/2013 08:40 AM, Sydney Shall wrote:
> Hi,
> I am  learning Python.
>
> I use MAC OSX 10.6.8
> Python 2.7.3
>
> I have been given a project to write a program involving random walks.
> I have drafted a program which has passed all the static tests, but on
> testing my program i get the following error message:
>
>
> Traceback (most recent call last):
>    File "/Users/Sydney/Documents/6.00x Files/Problem
> Sets/ProblemSet7/ps7 copy.py", line 303, in <module>
>      testRobotMovement(StandardRobot, RectangularRoom)
>    File "ps7_verify_movement.py", line 12, in testRobotMovement
>    File "/Users/Sydney/Documents/6.00x Files/Problem
> Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean
>      while self.room.isPositionInRoom(self.position) == False:
>    File "/Users/Sydney/Documents/6.00x Files/Problem
> Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom
>      return self.room[(x,y)] in self.room
> KeyError: (<bound method Position.getX of <__main__.Position object at
> 0x4699490>>, <bound method Position.getY of <__main__.Position object at
> 0x4699490>>)
>  >>>
>
> The program text referred to is the following, I give the whole module,
> which is part of a larger program.
>   def isPositionInRoom(self, pos):
>          """
>          Return True if pos is inside the room.
>
>          pos: a Position object.
>          returns: True if pos is in the room, False otherwise.
>          """
>          x = pos.getX
>          y = pos.getY

You never show the code for Position.getX and Position.getY, but I'd 
expect they're methods that take no arguments.  in that case, you need 
parens in order to call them.

            x = pos.getX()
            y = pos.getY()

>          return self.room[(x,y)] in self.room
>

a simple print of x and y could have revealed this as well.


-- 
DaveA

From kushal.kumaran+python at gmail.com  Mon Apr  8 15:37:58 2013
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Mon, 08 Apr 2013 19:07:58 +0530
Subject: [Tutor] Socket Programming
In-Reply-To: <CACQ6Q4Ev5t617wcdv0e-_VEmQ5GEg0AQFM+Atnxp1fiLnOVKFg@mail.gmail.com>
References: <CACQ6Q4Ev5t617wcdv0e-_VEmQ5GEg0AQFM+Atnxp1fiLnOVKFg@mail.gmail.com>
Message-ID: <5162c83b.e5f1420a.13d6.ffff81bf@mx.google.com>

Mousumi Basu <mousumi251 at gmail.com> writes:

> I want to perform binding between two computers having ip addresses
> 172.18.2.11 and  172.18.2.95.So i wrote the following code(on the computer
> having IP address 172.18.2.95):-
>
>
> import socket
> import sys
> s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
> try:
>     s=s.bind(('172.18.2.11',2213))

The bind method does not do what you think it does.

To bind to an IP address, the address must be assigned to one of the
interfaces on the host where the code is running.  So your bind call
will not work on 172.18.2.95.  It will only work on 172.18.2.11.  To
make a connection to a different host, you call the connect method.

Since you are using SOCK_DGRAM, an explicit connect call is not
required.  You can just call the sendto method on the socket.  On the
other end, the socket will need the bind method to be called.  It can
then call recvfrom to receive data.

You should read an introductory sockets programming text if you intend
to use the python socket module.
This page: http://beej.us/guide/bgnet/output/html/multipage/index.html
which showed up in my web search, seems simple.  You will have to
translate C code to python, but the basic concepts will apply.

>     print 'socket bind is complete'
> except socket.error,msg:
>     print 'bind failed'
>     sys.exit()
>
>
> The output is :-
> bind failed
>
>
> but when i am writting;-
>
> s=s.bind(('localhost',2213))
>
> the output is;-
> socket bind is complete
>
>
>
> Can you please tell me where i am making the error?
> (The computers are connected as the ping operation is executing properly in
> command prompt)

-- 
regards,
kushal

From Steve.Flynn at capita.co.uk  Mon Apr  8 14:48:17 2013
From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT))
Date: Mon, 8 Apr 2013 13:48:17 +0100
Subject: [Tutor] How to extract a float from an instancemethod call
In-Reply-To: <5162BAB1.8010700@virginmedia.com>
References: <5162BAB1.8010700@virginmedia.com>
Message-ID: <D35D4ADAE41B404A9EB381E750C1A5A503ADF065@CAPPRWMMBX14.central.ad.capita.co.uk>

Aha - another EdX 6.00 Python course student.

> Traceback (most recent call last):
>    File "/Users/Sydney/Documents/6.00x Files/Problem
> Sets/ProblemSet7/ps7 copy.py", line 303, in <module>
>      testRobotMovement(StandardRobot, RectangularRoom)
>    File "ps7_verify_movement.py", line 12, in testRobotMovement
>    File "/Users/Sydney/Documents/6.00x Files/Problem
> Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean
>      while self.room.isPositionInRoom(self.position) == False:
>    File "/Users/Sydney/Documents/6.00x Files/Problem
> Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom
>      return self.room[(x,y)] in self.room
> KeyError: (<bound method Position.getX of <__main__.Position object at
> 0x4699490>>, <bound method Position.getY of <__main__.Position object
at
> 0x4699490>>)
>  >>>
> 
> The program text referred to is the following, I give the whole
module,
> which is part of a larger program.
>   def isPositionInRoom(self, pos):
>          """
>          Return True if pos is inside the room.
> 
>          pos: a Position object.
>          returns: True if pos is in the room, False otherwise.
>          """
>          x = pos.getX
>          y = pos.getY
>          return self.room[(x,y)] in self.room


You extract X and Y from the Position object using it's accessor
methods. All you then need to do is check to ensure that both X and Y
are >= zero and that both of them, when converted to an into, are less
than room. width and room. height.




This email and any attachment to it are confidential.  Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately.

Any views or opinions expressed in this email are those of the sender only, unless otherwise stated.  All copyright in any Capita material in this email is reserved.

All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. 

Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law.

From alan.gauld at btinternet.com  Mon Apr  8 11:02:04 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 08 Apr 2013 10:02:04 +0100
Subject: [Tutor] Socket Programming
In-Reply-To: <CACQ6Q4Ev5t617wcdv0e-_VEmQ5GEg0AQFM+Atnxp1fiLnOVKFg@mail.gmail.com>
References: <CACQ6Q4Ev5t617wcdv0e-_VEmQ5GEg0AQFM+Atnxp1fiLnOVKFg@mail.gmail.com>
Message-ID: <kju128$5b2$1@ger.gmane.org>

On 08/04/13 08:06, Mousumi Basu wrote:

> import socket
> import sys
> s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
> try:
>      s=s.bind(('172.18.2.11',2213))
>      print 'socket bind is complete'
> except socket.error,msg:
>      print 'bind failed'
>      sys.exit()

Your first error is that when developing you don't want to hide the 
error messages so add a raise statement to the except block so you get 
the full traceback with all of its helpful details.


> but when i am writting;-
>
> s=s.bind(('localhost',2213))
>
> the output is;-
> socket bind is complete

Which suggests that the 172... IP address you are using above is not 
recognised... or maybe has a firewall around it, or some other 
restrictions on access.

> Can you please tell me where i am making the error?
> (The computers are connected as the ping operation is executing properly
> in command prompt)

It is most likely a network configuration issue but only you can fix 
that since we can't see how the network is set up. Rather than using 
ping try using telnet to reach the IP address and port and see what 
response you get.

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


From losermeloser at yahoo.com  Mon Apr  8 18:24:32 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Mon, 8 Apr 2013 09:24:32 -0700 (PDT)
Subject: [Tutor] Socket Programming
In-Reply-To: <5162c83b.e5f1420a.13d6.ffff81bf@mx.google.com>
References: <CACQ6Q4Ev5t617wcdv0e-_VEmQ5GEg0AQFM+Atnxp1fiLnOVKFg@mail.gmail.com>
	<5162c83b.e5f1420a.13d6.ffff81bf@mx.google.com>
Message-ID: <1365438272.94498.YahooMailNeo@web121105.mail.ne1.yahoo.com>

on socket programming. if as a client or server, the information being sent has a buffer size on 2048, will this retrieve all data below 2KB? or can it be exceeded with say 2100? or does 2100 fall under 3KB?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130408/a4d07624/attachment.html>

From donald.dietrich at live.com  Mon Apr  8 20:58:54 2013
From: donald.dietrich at live.com (Donald Dietrich)
Date: Mon, 8 Apr 2013 18:58:54 +0000
Subject: [Tutor] =?utf-8?q?Reading_Program?=
Message-ID: <BAY401-EAS102DF14AD2085DE1744539F8DC50@phx.gbl>

I am just new to python programing, but would like some help developing a program for ?flow reading?  What I would like the program to do is use any  .txt file like micorsoft word .txt file and flow the words across the screen one at time until the file is come to the end. I would also like to control the rate (time) of flow. Do you think you can help me.     Sincerely, Donald Dietrich



Sent from Windows Mail
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130408/f745275d/attachment.html>

From bgailer at gmail.com  Mon Apr  8 21:46:29 2013
From: bgailer at gmail.com (bob gailer)
Date: Mon, 08 Apr 2013 15:46:29 -0400
Subject: [Tutor] Reading Program
In-Reply-To: <BAY401-EAS102DF14AD2085DE1744539F8DC50@phx.gbl>
References: <BAY401-EAS102DF14AD2085DE1744539F8DC50@phx.gbl>
Message-ID: <51631E95.1060505@gmail.com>

On 4/8/2013 2:58 PM, Donald Dietrich wrote:
> I am just new to python programing
welcome. what other programming experience do you have? What version of 
python? and what OS?
> would like some help developing a program for "flow reading"  What I 
> would like the program to do is use any  .txt file like micorsoft word 
> .txt file and flow the words across the screen one at time until the 
> file is come to the end. I would also like to control the rate (time) 
> of flow.
Do you have any experience developing GUI applications?

Do you have any experience with reading files?

I would start simple, and add pieces one at a time. Pseudo code:

open the file
grab a line
   split it (by default this will give you a list of "words" - meaning 
text strings that are separated from one another by
   whitespace)
   write  a word to the console (terminal)
   sleep for a short time
   repeat for each word in the list
repeat for each line in the file.

Then take a look at the various GUI packages that have a Python version.

tkinter comes with the Python distribution.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130408/fcfc11f9/attachment.html>

From brianjamesarb at gmail.com  Mon Apr  8 22:38:24 2013
From: brianjamesarb at gmail.com (brian arb)
Date: Mon, 8 Apr 2013 16:38:24 -0400
Subject: [Tutor] FYI: An Introduction to Interactive Programming in Python
Message-ID: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>

An Introduction to Interactive Programming in PythonJoe Warren, Scott
Rixner, Stephen Wong and John Greiner

This course is designed to be a fun introduction to the basics of
programming in Python. Our main focus will be on building simple
interactive games such as Pong, Blackjack and Asteroids.

https://www.coursera.org/course/interactivepython
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130408/25ee7ad4/attachment.html>

From steve at pearwood.info  Tue Apr  9 01:58:42 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 09 Apr 2013 09:58:42 +1000
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
	Python
In-Reply-To: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
Message-ID: <516359B2.2040300@pearwood.info>

On 09/04/13 06:38, brian arb wrote:
> An Introduction to Interactive Programming in PythonJoe Warren, Scott
> Rixner, Stephen Wong and John Greiner
>
> This course is designed to be a fun introduction to the basics of
> programming in Python. Our main focus will be on building simple
> interactive games such as Pong, Blackjack and Asteroids.
>
> https://www.coursera.org/course/interactivepython

Thanks for the link Brian.

As an aside, I wonder, apart from Conway's Game of Life, which isn't
actually a game at all, what's a non-interactive game?



-- 
Steven

From dfjennings at gmail.com  Tue Apr  9 02:29:42 2013
From: dfjennings at gmail.com (Don Jennings)
Date: Mon, 8 Apr 2013 20:29:42 -0400
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
	Python
In-Reply-To: <516359B2.2040300@pearwood.info>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info>
Message-ID: <A587044E-6190-488C-8D85-1B92B1891E0C@gmail.com>


On Apr 8, 2013, at 7:58 PM, Steven D'Aprano wrote:

> On 09/04/13 06:38, brian arb wrote:
>> An Introduction to Interactive Programming in PythonJoe Warren, Scott
>> Rixner, Stephen Wong and John Greiner
>> 
>> This course is designed to be a fun introduction to the basics of
>> programming in Python. Our main focus will be on building simple
>> interactive games such as Pong, Blackjack and Asteroids.
>> 
>> https://www.coursera.org/course/interactivepython
> 
> Thanks for the link Brian.
> 
> As an aside, I wonder, apart from Conway's Game of Life, which isn't
> actually a game at all, what's a non-interactive game?

Watching someone else play Pong? ;>)

Take care,
Don


From davea at davea.name  Tue Apr  9 03:54:37 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 08 Apr 2013 21:54:37 -0400
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
	Python
In-Reply-To: <516359B2.2040300@pearwood.info>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info>
Message-ID: <516374DD.3060704@davea.name>

On 04/08/2013 07:58 PM, Steven D'Aprano wrote:
> On 09/04/13 06:38, brian arb wrote:
>> An Introduction to Interactive Programming in PythonJoe Warren, Scott
>> Rixner, Stephen Wong and John Greiner
>>
>> This course is designed to be a fun introduction to the basics of
>> programming in Python. Our main focus will be on building simple
>> interactive games such as Pong, Blackjack and Asteroids.
>>
>> https://www.coursera.org/course/interactivepython
>
> Thanks for the link Brian.
>
> As an aside, I wonder, apart from Conway's Game of Life, which isn't
> actually a game at all, what's a non-interactive game?
>
>

Perhaps a game where the interaction is not real-time, like Adventure 
and other early RPG's.

-- 
DaveA

From LConrad at Go2France.com  Tue Apr  9 05:20:24 2013
From: LConrad at Go2France.com (Len Conrad)
Date: Mon, 08 Apr 2013 21:20:24 -0600
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
 Python
In-Reply-To: <516374DD.3060704@davea.name>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name>
Message-ID: <201304090521923.SM01804@W500.Go2France.com>



wrong teaching language!  :)

Computer scientists develop video game that teaches how to program in Java

http://phys.org/news/2013-04-scientists-video-game-java.html


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130408/9c75e450/attachment.html>

From kartiksundarajan at gmail.com  Tue Apr  9 08:18:48 2013
From: kartiksundarajan at gmail.com (kartik sundarajan)
Date: Tue, 9 Apr 2013 11:48:48 +0530
Subject: [Tutor] Phyton script for fasta file (seek help)
In-Reply-To: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com>
References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com>
Message-ID: <CAJ2_K29UYr9SzxOT6XLbiAu6UricYbJZY+REVbmLmy768fOd-w@mail.gmail.com>

My guess is you are using Python version >2.6 where "set" is a built-in.
You can fix this by doing the following.

1) Remove "from sets import Set"
2) And replace "alphabet = list(Set(stList))" with "alphabet =
list(set(stList))"

This should work straight away.

P.S Its "Python" not phyton

Cheers
Kartik



On Sun, Mar 24, 2013 at 12:20 PM, michelle_low <michelle_low at zoho.com>wrote:

> **
>
> Hi everyone,
>
>
> Can someone please help me with the following phyton script? I received
> the error message  DeprecationWarning: the sets module is deprecated
>   from sets import Set.
>
> After googling, I have tried the methods others suggest:  change sets to
> set or delete the from sets import Set but none of them works.
>
> Can someone suggest me how to modify the following codes so that the input
> file is read from standard input?
> I'd like to execute them with unix command
>
> script.py <  sequence.fna
>
>
> Thanks a bunch.
>
>
>
> #!/usr/local/bin/python
>
> import math
> from sets import Set
>
>
> line = file("sequence.fna", "r")
>
> for x in line:
>   if x [0] == ">" :
>
> #determine the length of sequences
>     s=line.next()
>     s=s.rstrip()
>     length = len(s)
>
> # determine the GC content
>     G = s.count('G')
>     C = s.count('C')
>     GC= 100 * (float(G + C) / length)
>
>
>     stList = list(s)
>     alphabet = list(Set(stList))
>
>     freqList = []
>     for symbol in alphabet:
>       ctr = 0
>       for sym in stList:
>         if sym == symbol:
>             ctr += 1
>     freqList.append(float(ctr)/len(stList))
>
> # Shannon entropy
>   ent = 0.0
>   for freq in freqList:
>     ent = ent + freq * math.log(freq, 2)
>   ent = -ent
>
>   print x
>   print "Length:" , length
>   print "G+C:" ,round(GC),"%"
>   print 'Shannon entropy:'
>   print ent
>   print 'Minimum number of bits required to encode each symbol:'
>   print int(math.ceil(ent))
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/078c371a/attachment.html>

From alan.gauld at btinternet.com  Tue Apr  9 09:50:52 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 09 Apr 2013 08:50:52 +0100
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
	Python
In-Reply-To: <201304090521923.SM01804@W500.Go2France.com>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name>
	<201304090521923.SM01804@W500.Go2France.com>
Message-ID: <kk0h8o$1dv$1@ger.gmane.org>

On 09/04/13 04:20, Len Conrad wrote:

>   Computer scientists develop video game that teaches how to program in
>   Java*
>
> http://phys.org/news/2013-04-scientists-video-game-java.html

As an engineer I used to be embarrassed that people called it software 
engineering. Now they are calling this computer *science*.... oh dear...

========================
CodeSpells was influenced by research that Esper and Foster conducted on 
how successful programmers learn their trade. They surveyed 30 computer 
scientists and identified five characteristics that are key to learn 
programming outside a classroom setting: activities must be structured 
by the person who is trying to learn; learning must be creative and 
exploratory; programming is empowering; learners have difficulty 
stopping once they start; and learners spend countless hours on the 
activity.
=======================

Since when did 30 become a representative sample size?


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


From breamoreboy at yahoo.co.uk  Tue Apr  9 10:48:32 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 09 Apr 2013 09:48:32 +0100
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
	Python
In-Reply-To: <201304090521923.SM01804@W500.Go2France.com>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name>
	<201304090521923.SM01804@W500.Go2France.com>
Message-ID: <kk0kif$p7d$2@ger.gmane.org>

On 09/04/2013 04:20, Len Conrad wrote:
>
>   *wrong teaching language!  :)
>
>   Computer scientists develop video game that teaches how to program in
>   Java*
>
> http://phys.org/news/2013-04-scientists-video-game-java.html
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Please tone down your language.  Using four letter words starting with 
'j' on a Python mailing list is a bit offputting first thing in the 
morning :)

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From daedae11 at 126.com  Tue Apr  9 10:20:42 2013
From: daedae11 at 126.com (daedae11)
Date: Tue, 9 Apr 2013 16:20:42 +0800 (CST)
Subject: [Tutor] How to make a python script run on startup
Message-ID: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>

On Windows, how to make a python script run on startup?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/8e82f244/attachment.html>

From davea at davea.name  Tue Apr  9 11:29:56 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 09 Apr 2013 05:29:56 -0400
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
Message-ID: <5163DF94.1070107@davea.name>

On 04/09/2013 04:20 AM, daedae11 wrote:
> On Windows, how to make a python script run on startup?
>
>

Windows has a system scheduler, which you can add entries to, specifying 
what time(s) a particular entry is to run.  One of the choices is system 
startup.


-- 
DaveA

From rhettnaxel at gmail.com  Tue Apr  9 11:54:50 2013
From: rhettnaxel at gmail.com (Alexander Mark)
Date: Tue, 9 Apr 2013 05:54:50 -0400
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
Message-ID: <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>

There is a startup folder, usually on the start menu, you can add the script to. 

--ame

On Apr 9, 2013, at 4:20, daedae11 <daedae11 at 126.com> wrote:

> On Windows, how to make a python script run on startup?
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/2bcd9270/attachment.html>

From sayanchatterjee at gmail.com  Tue Apr  9 13:14:55 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Tue, 9 Apr 2013 16:44:55 +0530
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
	<092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
Message-ID: <CAAT-4OSnj0dFbj5g8GSUgJx71zmvjaTEgYndLvAFc9HxG0mpmw@mail.gmail.com>

Anything executable inside the start-up folder will run on start up!


On 9 April 2013 15:24, Alexander Mark <rhettnaxel at gmail.com> wrote:

> There is a startup folder, usually on the start menu, you can add the
> script to.
>
> --ame
>
> On Apr 9, 2013, at 4:20, daedae11 <daedae11 at 126.com> wrote:
>
> On Windows, how to make a python script run on startup?
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/9d3cb18f/attachment.html>

From eryksun at gmail.com  Tue Apr  9 13:21:32 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 9 Apr 2013 07:21:32 -0400
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
	<092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
Message-ID: <CACL+1aswcFMgue-CQL0OEzR-eBEZu3Axq+pgboO5B3tkAseMSw@mail.gmail.com>

On Tue, Apr 9, 2013 at 5:54 AM, Alexander Mark <rhettnaxel at gmail.com> wrote:
> There is a startup folder, usually on the start menu, you can add the script
> to.

current user:
"%USERPROFILE%\Start Menu\Programs\Startup"

all users:
"%ALLUSERSPROFILE%\Start Menu\Programs\Startup"

Updating the latter will probably require elevation, which you do via
ShellExecute with the "runas" verb, using either pywin32 or ctypes. If
you don't want a console use the .pyw extension.

From ausnajm at yahoo.com.au  Tue Apr  9 13:50:45 2013
From: ausnajm at yahoo.com.au (Najam Us Saqib)
Date: Tue, 9 Apr 2013 04:50:45 -0700 (PDT)
Subject: [Tutor] Flip a coin
Message-ID: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com>

Hi,

This program is killing me, I have been working on it for last 3 hours, I have tried my best but can't make it work, please help me out.?

The Problem:

Create a program that flips a coin 100 times and than tells you the number of tails and heads.

My code:

# Flip a coin

import random

flip_coin = 100
head = ""
tail = ""
n_head = 0
n_tail = 0
the_num = (raw_input("Press enter key to flip the coin!"))


#raw_input("Please Flip the Coin")

while flip_coin != 100:
? ? flip_coin = random.randrange(100) +1?
? ? if flip_coin <= 50:
? ? ? ? ?
? ? ?print "head"
? ??
? ? else:?
? ? ?print "tail"
? ??
? ? the_num = (raw_input("Press Enter to flip the coin"))
? ? n_head += 1
? ? n_tail += 1
? ??
? ??

print "The total numbers of heads are" ,n_head
print "The total numbers of tails are" ,n_tail

raw_input("\n\nPress the enter key to exit, thank you")

Thank you very much, looking forward to hear from you.

Regards,
Najam.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/64f13465/attachment.html>

From sayanchatterjee at gmail.com  Tue Apr  9 14:14:59 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Tue, 9 Apr 2013 17:44:59 +0530
Subject: [Tutor] Flip a coin
In-Reply-To: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com>
References: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com>
Message-ID: <CAAT-4OQ6AgH85AhphQjmtoGkYjuFqXK=rFLyo-X7rqWymQjkRQ@mail.gmail.com>

flip_coin = 100

and then after a while

while flip_coin != 100:

It is contradicting.So the while loop is never executed. Just put flip_coin
= 0 and remove
head = ""
tail = ""

They are not necessary.

It should work.

Cheers,
Sayan


On 9 April 2013 17:20, Najam Us Saqib <ausnajm at yahoo.com.au> wrote:

> Hi,
>
> This program is killing me, I have been working on it for last 3 hours, I
> have tried my best but can't make it work, please help me out.
>
> The Problem:
>
> Create a program that flips a coin 100 times and than tells you the number
> of tails and heads.
>
> My code:
>
> # Flip a coin
>
> import random
>
> flip_coin = 100
> head = ""
> tail = ""
> n_head = 0
> n_tail = 0
> the_num = (raw_input("Press enter key to flip the coin!"))
>
>
> #raw_input("Please Flip the Coin")
>
> while flip_coin != 100:
>     flip_coin = random.randrange(100) +1
>     if flip_coin <= 50:
>
>      print "head"
>
>     else:
>      print "tail"
>
>     the_num = (raw_input("Press Enter to flip the coin"))
>     n_head += 1
>     n_tail += 1
>
>
>
> print "The total numbers of heads are" ,n_head
> print "The total numbers of tails are" ,n_tail
>
> raw_input("\n\nPress the enter key to exit, thank you")
>
> Thank you very much, looking forward to hear from you.
>
> Regards,
> Najam.
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>


-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/f93841ec/attachment-0001.html>

From steve at pearwood.info  Tue Apr  9 14:18:17 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 09 Apr 2013 22:18:17 +1000
Subject: [Tutor] Flip a coin
In-Reply-To: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com>
References: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com>
Message-ID: <51640709.4030202@pearwood.info>

On 09/04/13 21:50, Najam Us Saqib wrote:
> Hi,
>
> This program is killing me, I have been working on it for last 3 hours, I have tried my best but can't make it work, please help me out.


Would you like to tell us what it is doing wrong, or should we guess?

My guess is below:

> flip_coin = 100

Here you set flip_coin to 100.

> while flip_coin != 100:

Here you test whether flip_coin is not equal to 100. Since it is 100, the while loop is skipped, and nothing you write inside the while loop is executed at all.


If you want to run something 100 times, use a for loop:

for i in range(100):
     do_something()


-- 
Steven

From steve at pearwood.info  Tue Apr  9 14:47:50 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 09 Apr 2013 22:47:50 +1000
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
	Python
In-Reply-To: <kk0h8o$1dv$1@ger.gmane.org>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name>
	<201304090521923.SM01804@W500.Go2France.com>
	<kk0h8o$1dv$1@ger.gmane.org>
Message-ID: <51640DF6.4060503@pearwood.info>

On 09/04/13 17:50, Alan Gauld wrote:
> On 09/04/13 04:20, Len Conrad wrote:
>
>>   Computer scientists develop video game that teaches how to program in
>>   Java*
>>
>> http://phys.org/news/2013-04-scientists-video-game-java.html
>
> As an engineer I used to be embarrassed that people called it software engineering. Now they are calling this computer *science*.... oh dear...


Computer science is a science, or to be technical, a branch of mathematics. It has about as much to do with the every day practice of writing programs as science does to the every day practice of building televisions -- that is to say, depending on how you look at it, either *not at all* or *completely*.


But in this case, it's less computer science and more pedagogy, which is the science and art of teaching.



> ========================
> CodeSpells was influenced by research that Esper and Foster conducted on how successful programmers learn their trade. They surveyed 30 computer scientists and identified five characteristics that are key to learn programming outside a classroom setting: activities must be structured by the person who is trying to learn; learning must be creative and exploratory; programming is empowering; learners have difficulty stopping once they start; and learners spend countless hours on the activity.
> =======================
>
> Since when did 30 become a representative sample size?


If they are randomly selected, 30 is likely plenty for a representative sample size. In surveys, a sample size of 30 gives you a margin of error of about 15%, which isn't too bad. (To drop that margin of error to 10% means increasing the sample size to about 65, and to 5%, you need about 250 people.)

In this case, I would be suspicious of the results, not because 30 is too small a sample, but because:

1) it is likely to be a biased selection

2) both computer scientists and educators are prone to fashions, and Java is one such fashion.



-- 
Steven

From kevgathuku at gmail.com  Tue Apr  9 15:48:45 2013
From: kevgathuku at gmail.com (Kevin Ndung'u)
Date: Tue, 9 Apr 2013 16:48:45 +0300
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <CACL+1aswcFMgue-CQL0OEzR-eBEZu3Axq+pgboO5B3tkAseMSw@mail.gmail.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
	<092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
	<CACL+1aswcFMgue-CQL0OEzR-eBEZu3Axq+pgboO5B3tkAseMSw@mail.gmail.com>
Message-ID: <CAP8Q3Z1-AjQzGUc1x+6DtOgkozbKzY4wUj2kOJpPFTuHoapvEw@mail.gmail.com>

anybody know how to do this on linux?

On 4/9/13, eryksun <eryksun at gmail.com> wrote:
> On Tue, Apr 9, 2013 at 5:54 AM, Alexander Mark <rhettnaxel at gmail.com>
> wrote:
>> There is a startup folder, usually on the start menu, you can add the
>> script
>> to.
>
> current user:
> "%USERPROFILE%\Start Menu\Programs\Startup"
>
> all users:
> "%ALLUSERSPROFILE%\Start Menu\Programs\Startup"
>
> Updating the latter will probably require elevation, which you do via
> ShellExecute with the "runas" verb, using either pywin32 or ctypes. If
> you don't want a console use the .pyw extension.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

From sayanchatterjee at gmail.com  Tue Apr  9 16:12:05 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Tue, 9 Apr 2013 19:42:05 +0530
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <CAP8Q3Z1-AjQzGUc1x+6DtOgkozbKzY4wUj2kOJpPFTuHoapvEw@mail.gmail.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
	<092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
	<CACL+1aswcFMgue-CQL0OEzR-eBEZu3Axq+pgboO5B3tkAseMSw@mail.gmail.com>
	<CAP8Q3Z1-AjQzGUc1x+6DtOgkozbKzY4wUj2kOJpPFTuHoapvEw@mail.gmail.com>
Message-ID: <CAAT-4OT57902+jqNK0kaMgNLVLEQ2xUMA=EYxm=Tr4vmLWhFAg@mail.gmail.com>

Hope this link helps.:)
http://stackoverflow.com/questions/8339555/how-to-run-a-script-at-the-start-up-of-ubuntu


On 9 April 2013 19:18, Kevin Ndung'u <kevgathuku at gmail.com> wrote:

> anybody know how to do this on linux?
>
> On 4/9/13, eryksun <eryksun at gmail.com> wrote:
> > On Tue, Apr 9, 2013 at 5:54 AM, Alexander Mark <rhettnaxel at gmail.com>
> > wrote:
> >> There is a startup folder, usually on the start menu, you can add the
> >> script
> >> to.
> >
> > current user:
> > "%USERPROFILE%\Start Menu\Programs\Startup"
> >
> > all users:
> > "%ALLUSERSPROFILE%\Start Menu\Programs\Startup"
> >
> > Updating the latter will probably require elevation, which you do via
> > ShellExecute with the "runas" verb, using either pywin32 or ctypes. If
> > you don't want a console use the .pyw extension.
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/72cbd3d5/attachment.html>

From msirenef at lightbird.net  Tue Apr  9 16:30:20 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Tue, 09 Apr 2013 10:30:20 -0400
Subject: [Tutor] Flip a coin
In-Reply-To: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com>
References: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com>
Message-ID: <516425FC.8050105@lightbird.net>

On 04/09/2013 07:50 AM, Najam Us Saqib wrote:
> Hi,
 >
 > This program is killing me, I have been working on it for last 3 
hours, I have tried my best but can't make it work, please help me out.
 >
 > The Problem:
 >
 > Create a program that flips a coin 100 times and than tells you the 
number of tails and heads.
 >
 > My code:
 >
 > # Flip a coin
 >
 > import random
 >
 > flip_coin = 100
 > head = ""
 > tail = ""
 > n_head = 0
 > n_tail = 0
 > the_num = (raw_input("Press enter key to flip the coin!"))
 >
 >
 > #raw_input("Please Flip the Coin")
 >
 > while flip_coin != 100:
 >     flip_coin = random.randrange(100) +1
 >     if flip_coin <= 50:
 >
 >      print "head"
 >
 >     else:
 >      print "tail"
 >
 >     the_num = (raw_input("Press Enter to flip the coin"))
 >     n_head += 1
 >     n_tail += 1
 >
 >
 >
 > print "The total numbers of heads are" ,n_head
 > print "The total numbers of tails are" ,n_tail
 >
 > raw_input("\n\nPress the enter key to exit, thank you")
 >
 > Thank you very much, looking forward to hear from you.
 >
 > Regards,
 > Najam.
 >


You shouldn't start with writing code when you're not clear on how it
needs to work -- instead, start with pseudo code. In the same way, if
you can lift 200lbs you can start with 100lbs and then work your way up.

The pseudo code is a lot simpler to write than code:

# assume 0 is heads and 1 is tails

num_heads = num_tails = 0

- repeat 100 times:
     get input from user
     if input == quit: break loop

     flip = random integer out of 0 and 1

     if flip:
         print tails
         num_tails += 1
     else:
         print heads
         num_heads += 1
     print num_heads, num_tails

print Exiting...


To find out how to pick a random integer, see:

http://docs.python.org/2/library/random.html


  -m


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/


From eryksun at gmail.com  Tue Apr  9 16:38:36 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 9 Apr 2013 10:38:36 -0400
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <7c3c0ce4.1900b.13deecaf89f.Coremail.daedae11@126.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
	<092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
	<CACL+1aswcFMgue-CQL0OEzR-eBEZu3Axq+pgboO5B3tkAseMSw@mail.gmail.com>
	<7c3c0ce4.1900b.13deecaf89f.Coremail.daedae11@126.com>
Message-ID: <CACL+1auPrYj2doH6uVKYVTC56f82LqT6WRGaHjGEa4izY8gXgw@mail.gmail.com>

On Tue, Apr 9, 2013 at 8:35 AM, daedae11 <daedae11 at 126.com> wrote:
> I refer the msdn for ShellExecute, there isn't a "runas" verb, only "edit",
> "find", "open", "print", "properties".

Adding a file to the all users startup folder probably doesn't even
require elevation. Maybe even a regular user can do it, given the
default ProgramData NTFS permissions. I don't remember what the
defaults are.

Background:

NT 6 (Vista) added User Account Control (UAC), which adds the "run as
administrator" option. This launches a process with an elevated access
token.

ShellExecute allows the same with the "runas" verb. You can verify
whether it exists on your system for the exefile filetype (e.g.
python.exe):

    C:\>reg query hkcr\exefile\shell\runas\command

    HKEY_CLASSES_ROOT\exefile\shell\runas\command
        (Default)    REG_SZ    "%1" %*
        IsolatedCommand    REG_SZ    "%1" %*

On a related note, the old "runas.exe" console command lets you launch
a process with the credentials of an administrator account. However,
it can't 'elevate' the process.

From eryksun at gmail.com  Tue Apr  9 16:55:31 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 9 Apr 2013 10:55:31 -0400
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <CAP8Q3Z1-AjQzGUc1x+6DtOgkozbKzY4wUj2kOJpPFTuHoapvEw@mail.gmail.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
	<092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
	<CACL+1aswcFMgue-CQL0OEzR-eBEZu3Axq+pgboO5B3tkAseMSw@mail.gmail.com>
	<CAP8Q3Z1-AjQzGUc1x+6DtOgkozbKzY4wUj2kOJpPFTuHoapvEw@mail.gmail.com>
Message-ID: <CACL+1asmPP=O+b0O1XKQS3adzGjP0jOQNgv_FJXqebyWB+pwUg@mail.gmail.com>

On Tue, Apr 9, 2013 at 9:48 AM, Kevin Ndung'u <kevgathuku at gmail.com> wrote:
>
> anybody know how to do this on linux?

For a desktop environment that implements freedesktop.org standards (X
Desktop Group), such as GNOME, KDE and Xfce, you can add .desktop
files per user to "$HOME/.config/autostart". System wide it's
"$XDG_CONFIG_DIRS/autostart".

http://standards.freedesktop.org/autostart-spec/latest/ar01s02.html

From brianjamesarb at gmail.com  Tue Apr  9 17:32:03 2013
From: brianjamesarb at gmail.com (brian arb)
Date: Tue, 9 Apr 2013 11:32:03 -0400
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
	Python
In-Reply-To: <516359B2.2040300@pearwood.info>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info>
Message-ID: <CABYizFKANj_ysn4i9ZjezpXHPwbeV5mdd=dyLzv+QsssQ6FthQ@mail.gmail.com>

One game  wrote along time ago when I was first learning Python and App
Engine is http://cdacabeecdebcabab.appspot.com/
It's kind of a  non-interactive Sudoku puzzle, the only really interaction
is to click "solve this" or "display next puzzle" then to watch the python
code written attempt to solve the puzzle you click on the button "next
iteration" until you reach a solution or the code fails to resolve any more
of the cells.




On Mon, Apr 8, 2013 at 7:58 PM, Steven D'Aprano <steve at pearwood.info> wrote:

> On 09/04/13 06:38, brian arb wrote:
>
>> An Introduction to Interactive Programming in PythonJoe Warren, Scott
>>
>> Rixner, Stephen Wong and John Greiner
>>
>> This course is designed to be a fun introduction to the basics of
>> programming in Python. Our main focus will be on building simple
>> interactive games such as Pong, Blackjack and Asteroids.
>>
>> https://www.coursera.org/**course/interactivepython<https://www.coursera.org/course/interactivepython>
>>
>
> Thanks for the link Brian.
>
> As an aside, I wonder, apart from Conway's Game of Life, which isn't
> actually a game at all, what's a non-interactive game?
>
>
>
> --
> Steven
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/ad3c0b66/attachment.html>

From davea at davea.name  Tue Apr  9 18:29:03 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 09 Apr 2013 12:29:03 -0400
Subject: [Tutor] Flip a coin
In-Reply-To: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com>
References: <1365508245.81711.YahooMailNeo@web161802.mail.bf1.yahoo.com>
Message-ID: <516441CF.6070101@davea.name>

On 04/09/2013 07:50 AM, Najam Us Saqib wrote:
> Hi,
>
> This program is killing me, I have been working on it for last 3 hours, I have tried my best but can't make it work, please help me out.
>
> The Problem:
>
> Create a program that flips a coin 100 times and than tells you the number of tails and heads.
>

Nowhere does that say to ask the user for input, or even to wait for 
user input.  So start with Miya's pseudo-code, remove the input stuff, 
and try to turn that into code.

Keep it very simple till it works, then consider whether any 
fancy-ing-up is useful.

-- 
DaveA

From davea at davea.name  Tue Apr  9 18:35:17 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 09 Apr 2013 12:35:17 -0400
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
	<092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
Message-ID: <51644345.5020603@davea.name>

On 04/09/2013 05:54 AM, Alexander Mark wrote:
> On Apr 9, 2013, at 4:20, daedae11 <daedae11 at 126.com> wrote:
>
>> On Windows, how to make a python script run on startup?
>>
>>
>> _
(Top-posted comment moved AFTER the question)

 > There is a startup folder, usually on the start menu, you can add the 
script to.
 >

But does anything in the startup folder run BEFORE any user logs in? 
It's been a long time since I had to run Windows, but I didn't think so.


-- 
DaveA

From davea at davea.name  Tue Apr  9 19:04:33 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 09 Apr 2013 13:04:33 -0400
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <2957c1e7.178e3.13dee722c12.Coremail.daedae11@126.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
	<5163DF94.1070107@davea.name>
	<2957c1e7.178e3.13dee722c12.Coremail.daedae11@126.com>
Message-ID: <51644A21.80108@davea.name>

On 04/09/2013 06:58 AM, daedae11 wrote:

(Please don't top-post.  And don't forget to include the list in your 
cc.  I'm forwarding it for you)

> Which module to should I use to add entries to that system scheduler?
>
>

The system scheduler is an interactive (gui) program that comes with the 
OS.  No idea what module would mean in this context.   And I haven't run 
Windows in a long time, except for occasionally helping others.

Every version of Windows does its best to move things around and confuse 
any administrative user.

For XP, try:
   http://support.microsoft.com/kb/308569

and notice there's a distinction between "When my computer starts" and 
"When a user logs on"

--
DaveA


From wolfrage8765 at gmail.com  Tue Apr  9 21:22:13 2013
From: wolfrage8765 at gmail.com (Jordan)
Date: Tue, 09 Apr 2013 21:22:13 +0200
Subject: [Tutor] Impossible Else as Exception
Message-ID: <51646A65.5080708@gmail.com>

I want to know what exception should be raised if there is a bug in my 
code that allows an else statement to be triggered, because the else 
condition in my code should be impossible, unless there is an error in 
my code.  What exception should I raise so that if my code is wrong it 
will raise an exception which will give me a trace back?  Which would be 
most Pythonic?

Example:

if condition is 1:
     do something with 1
elif condition is 2:
     do something with 2
else: # Impossible unless the code above is flawed.
     Raise Exception

From dyoo at hashcollision.org  Tue Apr  9 21:26:37 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Tue, 9 Apr 2013 13:26:37 -0600
Subject: [Tutor] Phyton script for fasta file (seek help)
In-Reply-To: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com>
References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com>
Message-ID: <CAGZAPF5pr4VBG1RA_94hMQrM2ECR_znWztEha1uRZeta6nBvXg@mail.gmail.com>

Side note: I would strongly suggest using the biopython libraries for
the basic parsing.  FASTA parsing has been done and replicated so many
times that it's almost a hazing ritual for the practicing
bioinformatician.  The biopython folks have written a parser, so
perhaps you can reuse it.

    http://biopython.org/wiki/Main_Page
    http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc11


About reading from either standard input or as command line arguments,
see the 'fileinput' library:

    http://docs.python.org/3/library/fileinput.html

It automatically handles reading either from sys.stdin, or by opening
up the name of the file passed as a command line argument.

From eryksun at gmail.com  Tue Apr  9 21:41:15 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 9 Apr 2013 15:41:15 -0400
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <51644345.5020603@davea.name>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
	<092EBFE6-98C9-4368-BBA1-0A91C6239984@gmail.com>
	<51644345.5020603@davea.name>
Message-ID: <CACL+1at2Ee5fAnec=cdjJVVoV7+oQBxvNhwZoHe2FUnc-55+9w@mail.gmail.com>

On Tue, Apr 9, 2013 at 12:35 PM, Dave Angel <davea at davea.name> wrote:
> But does anything in the startup folder run BEFORE any user logs in? It's
> been a long time since I had to run Windows, but I didn't think so.

The contents of the startup folders are executed in the current
session after logon. The same applies to run keys such as
"HKLM\Software\Microsoft\Windows\CurrentVersion\Run".

I wasn't taking "startup" to mean literally before any user has logged
on. But yes, if that's the requirement, you can use the Task Scheduler
service to start a program as a batch process in session 0 (or instead
create your own service).

Just as an FYI, in the "Home" versions of Windows the task scheduler
can't store logon credentials, so to run at startup you have to use
LOCALSERVICE or SYSTEM.

To automate creating a task use the "schtasks" command. For example,
to create a task named "Python" that runs python.exe at startup under
the LOCALSERVICE account, execute the following from an elevated
shell:

schtasks /Create /TN Python /RU LOCALSERVICE /SC ONSTART /TR
C:\Python33\python.exe

This will run as a non-interactive service in session 0. There won't
be a visible GUI or console window to interact with in your desktop
session.

From alan.gauld at btinternet.com  Tue Apr  9 22:04:16 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 09 Apr 2013 21:04:16 +0100
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
	Python
In-Reply-To: <51640DF6.4060503@pearwood.info>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name>
	<201304090521923.SM01804@W500.Go2France.com>
	<kk0h8o$1dv$1@ger.gmane.org> <51640DF6.4060503@pearwood.info>
Message-ID: <kk1s7s$3cp$1@ger.gmane.org>

On 09/04/13 13:47, Steven D'Aprano wrote:

>> Since when did 30 become a representative sample size?
>
> If they are randomly selected, 30 is likely plenty for a representative
> sample size. In surveys, a sample size of 30 gives you a margin of error
> of about 15%, which isn't too bad.

Hmm, if I'd gone to my manager (and especially the finance director) 
with a project proposal based on assumptions with a 15% margin they'd 
have thrown me out. And if I told them I'd developed 5 key assumptions 
based on that same proposal I'd probably have been fired! I'd be looking 
for something like 300+ samples for a project like this to claim that my 
5 key principles were valid. And its not like there is a shortage of 
computer scientists to ask (although admittedly harder to find ones with 
no formal computer training)!

> 1) it is likely to be a biased selection

My suspicion is they just asked around their local department!
But maybe I'm just overly suspicious...

> 2) both computer scientists and educators are prone to fashions, and
> Java is one such fashion.

I don't care about the language since their 5 principles of learning are 
language independent. It was the idea that you could define 5 key 
principles needed to learn to program from a sample size of 30...

If they came to me to peer review that I'd have been telling them to go 
back and do a bigger survey!

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


From alan.gauld at btinternet.com  Tue Apr  9 22:07:27 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 09 Apr 2013 21:07:27 +0100
Subject: [Tutor] How to make a python script run on startup
In-Reply-To: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
References: <57a77808.12add.13dede1fb60.Coremail.daedae11@126.com>
Message-ID: <kk1sdq$3cp$2@ger.gmane.org>

On 09/04/13 09:20, daedae11 wrote:
> On Windows, how to make a python script run on startup?

The same way you make anything run on startup there is nothing magical 
about Python code.

You can schedule it, add it to the registry or put it in the users 
startup folder if you want it at login rather than system start...

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


From breamoreboy at yahoo.co.uk  Tue Apr  9 22:38:45 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 09 Apr 2013 21:38:45 +0100
Subject: [Tutor] Impossible Else as Exception
In-Reply-To: <51646A65.5080708@gmail.com>
References: <51646A65.5080708@gmail.com>
Message-ID: <kk1u6i$o4l$1@ger.gmane.org>

On 09/04/2013 20:22, Jordan wrote:
> I want to know what exception should be raised if there is a bug in my
> code that allows an else statement to be triggered, because the else
> condition in my code should be impossible, unless there is an error in
> my code.  What exception should I raise so that if my code is wrong it
> will raise an exception which will give me a trace back?  Which would be
> most Pythonic?
>
> Example:
>
> if condition is 1:
>      do something with 1
> elif condition is 2:
>      do something with 2
> else: # Impossible unless the code above is flawed.
>      Raise Exception
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

The RuntimeError builtin see 
http://docs.python.org/3/library/exceptions.html#RuntimeError.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From ramit.prasad at jpmorgan.com  Tue Apr  9 22:58:49 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 9 Apr 2013 20:58:49 +0000
Subject: [Tutor] FYI: An Introduction to Interactive Programming
	in	Python
In-Reply-To: <kk1s7s$3cp$1@ger.gmane.org>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name>
	<201304090521923.SM01804@W500.Go2France.com>	<kk0h8o$1dv$1@ger.gmane.org>
	<51640DF6.4060503@pearwood.info> <kk1s7s$3cp$1@ger.gmane.org>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474182BC593@SCACMX008.exchad.jpmchase.net>

Alan Gauld wrote:
> 
> On 09/04/13 13:47, Steven D'Aprano wrote:
> 
> >> Since when did 30 become a representative sample size?
> >
> > If they are randomly selected, 30 is likely plenty for a representative
> > sample size. In surveys, a sample size of 30 gives you a margin of error
> > of about 15%, which isn't too bad.
> 
> Hmm, if I'd gone to my manager (and especially the finance director)
> with a project proposal based on assumptions with a 15% margin they'd
> have thrown me out. And if I told them I'd developed 5 key assumptions
> based on that same proposal I'd probably have been fired! I'd be looking
> for something like 300+ samples for a project like this to claim that my
> 5 key principles were valid. And its not like there is a shortage of
> computer scientists to ask (although admittedly harder to find ones with
> no formal computer training)!

Well, 15% error margin is from statistics and provable, but the layman
usually hears "30 people" and thinks "that's far too small". I certainly
did it too. :) 

Error margins are one of those surprising things like the Birthday 
Problem (at least to me). Seems like it should not be true but it is.
http://en.wikipedia.org/wiki/Birthday_problem

Honestly, with surveys the method of the survey itself makes a 
difference. This includes things like question wording, question
order, and even survey format (free form, multiple choice, etc).

Much like scientific studies, I am more interested in *how* it
was done than in some summarized (frequently sensationalized)
"findings". In my opinion, a flawed methodology is more 
frequently a problem than a small sample size. 

> 
> > 1) it is likely to be a biased selection
> 
> My suspicion is they just asked around their local department!
> But maybe I'm just overly suspicious... 

Overly suspicious or concerned based on experience? :)


~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.  

From silideba at gmail.com  Tue Apr  9 23:23:21 2013
From: silideba at gmail.com (Debashish Saha)
Date: Wed, 10 Apr 2013 02:53:21 +0530
Subject: [Tutor] Retrieving data from a text file
Message-ID: <CA+b=61DWQd2Q1uJVwwr7tW4qr=og8ad018SOz-cHbjQVpVD5ew@mail.gmail.com>

In the following you can see data from a ephemeris.txt file. Now I want to
retrieve several columns(say, for example the column starting with 00:00,
27.69 and 44.1) and name the array as x,y,z. What do I have to I tried this

x, y, z = numpy.loadtxt("ephemeris.txt", unpack=True)
And  got this error

"ValueError: could not convert string to float: Date__(UT)__HR:MN"
Could you also help me in converting that HR:MN into minute only?

Date__(UT)__HR:MN     R.A.__(a-apparent)__DEC\
**********************************************\
 2013-Jan-01 00:00 *   14 31 27.69 -12 29 44.1\
 2013-Jan-01 00:01 *   14 31 27.71 -12 29 44.1\
 2013-Jan-01 00:02 *   14 31 27.72 -12 29 44.2\
 2013-Jan-01 00:03 *   14 31 27.73 -12 29 44.2\
 2013-Jan-01 00:04 *   14 31 27.75 -12 29 44.3\
 2013-Jan-01 00:05 *   14 31 27.76 -12 29 44.3\
 2013-Jan-01 00:06 *   14 31 27.77 -12 29 44.4\
 2013-Jan-01 00:07 *   14 31 27.78 -12 29 44.4\
 2013-Jan-01 00:08 *   14 31 27.80 -12 29 44.4\
 2013-Jan-01 00:09 *   14 31 27.81 -12 29 44.5\p
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/7ca76a17/attachment-0001.html>

From bfishbein79 at gmail.com  Tue Apr  9 23:31:23 2013
From: bfishbein79 at gmail.com (Benjamin Fishbein)
Date: Tue, 9 Apr 2013 16:31:23 -0500
Subject: [Tutor] building a website with python
Message-ID: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>

Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet.
I learned html, css, and javascript via codeacademy.org, but have never built a website.
I would like to build it with Python, and was wondering if you could give me some pointers about what I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are all hosts basically the same.
Thanks,
Ben



From ramit.prasad at jpmorgan.com  Tue Apr  9 23:54:28 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 9 Apr 2013 21:54:28 +0000
Subject: [Tutor] building a website with python
In-Reply-To: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474182BD269@SCACMX008.exchad.jpmchase.net>

Benjamin Fishbein wrote:
> 
> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my
> small business. Now I want to build a website. I acquired the domain name through godaddy.com
> (bookchicken.com) but have not found hosting yet.
> I learned html, css, and javascript via codeacademy.org, but have never built a website.
> I would like to build it with Python, and was wondering if you could give me some pointers about what
> I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are
> all hosts basically the same.
> Thanks,
> Ben

http://wiki.python.org/moin/WebFrameworks

Lots of Python frameworks to choose from, though Django is the most famous/popular. There are
lighter frameworks too, depending on what you need.

Your hosting solution to support Python, and I do not believe all hosts support Python. You 
should double check with whatever host you choose.


~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.  

From marc.tompkins at gmail.com  Wed Apr 10 00:03:59 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Tue, 9 Apr 2013 15:03:59 -0700
Subject: [Tutor] building a website with python
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474182BD269@SCACMX008.exchad.jpmchase.net>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
	<5B80DD153D7D744689F57F4FB69AF474182BD269@SCACMX008.exchad.jpmchase.net>
Message-ID: <CAKK8jXbnwpiW99vLk5Vz5z8AQ6bahRjfab5bhOfTrbOJcEJ2FQ@mail.gmail.com>

On Tue, Apr 9, 2013 at 2:54 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com>wrote:

> Your hosting solution (needs) to support Python, and I do not believe all
> hosts support Python. You
> should double check with whatever host you choose.
>

Almost all commercial web hosts offer limited Python support (running as an
Apache module), but this is NOT sufficient to run the larger Python web
frameworks, such as Django.  What you need to check for is support for
"long-running processes"; as of the last time I checked, GoDaddy, 1and1,
and most of the budget hosts don't offer that - so no Django
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/a29a6344/attachment.html>

From wprins at gmail.com  Wed Apr 10 00:06:21 2013
From: wprins at gmail.com (Walter Prins)
Date: Tue, 9 Apr 2013 23:06:21 +0100
Subject: [Tutor] building a website with python
In-Reply-To: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
Message-ID: <CANLXbfC8QRro3jbcvdCpPMroM_2Jqq_vCeEZFQ1U4c61+krt4w@mail.gmail.com>

Hello Benjamin,

On 9 April 2013 22:31, Benjamin Fishbein <bfishbein79 at gmail.com> wrote:

> Hello. I learned Python this past year (with help from many of you) and
> wrote many programs for my small business. Now I want to build a website. I
> acquired the domain name through godaddy.com (bookchicken.com) but have
> not found hosting yet.
> I learned html, css, and javascript via codeacademy.org, but have never
> built a website.
> I would like to build it with Python, and was wondering if you could give
> me some pointers about what I need to learn first: Django is the thing to
> use? And do I need specific hosting to use python or are all hosts
> basically the same.
>

Django is good but arguably big and a bit intimidating if you're starting
out.  There are many alternatives, from so called "micro" frameworks like
"bottle" (which is implemented in a single Python file) to CherryPy to
Flask.  Personally, I'd suggest having a look at Web2Py.  It's not quite as
heavy as Django but very capable nonetheless.  It also deploys easily,
including to Google App Engine and elsewhere, and includes a very capable
Admin interface that also includes a basic IDE, thus allowing you to tweak
the site right from within the site should you have the need. Here's a nice
little presentation about Web2Py:
http://www.slideshare.net/blackthorne/web2pyweb-development-like-a-boss
... and a tutorial to get you going:
http://killer-web-development.com/section/1/0

Not all web hosts are the same -- you need to ensure you have Python
available with the host you use.  There are dedicated Python hosts out
there.  (PythonAnywhere comes to mind.)  As a slightly different
possibility, you might consider running your own virtual host in the cloud.
 You would need to learn a bit about administering a server box, but this
route does give you the ultimate control over your website and environment.
 Here's a link to Rackspace with which I've had good experiences thus far
for your review:
http://www.rackspace.com/cloud/servers/

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/29ae59ba/attachment.html>

From oscar.j.benjamin at gmail.com  Wed Apr 10 00:12:11 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Tue, 9 Apr 2013 23:12:11 +0100
Subject: [Tutor] Impossible Else as Exception
In-Reply-To: <51646A65.5080708@gmail.com>
References: <51646A65.5080708@gmail.com>
Message-ID: <CAHVvXxTrbgC-jgRBoXwdp4_ydAQp_-wm62ybeSR8GMn5pxvUgw@mail.gmail.com>

On 9 April 2013 20:22, Jordan <wolfrage8765 at gmail.com> wrote:
> I want to know what exception should be raised if there is a bug in my code
> that allows an else statement to be triggered, because the else condition in
> my code should be impossible, unless there is an error in my code.  What
> exception should I raise so that if my code is wrong it will raise an
> exception which will give me a trace back?  Which would be most Pythonic?
>
> Example:
>
> if condition is 1:
>     do something with 1
> elif condition is 2:
>     do something with 2
> else: # Impossible unless the code above is flawed.
>     Raise Exception

AssertionError is raised when an assert statement fails. Since this
situation is essentially an implicit assert it would make sense to use
that.


Oscar

From eire1130 at gmail.com  Wed Apr 10 00:58:39 2013
From: eire1130 at gmail.com (James Reynolds)
Date: Tue, 9 Apr 2013 18:58:39 -0400
Subject: [Tutor] building a website with python
In-Reply-To: <CANLXbfC8QRro3jbcvdCpPMroM_2Jqq_vCeEZFQ1U4c61+krt4w@mail.gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
	<CANLXbfC8QRro3jbcvdCpPMroM_2Jqq_vCeEZFQ1U4c61+krt4w@mail.gmail.com>
Message-ID: <CAE0jAbqrootBLQTF0AHxLLm3gDsWxHChBFH5+BPdZmOPdAj=8Q@mail.gmail.com>

As far as hosts, I use digital ocean. It's a cloud based thing like EC2,
but it's cheap (5/10/20 and up). You will of course have to configure
everything yourself, but that's not such a bad thing.

It will give you good experience configuring a linux box as well and
learning about deployment.

Since I'm a django developer, I'm going to suggest you learn that of
course. But, there are others out there. However, with Django you get the
Django eco system, which is large and very helpful.

For example, you can use fabric for easy deployment, south for database
migrations, celery for task management and so and so forth.

Even simple websites could find some use in south and fabric.


On Tue, Apr 9, 2013 at 6:06 PM, Walter Prins <wprins at gmail.com> wrote:

> Hello Benjamin,
>
> On 9 April 2013 22:31, Benjamin Fishbein <bfishbein79 at gmail.com> wrote:
>
>> Hello. I learned Python this past year (with help from many of you) and
>> wrote many programs for my small business. Now I want to build a website. I
>> acquired the domain name through godaddy.com (bookchicken.com) but have
>> not found hosting yet.
>> I learned html, css, and javascript via codeacademy.org, but have never
>> built a website.
>> I would like to build it with Python, and was wondering if you could give
>> me some pointers about what I need to learn first: Django is the thing to
>> use? And do I need specific hosting to use python or are all hosts
>> basically the same.
>>
>
> Django is good but arguably big and a bit intimidating if you're starting
> out.  There are many alternatives, from so called "micro" frameworks like
> "bottle" (which is implemented in a single Python file) to CherryPy to
> Flask.  Personally, I'd suggest having a look at Web2Py.  It's not quite as
> heavy as Django but very capable nonetheless.  It also deploys easily,
> including to Google App Engine and elsewhere, and includes a very capable
> Admin interface that also includes a basic IDE, thus allowing you to tweak
> the site right from within the site should you have the need. Here's a nice
> little presentation about Web2Py:
> http://www.slideshare.net/blackthorne/web2pyweb-development-like-a-boss
> ... and a tutorial to get you going:
> http://killer-web-development.com/section/1/0
>
> Not all web hosts are the same -- you need to ensure you have Python
> available with the host you use.  There are dedicated Python hosts out
> there.  (PythonAnywhere comes to mind.)  As a slightly different
> possibility, you might consider running your own virtual host in the cloud.
>  You would need to learn a bit about administering a server box, but this
> route does give you the ultimate control over your website and environment.
>  Here's a link to Rackspace with which I've had good experiences thus far
> for your review:
> http://www.rackspace.com/cloud/servers/
>
> Walter
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/cc73f83e/attachment-0001.html>

From alan.gauld at btinternet.com  Wed Apr 10 01:14:12 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 10 Apr 2013 00:14:12 +0100
Subject: [Tutor] Impossible Else as Exception
In-Reply-To: <51646A65.5080708@gmail.com>
References: <51646A65.5080708@gmail.com>
Message-ID: <kk27c0$i4q$1@ger.gmane.org>

On 09/04/13 20:22, Jordan wrote:
> I want to know what exception should be raised if there is a bug in my
> code that allows an else statement to be triggered, because the else
> condition in my code should be impossible,

class BuggyCodeError(StandardError): pass

Maybe?

Seriously, exceptions are not intended for handling buggy code.
You should be removing the bugs using assertions and tests.

The exception to raise is whatever is appropriate to how you
got into that else and that depends on the nature of the
conditions.

One option might be a ValueError or maybe an IOError.
I'm not sure I agree with the suggestion to use AssertionError because 
that implies it came from an assertion. I'd rather define a bespoke 
error class than use that.


> if condition is 1:
>      do something with 1
> elif condition is 2:
>      do something with 2
> else: # Impossible unless the code above is flawed.
>      Raise Exception

If its really impossible for the condition to be anything other than 1 
or 2 then an elif should not be needed. If it is possible to get another 
value think about what causes could exist to get the
other value ( even if it is a code error!!) and describe the cause(s).

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


From steve at pearwood.info  Wed Apr 10 01:52:40 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 10 Apr 2013 09:52:40 +1000
Subject: [Tutor] Impossible Else as Exception
In-Reply-To: <51646A65.5080708@gmail.com>
References: <51646A65.5080708@gmail.com>
Message-ID: <5164A9C8.6060405@pearwood.info>

On 10/04/13 05:22, Jordan wrote:
> I want to know what exception should be raised if there is a bug in my code that allows an else statement to be triggered, because the else condition in my code should be impossible, unless there is an error in my code.  What exception should I raise so that if my code is wrong it will raise an exception which will give me a trace back?  Which would be most Pythonic?
>
> Example:
>
> if condition is 1:
>      do something with 1
> elif condition is 2:
>      do something with 2
> else: # Impossible unless the code above is flawed.
>      Raise Exception


The above isn't a great example, because the sample code *is* flawed.
The short reason why it is flawed is this:

You use identity tests (using `is`) instead of equality tests (using
`==`) which makes the above code fragile and dependent on the exact
version and implementation of Python being used. There are two rules
for when to use `is`:

1) Only use `is` when comparing to None;

2) (For everything else) If you have to ask if you should use `is`,
    the answer is No.


As given, your question cannot be answered simply. It depends on the
circumstances. Here are the two most common cases:


1) You're testing data you receive from a user, the caller, or another
part of the program. You know what the data should be, but you can't be
sure that it will be. Here's a toy example:


def func(n):
     """Do something useful. Argument n must be 1 or 2."""
     if n == 1:
         do_this()
     elif n == 2:
         do_that()
     else:
         # Y U No Listen? I told you that n must be 1 or 2!
         ...


So what should I put in place of the dots? The answer depends on the
exact tests being performed, but the two most common cases are:

ValueError, if the argument has the wrong value;

TypeError, if the argument has the wrong type.


In this case, I would go with ValueError:

     else:
          raise ValueError('n must be 1 or 2, not %r' % n)



1) You're testing the *internal logic* of your code. In this case, you're
sure of what the data will be, but out of some tiny lingering doubt that
maybe *you* have made a mistake, you want to check just to be sure. Here
is a toy example:


def spam(n):
     """Returns 'spam' n times. Guarantees to return spam."""
     if n <= 0: n = 1
     return ' '.join(['spam']*n)


def breakfast(hunger=3):
     s = "toast and %s and eggs" % spam(hunger)
     if "spam" in s:  # This should always be true.
         return s
     else:
         # This can never happen!
         raise RuntimeError('no spam in breakfast? yuck!')


So RuntimeError is a good choice for this. But if you are *sure* that
the error condition can *never* happen, but not *absolutely sure* and
you still want to check just in case you're mistaken, then an even
better way to write it is:

def breakfast(hunger=3):
     s = "toast and %s and eggs" % spam(hunger)
     assert "spam" in s, 'no spam in breakfast? yuck!'
     return s



-- 
Steven

From steve at pearwood.info  Wed Apr 10 01:56:53 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 10 Apr 2013 09:56:53 +1000
Subject: [Tutor] FYI: An Introduction to Interactive Programming
	in	Python
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474182BC593@SCACMX008.exchad.jpmchase.net>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name>
	<201304090521923.SM01804@W500.Go2France.com>	<kk0h8o$1dv$1@ger.gmane.org>
	<51640DF6.4060503@pearwood.info> <kk1s7s$3cp$1@ger.gmane.org>
	<5B80DD153D7D744689F57F4FB69AF474182BC593@SCACMX008.exchad.jpmchase.net>
Message-ID: <5164AAC5.9020404@pearwood.info>

On 10/04/13 06:58, Prasad, Ramit wrote:

> Much like scientific studies, I am more interested in *how* it
> was done than in some summarized (frequently sensationalized)
> "findings". In my opinion, a flawed methodology is more
> frequently a problem than a small sample size.

+1000 on that.


-- 
Steven

From steve at pearwood.info  Wed Apr 10 02:15:35 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 10 Apr 2013 10:15:35 +1000
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
	Python
In-Reply-To: <kk1s7s$3cp$1@ger.gmane.org>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info> <516374DD.3060704@davea.name>
	<201304090521923.SM01804@W500.Go2France.com>
	<kk0h8o$1dv$1@ger.gmane.org> <51640DF6.4060503@pearwood.info>
	<kk1s7s$3cp$1@ger.gmane.org>
Message-ID: <5164AF27.3050506@pearwood.info>

On 10/04/13 06:04, Alan Gauld wrote:
> On 09/04/13 13:47, Steven D'Aprano wrote:
>
>>> Since when did 30 become a representative sample size?
>>
>> If they are randomly selected, 30 is likely plenty for a representative
>> sample size. In surveys, a sample size of 30 gives you a margin of error
>> of about 15%, which isn't too bad.
>
> Hmm, if I'd gone to my manager (and especially the finance director) with a project proposal based on assumptions with a 15% margin they'd have thrown me out.

The 15% figure comes from surveys where people are asked to rate something on some scale, say from 1 to 7. If your sample of 30 gives an average rating of 5, then a 15% margin of error corresponds to plus or minus 1: the true average is likely to be 4, 5 or 6. Given that the question being asking is fundamentally subjective, and you have no idea whether Fred's rating of 5 and Wilma's rating of 5 mean the same thing, I think that plus or minus 1 is pretty much as good as you can reasonably expect. Additional samples just adds spurious precision that looks good but doesn't *mean* anything.

But what do I know? :)



> My suspicion is they just asked around their local department!
> But maybe I'm just overly suspicious...

Nah, I reckon you've hit the nail right on the head.



-- 
Steven

From dyoo at hashcollision.org  Wed Apr 10 02:17:41 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Tue, 9 Apr 2013 18:17:41 -0600
Subject: [Tutor] Impossible Else as Exception
In-Reply-To: <5164A9C8.6060405@pearwood.info>
References: <51646A65.5080708@gmail.com> <5164A9C8.6060405@pearwood.info>
Message-ID: <CAGZAPF6QCi=f=mcPL+m8Xy2QrWyXUbFSjwLX4vdcTqxiyYtFHg@mail.gmail.com>

>> if condition is 1:
>>      do something with 1
>> elif condition is 2:
>>      do something with 2
>> else: # Impossible unless the code above is flawed.
>>      Raise Exception
>
>
>
> The above isn't a great example, because the sample code *is* flawed.
> The short reason why it is flawed is this:
>
> You use identity tests (using `is`) instead of equality tests (using
> `==`) which makes the above code fragile and dependent on the exact
> version and implementation of Python being used.


I don't think we can say this.  The code above is not literal.
Otherwise, we should be technically obligated to raise the exact same
objection to "do something with 2".



Going back to the original question: perhaps an assertion here would
be sufficient.  Something like:

    assert False, "Impossible situation"

would document that the case analysis above should be technically
exhaustive, and that reaching the assertion should be treated as an
internal error.

From steve at pearwood.info  Wed Apr 10 02:17:55 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 10 Apr 2013 10:17:55 +1000
Subject: [Tutor] building a website with python
In-Reply-To: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
Message-ID: <5164AFB3.6090200@pearwood.info>

On 10/04/13 07:31, Benjamin Fishbein wrote:
> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet.
> I learned html, css, and javascript via codeacademy.org, but have never built a website.
> I would like to build it with Python, and was wondering if you could give me some pointers about what I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are all hosts basically the same.


Django is an excellent product but pretty heavyweight. Consider CherryPy for a lighter experience with a more gentle learning curve.

http://www.cherrypy.org/



-- 
Steven

From alan.gauld at btinternet.com  Wed Apr 10 02:29:57 2013
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Wed, 10 Apr 2013 01:29:57 +0100 (BST)
Subject: [Tutor] Chapter 3 Projects
In-Reply-To: <1365552412.1498.YahooMailNeo@web141006.mail.bf1.yahoo.com>
References: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com>
	<kio66h$cvn$1@ger.gmane.org>
	<1365552412.1498.YahooMailNeo@web141006.mail.bf1.yahoo.com>
Message-ID: <1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com>

Forwarded to group. Please use ReplyAll when responding to tutor posts.


>________________________________
> From: Mariel Jane Sanchez <zac_vanessa1fan at yahoo.ca>
>To: Alan Gauld <alan.gauld at btinternet.com> 
>Sent: Wednesday, 10 April 2013, 1:06
>Subject: Re: [Tutor] Chapter 3 Projects
> 
>
>
>Thank you so much, I finally figured out the 2nd project. I still have problems with 1 and 3 so I'll try to be more clear.?
>
>It would help if you posted your code. It shouldn't be long?and its much easier to see where you are getting confused if we can see the code!
Chapter 3 Booklet PDF is attached
>
>Chapter 3?
>Project 1 on page 90 on the PDF
>"1. Write a program that gets a score from the player and rates it on the following:
>- Given a score between 0-999, the program should display the message, 'Nothing to brag about."
>- Given a score between 1000-9999, the program should display the message, 'Good score.'
>- Given a score over 9999, the program should display the message, 'Very impressive!"
>- If the score is a negative number, the program should display the message, 'That is not a legal score!'"
>
>I'd do it like this

score = raw_input('score? ')
if score < 0: print 'That is not a legal score'
elif score > 9999: print 'Very impressive'
elif 9999 >= score >= 1000: print 'Good score.'
elif  # student to complete...


>
>I tried using range as another tutor suggested which would make sense since it's dealing with ranges but I still get the same result as before. Can you explain how to do this step by step, if you don't mind?
>
>You can use range by substituting the elif lines above with:

elif score in range(1000,10000): print 'Good score.'

Project 3 (Guess My Number code on page 35)
>"Modify the Guess My Number program from the chapter so that the player has only five guesses. If the player runs out of guesses, the program should end the game and display an appropriately chastising message"
>For my case, I somehow, accidentally programmed it to have only 5 tries and also put a message that says " You ran out of tries," which I think is a good progress. However, on the last try; when I put my guess, hit enter and got the guess wrong, the message loops.?
>
>I ?showed you the structure for this last time.
Without seeing your code I have no idea what?you did wrong.


When you first started on Python, how did you do this project so there's no loop at the end?
>
>I did not do those projects because I did not do the course that?you are doing.?
I did not in fact do any courses, I just read the official documents and made?
up my own projects. So I can't tell you how I did it. I can only comment on how I might?
do it now.
?
Alan Gauld
Author of the Learn To Program website

http://www.alan-g.me.uk/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/216fde34/attachment-0001.html>

From eryksun at gmail.com  Wed Apr 10 02:43:59 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 9 Apr 2013 20:43:59 -0400
Subject: [Tutor] Impossible Else as Exception
In-Reply-To: <CAGZAPF6QCi=f=mcPL+m8Xy2QrWyXUbFSjwLX4vdcTqxiyYtFHg@mail.gmail.com>
References: <51646A65.5080708@gmail.com> <5164A9C8.6060405@pearwood.info>
	<CAGZAPF6QCi=f=mcPL+m8Xy2QrWyXUbFSjwLX4vdcTqxiyYtFHg@mail.gmail.com>
Message-ID: <CACL+1atbdmv0xKXD0CZ_k8kM=K8bXPsqt-ZTeTfsWFzvOTzi4Q@mail.gmail.com>

On Tue, Apr 9, 2013 at 8:17 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
>
> Going back to the original question: perhaps an assertion here would
> be sufficient.  Something like:
>
>     assert False, "Impossible situation"

Like "if __debug__" statements, assert statements are skipped by the
compiler if optimization is enabled. If you want an AssertionError
here even for optimized code, then explicitly raise
AssertionError('Impossible situation').

From dfjennings at gmail.com  Wed Apr 10 04:03:27 2013
From: dfjennings at gmail.com (Don Jennings)
Date: Tue, 9 Apr 2013 22:03:27 -0400
Subject: [Tutor] building a website with python
In-Reply-To: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
Message-ID: <C52014F1-E32C-4711-911B-4F811ABD9242@gmail.com>


On Apr 9, 2013, at 5:31 PM, Benjamin Fishbein wrote:

> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet.
> I learned html, css, and javascript via codeacademy.org, but have never built a website.
> I would like to build it with Python,

So, are you really just wanting to use python to build a static site? If so, you can run a python web framework on your local machine and then deploy the static files to any decent host you find. For example, there are instructions for setting up this scenario using flask, jinja2 and markdown[1]. If you have experience with ReStructuredText (here's a comparison of the two markups [2]), it's fairly easy to use docutils to produce the html files.
 
> and was wondering if you could give me some pointers about what I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are all hosts basically the same.

If you do want python web apps, I've had pleasant results from webfaction.com (though I don't do anything terribly difficult :>).

You've gotten some good feedback, but I suspect you will get better information if you provide more information about your goals for the site.

Take care,
Don

[1] https://nicolas.perriault.net/code/2012/dead-easy-yet-powerful-static-website-generator-with-flask/
[2] http://www.unexpected-vortices.com/doc-notes/markdown-and-rest-compared.html

From doanviettrung at gmail.com  Wed Apr 10 04:29:55 2013
From: doanviettrung at gmail.com (DoanVietTrungAtGmail)
Date: Wed, 10 Apr 2013 12:29:55 +1000
Subject: [Tutor] Set Reply-To field to Tutor@python.org
In-Reply-To: <CAHXRGSNKkL5r7i99GeCvvwZg_FRGtqZ9u3z4OGXXdXsQyDoiHw@mail.gmail.com>
References: <CAHVvXxSebCecQj4ez6WaZF2CYG_2uvcqeDyiHx3z+U+XsjGCEQ@mail.gmail.com>
	<510721b3.4553420a.4681.fffff522@mx.google.com>
	<1359474293.64460.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<CAHXRGSNKkL5r7i99GeCvvwZg_FRGtqZ9u3z4OGXXdXsQyDoiHw@mail.gmail.com>
Message-ID: <CAFZXNMFvY_SwNH5_f-Ub-fVKjjHdVdufEthJ1YeKrsk_UimydQ@mail.gmail.com>

FWIW, I'd like to reverse my answer, and now I agree with Oscar's 29 Jan
suggestion to make "Reply-to-tutor-list" the default.

Lately, several times a tutor had to forward to the list an email meant for
the list but sent to him only, by mistake. On the other hand, the
wrote-to-1-person-but-mistakenly-sent-to-list scenario that I had in mind
is rarer, therefore Oscar's suggestion is better than my previous reply.

Trung


On Wed, Jan 30, 2013 at 6:33 AM, Nick W <pacificmorrowind at gmail.com> wrote:

> My personal opinion (with whatever limited weight that has on this list
> since I've only answered a few questions - and probably half of them I've
> accidentally only sent to the op)/how I read it is that RFC 2822 actually
> allows lists to set reply-to header; by my view the list software is
> forwarding to everyone else and therefor counts as the most recent
> sender/author. I admit that that is a somewhat different conclusion to
> others that I've read as to the meaning of 2822, but that seems logical to
> me and also my personal preference is for having the reply-to header be set
> to the list address.
> Nick
>
>
> On Tue, Jan 29, 2013 at 7:44 AM, Albert-Jan Roskam <fomcl at yahoo.com>wrote:
>
>>
>>
>> >
>> > To summarize existing opinions on this matter:
>> >
>> > http://marc.merlins.org/netrants/listreplyto.html
>> >
>> > You might want to familiarize yourself with existing literature on the
>> > matter before starting a new flame war.
>>
>> Hmmm... False alarm?
>>
>> Page blocked
>>
>> The page you've been trying to access was blocked.
>> Reason: Access Denied! The requested URL is a Spyware site.
>> Transaction ID is 5107F01CFF920603D57F.
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/1386462c/attachment.html>

From amitsaha.in at gmail.com  Wed Apr 10 04:38:40 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Wed, 10 Apr 2013 12:38:40 +1000
Subject: [Tutor] building a website with python
In-Reply-To: <C52014F1-E32C-4711-911B-4F811ABD9242@gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
	<C52014F1-E32C-4711-911B-4F811ABD9242@gmail.com>
Message-ID: <CANODV3=nA8MpTy_D-Q8ocrgWkFTjDmS6G4C=85QrtNPOyrU5BQ@mail.gmail.com>

On Wed, Apr 10, 2013 at 12:03 PM, Don Jennings <dfjennings at gmail.com> wrote:
>
> On Apr 9, 2013, at 5:31 PM, Benjamin Fishbein wrote:
>
>> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet.
>> I learned html, css, and javascript via codeacademy.org, but have never built a website.
>> I would like to build it with Python,
>
> So, are you really just wanting to use python to build a static site? If so, you can run a python web framework on your local machine and then deploy the static files to any decent host you find. For example, there are instructions for setting up this scenario using flask, jinja2 and markdown[1]. If you have experience with ReStructuredText (here's a comparison of the two markups [2]), it's fairly easy to use docutils to produce the html files.

Good suggestion. I wrote this article showing how you can do that
using Sphinx. Please take a look [1]. The advantage of using something
like Sphinx is that it gives you static HTML, which you can simply
copy and paste. As you will see in the article, it is also very easy
to upload your HTML to GitHub pages.

[1] http://amitsaha.github.io/site/notes/articles/sphinx/static_html.html

Hope it is a solution which suits you. Also, getting familiar with
Sphinx may also help you in your future Python projects - since it is
*the* de-facto standard for documenting Python projects.

Best,
Amit.

--
http://amitsaha.github.com/

From amitsaha.in at gmail.com  Wed Apr 10 04:47:09 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Wed, 10 Apr 2013 12:47:09 +1000
Subject: [Tutor] building a website with python
In-Reply-To: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
Message-ID: <CANODV3=nMKTyVFArg_q7H-x6oMrV_qm3HguncCNGZaYjqn62Pw@mail.gmail.com>

On Wed, Apr 10, 2013 at 7:31 AM, Benjamin Fishbein
<bfishbein79 at gmail.com> wrote:
> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet.
> I learned html, css, and javascript via codeacademy.org, but have never built a website.
> I would like to build it with Python, and was wondering if you could give me some pointers about what I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are all hosts basically the same.

Django is great, but like others have suggested, so called "micro"
frameworks may be a good start. I personally would suggest Flask [1].
The documentation is extensive and excellent.


[1] http://flask.pocoo.org/docs/

-Amit.

--
http://amitsaha.github.com/

From amitsaha.in at gmail.com  Wed Apr 10 04:50:34 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Wed, 10 Apr 2013 12:50:34 +1000
Subject: [Tutor] building a website with python
In-Reply-To: <CANODV3=nMKTyVFArg_q7H-x6oMrV_qm3HguncCNGZaYjqn62Pw@mail.gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
	<CANODV3=nMKTyVFArg_q7H-x6oMrV_qm3HguncCNGZaYjqn62Pw@mail.gmail.com>
Message-ID: <CANODV3=jw9RiKnvKs6=O2LuR98e7XKCoEONrAf6qic18VysWkA@mail.gmail.com>

On Wed, Apr 10, 2013 at 12:47 PM, Amit Saha <amitsaha.in at gmail.com> wrote:
> On Wed, Apr 10, 2013 at 7:31 AM, Benjamin Fishbein
> <bfishbein79 at gmail.com> wrote:
>> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my small business. Now I want to build a website. I acquired the domain name through godaddy.com (bookchicken.com) but have not found hosting yet.
>> I learned html, css, and javascript via codeacademy.org, but have never built a website.
>> I would like to build it with Python, and was wondering if you could give me some pointers about what I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are all hosts basically the same.
>
> Django is great, but like others have suggested, so called "micro"
> frameworks may be a good start. I personally would suggest Flask [1].
> The documentation is extensive and excellent.
>
>
> [1] http://flask.pocoo.org/docs/

And, I will add Frozen-Flask (http://pythonhosted.org/Frozen-Flask/),
which basically gives you a set of static files, which you can just
dump on any host with no "special" features. I haven't tried it
myself, though.

-Amit.


--
http://amitsaha.github.com/

From bfishbein79 at gmail.com  Wed Apr 10 05:07:51 2013
From: bfishbein79 at gmail.com (Benjamin Fishbein)
Date: Tue, 9 Apr 2013 22:07:51 -0500
Subject: [Tutor] building a website with python
In-Reply-To: <C52014F1-E32C-4711-911B-4F811ABD9242@gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
	<C52014F1-E32C-4711-911B-4F811ABD9242@gmail.com>
Message-ID: <A3983D31-87D0-42B3-A778-D55DDE3BC160@gmail.com>

> 
> You've gotten some good feedback, but I suspect you will get better information if you provide more information about your goals for the site.
> 

Thanks for your help, everyone. There are some specific things I want the site to do, and I'm not sure which would be the best developing tool or hosting for these.
The python software I developed is for selling used books.
It takes book ISBN numbers as input and returns the best prices being offered.
It uses the selenium module...I'm not sure how that would translate into a website.
There are many websites that offer similar book price comparisons, but mine is different...it's user-friendly. Any volunteer at a thrift shop or library can use it...just a series of simple directions and yes/no questions, taking the user all the way from scanning or typing in an ISBN to dropping the parcel off at the post office. (The local libraries I worked with more than doubled their used-book revenues.) I want to expand this nationwide, and bookchicken.com seems to be the way to do it.
So much of the program is simple enough. But there's two parts of the program that I anticipate being important to what host, development tool I use:
1. ISBNs (the books the thrift shop/ library has) being sent to various websites and returning the data to my site to be analyzed by my program.
2. Maneuvering through the website of the company buying the books. I don't want to send the user off to a warehouse's site with a list of books to sell to them. They'll still be entering their address and name, but it'll be on my site, that I then send to the warehouse's page, get a packing slip and shipping label from the warehouse, and give these documents to the user to print out.

I'm not sure if this changes anyone's ideas about which host/ developer I should use. Please let me know.
Thanks,
Ben


 



From davea at davea.name  Wed Apr 10 05:11:40 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 09 Apr 2013 23:11:40 -0400
Subject: [Tutor] Chapter 3 Projects
In-Reply-To: <1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com>
References: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com>
	<kio66h$cvn$1@ger.gmane.org>
	<1365552412.1498.YahooMailNeo@web141006.mail.bf1.yahoo.com>
	<1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com>
Message-ID: <5164D86C.80107@davea.name>

On 04/09/2013 08:29 PM, ALAN GAULD wrote:
> Forwarded to group. Please use ReplyAll when responding to tutor posts.
>
>
>> ________________________________
>> From: Mariel Jane Sanchez <zac_vanessa1fan at yahoo.ca>
>> To: Alan Gauld <alan.gauld at btinternet.com>
>> Sent: Wednesday, 10 April 2013, 1:06
>> Subject: Re: [Tutor] Chapter 3 Projects
>>
>>
>>
>> Thank you so much, I finally figured out the 2nd project. I still have problems with 1 and 3 so I'll try to be more clear.
>>
>> It would help if you posted your code. It shouldn't be long and its much easier to see where you are getting confused if we can see the code!
> Chapter 3 Booklet PDF is attached
>>
>> Chapter 3
>> Project 1 on page 90 on the PDF
>> "1. Write a program that gets a score from the player and rates it on the following:
>> - Given a score between 0-999, the program should display the message, 'Nothing to brag about."
>> - Given a score between 1000-9999, the program should display the message, 'Good score.'
>> - Given a score over 9999, the program should display the message, 'Very impressive!"
>> - If the score is a negative number, the program should display the message, 'That is not a legal score!'"
>>
>> I'd do it like this
>
> score = raw_input('score? ')

That would need to be:
     score = int(raw_input('score? ')

> if score < 0: print 'That is not a legal score'
> elif score > 9999: print 'Very impressive'
> elif 9999 >= score >= 1000: print 'Good score.'
> elif  # student to complete...
>
>
>>
>> I tried using range as another tutor suggested which would make sense since it's dealing with ranges but I still get the same result as before. Can you explain how to do this step by step, if you don't mind?
>>
>> You can use range by substituting the elif lines above with:
>
> elif score in range(1000,10000): print 'Good score.'
>
> Project 3 (Guess My Number code on page 35)
>> "Modify the Guess My Number program from the chapter so that the player has only five guesses. If the player runs out of guesses, the program should end the game and display an appropriately chastising message"
>> For my case, I somehow, accidentally programmed it to have only 5 tries and also put a message that says " You ran out of tries," which I think is a good progress. However, on the last try; when I put my guess, hit enter and got the guess wrong, the message loops.
>>
>> I  showed you the structure for this last time.
> Without seeing your code I have no idea what you did wrong.
>
>
> When you first started on Python, how did you do this project so there's no loop at the end?
>>
>> I did not do those projects because I did not do the course that you are doing.
> I did not in fact do any courses, I just read the official documents and made
> up my own projects. So I can't tell you how I did it. I can only comment on how I might
> do it now.
>
> Alan Gauld
> Author of the Learn To Program website
>
> http://www.alan-g.me.uk/
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
DaveA

From wolfrage8765 at gmail.com  Wed Apr 10 08:18:28 2013
From: wolfrage8765 at gmail.com (Jordan)
Date: Wed, 10 Apr 2013 08:18:28 +0200
Subject: [Tutor] Impossible Else as Exception
In-Reply-To: <CACL+1atbdmv0xKXD0CZ_k8kM=K8bXPsqt-ZTeTfsWFzvOTzi4Q@mail.gmail.com>
References: <51646A65.5080708@gmail.com> <5164A9C8.6060405@pearwood.info>
	<CAGZAPF6QCi=f=mcPL+m8Xy2QrWyXUbFSjwLX4vdcTqxiyYtFHg@mail.gmail.com>
	<CACL+1atbdmv0xKXD0CZ_k8kM=K8bXPsqt-ZTeTfsWFzvOTzi4Q@mail.gmail.com>
Message-ID: <51650434.5020906@gmail.com>

Thank you all for the feedback and suggestions.  I have never used an 
assertion, before so I will read up on the concept.  But this last email 
about the optimizations makes me want to go with an AssertionError 
exception, since assert is skipped if the compiler is told to optimize.
Alan you are right, the code should be better tested, but test driven 
development seems like it would take me forever to complete even small 
tasks, there is so much to be tested.  I have limited time to program 
with my wife and kids, but do you think test driven development is still 
the way to go?

On 04/10/2013 02:43 AM, eryksun wrote:
> On Tue, Apr 9, 2013 at 8:17 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
>> Going back to the original question: perhaps an assertion here would
>> be sufficient.  Something like:
>>
>>      assert False, "Impossible situation"
> Like "if __debug__" statements, assert statements are skipped by the
> compiler if optimization is enabled. If you want an AssertionError
> here even for optimized code, then explicitly raise
> AssertionError('Impossible situation').
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From alan.gauld at btinternet.com  Wed Apr 10 10:10:16 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 10 Apr 2013 09:10:16 +0100
Subject: [Tutor] Impossible Else as Exception
In-Reply-To: <51650434.5020906@gmail.com>
References: <51646A65.5080708@gmail.com> <5164A9C8.6060405@pearwood.info>
	<CAGZAPF6QCi=f=mcPL+m8Xy2QrWyXUbFSjwLX4vdcTqxiyYtFHg@mail.gmail.com>
	<CACL+1atbdmv0xKXD0CZ_k8kM=K8bXPsqt-ZTeTfsWFzvOTzi4Q@mail.gmail.com>
	<51650434.5020906@gmail.com>
Message-ID: <kk36p4$3o9$1@ger.gmane.org>

On 10/04/13 07:18, Jordan wrote:

> Alan you are right, the code should be better tested, but test driven
> development seems like it would take me forever to complete even small
> tasks, there is so much to be tested.  I have limited time to program
> with my wife and kids, but do you think test driven development is still
> the way to go?

Do you want to spend your time writing tests that identify bugs 
immediately or spend your time debugging code after you've written it 
and every time you modify it?

A lot depends on how often you will be going back to the code in the 
future. If this is a use once throw away project then TDD may be 
overkill. If you are likely to want to enhance it in the future TDD
is an investment to save time.

I confess I don't use TDD all of the time and even with TDD errors will 
still sneak through. But TDD improves your chances of finding them early 
considerably.

It will usually take the same amount of total time, its just a question 
of how you use it.

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


From alan.gauld at btinternet.com  Wed Apr 10 10:14:13 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 10 Apr 2013 09:14:13 +0100
Subject: [Tutor] Chapter 3 Projects
In-Reply-To: <5164D86C.80107@davea.name>
References: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com>
	<kio66h$cvn$1@ger.gmane.org>
	<1365552412.1498.YahooMailNeo@web141006.mail.bf1.yahoo.com>
	<1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com>
	<5164D86C.80107@davea.name>
Message-ID: <kk370g$3o9$2@ger.gmane.org>

On 10/04/13 04:11, Dave Angel wrote:

>>> I'd do it like this
>>
>> score = raw_input('score? ')
>
> That would need to be:
>      score = int(raw_input('score? ')


Oops, yes. Good catch.


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


From arijit.ukil at tcs.com  Wed Apr 10 10:57:17 2013
From: arijit.ukil at tcs.com (Arijit Ukil)
Date: Wed, 10 Apr 2013 14:27:17 +0530
Subject: [Tutor] running python from windows command prompt
In-Reply-To: <CACzNyA21cNxYW9xcAbaWJC2v+6G6X8_PU5nymVxoY9ygDxui=g@mail.gmail.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>	<CACL+1at=8=7voXJv9dzBMPt8VBhoFPq4FTXM7pecrsrXYpR4Dg@mail.gmail.com>
	<CACzNyA2h8+BSH_27+yNny4ijDQJ-f6t9BRWh2gNh6ow51neGrw@mail.gmail.com>	<CAPM-O+x+3M4uZqCnO0Eq=sDfKNeg13Gmuv7-_HNsXbN4GgQDTg@mail.gmail.com>
	<CACzNyA21cNxYW9xcAbaWJC2v+6G6X8_PU5nymVxoY9ygDxui=g@mail.gmail.com>
Message-ID: <OF1432F962.35AF176B-ON65257B49.002F4DA4-65257B49.00313102@tcs.com>

I like to run a python program "my_python.py" from windows command prompt. 
This program ( a function called testing) takes input as block data (say 
data = [1,2,3,4] and outputs processed single data.

import math

def avrg(data):
    return sum(data)/len(data)

def testing (data):
    val = avrg(data)
    out = pow(val,2)
    return out

Pls help.

Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.ukil at tcs.com
Website: http://www.tcs.com
____________________________________________
Experience certainty.   IT Services
                        Business Solutions
                        Outsourcing
____________________________________________
=====-----=====-----=====
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/353323cb/attachment.html>

From davea at davea.name  Wed Apr 10 13:52:30 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 10 Apr 2013 07:52:30 -0400
Subject: [Tutor] Impossible Else as Exception
In-Reply-To: <51650434.5020906@gmail.com>
References: <51646A65.5080708@gmail.com> <5164A9C8.6060405@pearwood.info>
	<CAGZAPF6QCi=f=mcPL+m8Xy2QrWyXUbFSjwLX4vdcTqxiyYtFHg@mail.gmail.com>
	<CACL+1atbdmv0xKXD0CZ_k8kM=K8bXPsqt-ZTeTfsWFzvOTzi4Q@mail.gmail.com>
	<51650434.5020906@gmail.com>
Message-ID: <5165527E.8040003@davea.name>

On 04/10/2013 02:18 AM, Jordan wrote:
> Thank you all for the feedback and suggestions.  I have never used an
> assertion, before so I will read up on the concept.


One comment about assertion.  Even though an optimized run will ignore 
the assertion itself, it can save a (small) amount of time avoiding any 
other overhead "preparing" for the assertion.  So I'd make your if/elif 
logic something like this:



if condition == 1:
     do something with 1
else:   #Note, condition must be 2, unless something above is flawed
     assert(condition==2, "Condition must be 1 or 2, something's wrong")
     do something with 2


One more comment I didn't notice anybody else point out.  Many times, 
instead of hoping the code remains consistent, you can make it much more 
likely by changing types.  For example, instead of naming the conditions 
1 and 2, name then True and False.  Now, the test becomes:

if condition:
     do something with 1
else:
     do something with 2

This isn't as perfect an answer as with typed languages, because 
somebody can slip in some other type.

-- 
DaveA

From davea at davea.name  Wed Apr 10 14:14:21 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 10 Apr 2013 08:14:21 -0400
Subject: [Tutor] running python from windows command prompt
In-Reply-To: <OF1432F962.35AF176B-ON65257B49.002F4DA4-65257B49.00313102@tcs.com>
References: <CACzNyA0k14+DSzhApf60T6UN3K3h6OOZ1UBMqir4OJ0UruwQnA@mail.gmail.com>	<CACL+1at=8=7voXJv9dzBMPt8VBhoFPq4FTXM7pecrsrXYpR4Dg@mail.gmail.com>
	<CACzNyA2h8+BSH_27+yNny4ijDQJ-f6t9BRWh2gNh6ow51neGrw@mail.gmail.com>	<CAPM-O+x+3M4uZqCnO0Eq=sDfKNeg13Gmuv7-_HNsXbN4GgQDTg@mail.gmail.com>
	<CACzNyA21cNxYW9xcAbaWJC2v+6G6X8_PU5nymVxoY9ygDxui=g@mail.gmail.com>
	<OF1432F962.35AF176B-ON65257B49.002F4DA4-65257B49.00313102@tcs.com>
Message-ID: <5165579D.4090609@davea.name>

(Please don't hijack a thread with an unrelated question.  You're no 
doing yourself any favors, as any decent thread-viewer will hide your 
new subject line, and group the whole thread with its original title. 
That can cause your query to be ignored by many of the readers.)

To start a new thread, send the email to tutor at pyhon.org.

On 04/10/2013 04:57 AM, Arijit Ukil wrote:
> I like to run a python program "my_python.py" from windows command
> prompt. This program ( a function called testing) takes input as block
> data (say data = [1,2,3,4] and outputs processed single data.
>
> import math
>
> def avrg(data):
>      return sum(data)/len(data)
>
> def testing (data):
>      val = avrg(data)
>      out = pow(val,2)
>      return out
>

This program is missing some top-level code, so nobody is calling 
testing().  As it stands, it does nothing visible to the user.

You say the program should "take input" from the user, but there are at 
least 3 ways to do that.

1) The user could edit the source file, adding lines like:

mydata = (1, 9,43,7)
print ("results: %d" % testing(mydata) )

2) The user could put the source data into a file, such as a csv file
3) The user could have the parameters on the command line, after the 
script name.
    python my_python.py 1 9 43 7

Each of 2 and 3 require you to add some logic to process the data file 
and/or commandline.

Please specify the problem more completely, and show us what you tried, 
and somebody will probably be able to help you.

Also specify the Python version, as it can make a difference.  For 
example, avrg() function in Python 2.7 assumes either that its arguments 
include a float, or that you want only an integer result.  In Python 3, 
it'll switch to float.

-- 
DaveA

From arijit.ukil at tcs.com  Wed Apr 10 14:32:47 2013
From: arijit.ukil at tcs.com (Arijit Ukil)
Date: Wed, 10 Apr 2013 18:02:47 +0530
Subject: [Tutor] Running python from windows command prompt
Message-ID: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>

I like to run a python program "my_python.py" from windows command prompt. 
This program ( a function called testing) takes input as block data (say 
data = [1,2,3,4] and outputs processed single data. 

import math 

def avrg(data): 
    return sum(data)/len(data) 

def testing (data): 
    val = avrg(data) 
    out = pow(val,2) 
    return out 

I am using python 2.6. My intention is to run from windows command prompt 
as

python my_python.py 1 3  2

However I am getting error: No such file in the directory, Errno 21

Pls help.

Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.ukil at tcs.com
Website: http://www.tcs.com
____________________________________________
Experience certainty.   IT Services
                        Business Solutions
                        Outsourcing
____________________________________________
=====-----=====-----=====
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/fc597c87/attachment.html>

From amitsaha.in at gmail.com  Wed Apr 10 14:37:06 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Wed, 10 Apr 2013 22:37:06 +1000
Subject: [Tutor] Running python from windows command prompt
In-Reply-To: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
References: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
Message-ID: <CANODV3nhk-Pj1rwk64_QoTuNxr3aS+_47rz-fNArhbSzw_kbtw@mail.gmail.com>

On Wed, Apr 10, 2013 at 10:32 PM, Arijit Ukil <arijit.ukil at tcs.com> wrote:
> I like to run a python program "my_python.py" from windows command prompt.
> This program ( a function called testing) takes input as block data (say
> data = [1,2,3,4] and outputs processed single data.
>
> import math
>
> def avrg(data):
>    return sum(data)/len(data)
>
> def testing (data):
>    val = avrg(data)
>    out = pow(val,2)
>    return out
>
> I am using python 2.6. My intention is to run from windows command prompt as

Why not Python 2.7 or Python 3.3 ?

>
> python my_python.py 1 3  2
>
> However I am getting error: No such file in the directory, Errno 21

Have you set the Windows Path variable correctly? Do you see IDLE in
your programs menu?

-Amit.


--
http://amitsaha.github.com/

From amitsaha.in at gmail.com  Wed Apr 10 14:43:18 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Wed, 10 Apr 2013 22:43:18 +1000
Subject: [Tutor] Running python from windows command prompt
In-Reply-To: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
References: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
Message-ID: <CANODV3nmu7CgzMBZ9rEygZJp9M=JvOWpZF=mPdorSgR4CA0toA@mail.gmail.com>

On Wed, Apr 10, 2013 at 10:32 PM, Arijit Ukil <arijit.ukil at tcs.com> wrote:
> I like to run a python program "my_python.py" from windows command prompt.
> This program ( a function called testing) takes input as block data (say
> data = [1,2,3,4] and outputs processed single data.
>
> import math
>
> def avrg(data):
>    return sum(data)/len(data)
>
> def testing (data):
>    val = avrg(data)
>    out = pow(val,2)
>    return out
>
> I am using python 2.6. My intention is to run from windows command prompt as
>
> python my_python.py 1 3  2

I am hoping this is not your complete program. What tutorial are you
following? Can you please paste complete programs?

-Amit.

--
http://amitsaha.github.com/

From davea at davea.name  Wed Apr 10 14:50:44 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 10 Apr 2013 08:50:44 -0400
Subject: [Tutor] Running python from windows command prompt
In-Reply-To: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
References: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
Message-ID: <51656024.90803@davea.name>

On 04/10/2013 08:32 AM, Arijit Ukil wrote:
> I like to run a python program "my_python.py" from windows command
> prompt. This program ( a function called testing) takes input as block
> data (say data = [1,2,3,4] and outputs processed single data.
>
> import math
>
> def avrg(data):
>     return sum(data)/len(data)
>
> def testing (data):
>     val = avrg(data)
>     out = pow(val,2)
>     return out
>
> I am using python 2.6. My intention is to run from windows command
> prompt as
>
> python my_python.py 1 3  2
>
> However I am getting error: No such file in the directory, Errno 21
>
> Pls help.
>

Interesting error message.  So it really doesn't identify what file, nor 
in what directory it's looking?

Windows will search the path for python, but it's up to you to specify 
the right directory for data files.

Presumably that indicates that my_python.py is not in the current 
directory.  Is it?

If that's the problem, you can either change to the right directory (cd 
  mysource)  or you can give an explicit path on the command line

python path\to\my_python.py  1 3 2

It's frequently useful to paste the relevant portion of the commandline 
into your message.  Don't paraphrase.

-- 
DaveA

From woody544 at gmail.com  Wed Apr 10 16:44:09 2013
From: woody544 at gmail.com (Woody 544)
Date: Wed, 10 Apr 2013 10:44:09 -0400
Subject: [Tutor] File not found error, but it is in the folder!
Message-ID: <CAPwGs2rZJ57dG9-4XCgf2CK2KZkUprvfgJ0LgE4oUJ5dKiO7CQ@mail.gmail.com>

I have a script that worked before I moved it to another folder.  I
cannot understand why I am getting a 'No such file or directory'
error, when the file is in the folder.

Any clues would be much appreciated.  Thanks!

MJ

Here is a copy and paste of the script up to the error, output/error
and a check for the file:

SCRIPT:
import os, string, codecs
os.chdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS')

folder = 'W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses'
files = os.listdir(folder)

#os.walk(folder)

fy13q1dict = {'country' : 'countryname', 'title':'titlename',
'travel':'traveldata',
'publications':'pubdata','conferences':'confdata','highlights':'higlightdata','upcoming':'upcomingdata'}
countryname = ()
titlename = ()

for i in files:
    fy13q1dict = {'country' : 'countryname', 'title':'titlename'}
    fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
    data = str(fp.read())
    data = data.replace('\xa0',' ')
    data = data.split()

OUTPUT:
>>>

Traceback (most recent call last):
  File "W:\BEP\DOS reports\Q1 FY13\BEP_Tool4DOS\bep_dos_tool.py", line
22, in <module>
    fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
  File "C:\Python27\lib\codecs.py", line 881, in open
    file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 2] No such file or directory: 'Algeria_688_RVF.txt'

CHECK FOR FILE IN FOLDER:
>>> os.listdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses')
['Algeria_688_RVF.txt', 'Egypt_31060_RVFEnvir

From bgailer at gmail.com  Wed Apr 10 16:31:26 2013
From: bgailer at gmail.com (bob gailer)
Date: Wed, 10 Apr 2013 10:31:26 -0400
Subject: [Tutor] Reading Program
In-Reply-To: <BAY401-EAS102DF14AD2085DE1744539F8DC50@phx.gbl>
References: <BAY401-EAS102DF14AD2085DE1744539F8DC50@phx.gbl>
Message-ID: <516577BE.6040702@gmail.com>

On 4/8/2013 2:58 PM, Donald Dietrich wrote:
> I am just new to python programing, but would like some help 
> developing a program for "flow reading"  What I would like the program 
> to do is use any  .txt file like micorsoft word .txt file and flow the 
> words across the screen one at time until the file is come to the end. 
> I would also like to control the rate (time) of flow. Do you think you 
> can help me.
To Tutors:

I had a phone chat with Donald yesterday. Summary:
Win 8, IDLE, Python 3.1.

Working his way thru Python for Absolute Beginner.

He is seeking other books as well.

To Donald:

Here's the easiest way to create a text file:

In IDLE: File -> New Window
Enter 2 lines with 2 words on each line.
File -> Save:
   File name: test1.txt
   Save as type: Text files (*.txt)

Here's an interactive session showing some ideas:

In the Python Shell (read a file)
 >>> txt = open("test1.txt")
 >>> print(txt.read())
you should see the file contents here

In the Python Shell (parse the file into words)
 >>> txt = open("test1.txt")
 >>> print(txt.read().split())
you should see a list of the words in the file

In the Python Shell (display the words with a time delay)
 >>> txt = open("test1.txt")
 >>> for word in txt.read().split():
     print(word)
     time.sleep(.4)
now press enter again and you should see the words appear with a 0.4 
second delay.

Hope this helps get you going. Feel free to come back with questions.


-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/5e1140b1/attachment.html>

From bcloete at gmail.com  Wed Apr 10 17:06:08 2013
From: bcloete at gmail.com (Bradley Cloete)
Date: Wed, 10 Apr 2013 17:06:08 +0200
Subject: [Tutor] building a website with python
In-Reply-To: <A3983D31-87D0-42B3-A778-D55DDE3BC160@gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
	<C52014F1-E32C-4711-911B-4F811ABD9242@gmail.com>
	<A3983D31-87D0-42B3-A778-D55DDE3BC160@gmail.com>
Message-ID: <CACGgnMA211ACmCL8PtfHswpzpP4yKwDOtB5P2XQZjpkPGNtEVQ@mail.gmail.com>

On Wed, Apr 10, 2013 at 5:07 AM, Benjamin Fishbein <bfishbein79 at gmail.com>wrote:

> >
> > You've gotten some good feedback, but I suspect you will get better
> information if you provide more information about your goals for the site.
> >
>
> Thanks for your help, everyone. There are some specific things I want the
> site to do, and I'm not sure which would be the best developing tool or
> hosting for these.
> The python software I developed is for selling used books.
> It takes book ISBN numbers as input and returns the best prices being
> offered.
> It uses the selenium module...I'm not sure how that would translate into a
> website.
> There are many websites that offer similar book price comparisons, but
> mine is different...it's user-friendly. Any volunteer at a thrift shop or
> library can use it...just a series of simple directions and yes/no
> questions, taking the user all the way from scanning or typing in an ISBN
> to dropping the parcel off at the post office. (The local libraries I
> worked with more than doubled their used-book revenues.) I want to expand
> this nationwide, and bookchicken.com seems to be the way to do it.
> So much of the program is simple enough. But there's two parts of the
> program that I anticipate being important to what host, development tool I
> use:
> 1. ISBNs (the books the thrift shop/ library has) being sent to various
> websites and returning the data to my site to be analyzed by my program.
> 2. Maneuvering through the website of the company buying the books. I
> don't want to send the user off to a warehouse's site with a list of books
> to sell to them. They'll still be entering their address and name, but
> it'll be on my site, that I then send to the warehouse's page, get a
> packing slip and shipping label from the warehouse, and give these
> documents to the user to print out.
>
> I'm not sure if this changes anyone's ideas about which host/ developer I
> should use. Please let me know.
> Thanks,
> Ben
>
>

The Django website has a list of recommended hosts.

https://code.djangoproject.com/wiki/DjangoFriendlyWebHosts

also...

http://djangohosting.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/897289e6/attachment.html>

From torkamani at gmail.com  Wed Apr 10 17:16:22 2013
From: torkamani at gmail.com (Ali Torkamani)
Date: Wed, 10 Apr 2013 08:16:22 -0700
Subject: [Tutor] Phyton script for fasta file (seek help)
In-Reply-To: <CAGZAPF5pr4VBG1RA_94hMQrM2ECR_znWztEha1uRZeta6nBvXg@mail.gmail.com>
References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com>
	<CAGZAPF5pr4VBG1RA_94hMQrM2ECR_znWztEha1uRZeta6nBvXg@mail.gmail.com>
Message-ID: <CAEmF0k6rvtrXFESOs=ESz0sB_w0upo8Jas=iOGq--sqq9oK+NA@mail.gmail.com>

I have written the following function for reading fasta files, I hope this
helps:

Ali

def ReadFasta(filename):

    dictFasta=dict()
    prevLine='';
    try:

        f = open(filename, "r")

        for line in f:
            print line
            line=line.lower()
            line=line.strip()
            if len(line)==0: continue
            if (not(line[0]>='a' and line[0]<='z')) and line[0]!='>':
continue
            if line[0]=='>':
                prevLine=line[1:]
                dictFasta[prevLine]=''
            else:
                dictFasta[prevLine]=dictFasta[prevLine]+line

        f.close()
    except IOError:
        print 'error opening %s'%(filename)
        pass
    return dictFasta
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/8edfaf66/attachment.html>

From breamoreboy at yahoo.co.uk  Wed Apr 10 17:23:59 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Wed, 10 Apr 2013 16:23:59 +0100
Subject: [Tutor] File not found error, but it is in the folder!
In-Reply-To: <CAPwGs2rZJ57dG9-4XCgf2CK2KZkUprvfgJ0LgE4oUJ5dKiO7CQ@mail.gmail.com>
References: <CAPwGs2rZJ57dG9-4XCgf2CK2KZkUprvfgJ0LgE4oUJ5dKiO7CQ@mail.gmail.com>
Message-ID: <kk3vv3$oqm$1@ger.gmane.org>

On 10/04/2013 15:44, Woody 544 wrote:
> I have a script that worked before I moved it to another folder.  I
> cannot understand why I am getting a 'No such file or directory'
> error, when the file is in the folder.
>
> Any clues would be much appreciated.  Thanks!
>
> MJ
>
> Here is a copy and paste of the script up to the error, output/error
> and a check for the file:
>
> SCRIPT:
> import os, string, codecs
> os.chdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS')
>
> folder = 'W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses'
> files = os.listdir(folder)
>
> #os.walk(folder)
>
> fy13q1dict = {'country' : 'countryname', 'title':'titlename',
> 'travel':'traveldata',
> 'publications':'pubdata','conferences':'confdata','highlights':'higlightdata','upcoming':'upcomingdata'}
> countryname = ()
> titlename = ()
>
> for i in files:
>      fy13q1dict = {'country' : 'countryname', 'title':'titlename'}
>      fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
>      data = str(fp.read())
>      data = data.replace('\xa0',' ')
>      data = data.split()
>
> OUTPUT:
>>>>
>
> Traceback (most recent call last):
>    File "W:\BEP\DOS reports\Q1 FY13\BEP_Tool4DOS\bep_dos_tool.py", line
> 22, in <module>
>      fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
>    File "C:\Python27\lib\codecs.py", line 881, in open
>      file = __builtin__.open(filename, mode, buffering)
> IOError: [Errno 2] No such file or directory: 'Algeria_688_RVF.txt'
>
> CHECK FOR FILE IN FOLDER:
>>>> os.listdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses')
> ['Algeria_688_RVF.txt', 'Egypt_31060_RVFEnvir
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Your os.chdir call doesn't have the FY13Q1_responses directory on the end.

A slight aside, it's far easier to write Windows file paths with raw 
strings or even use forward slashes.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From eryksun at gmail.com  Wed Apr 10 17:29:02 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 10 Apr 2013 11:29:02 -0400
Subject: [Tutor] Running python from windows command prompt
In-Reply-To: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
References: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
Message-ID: <CACL+1au5uE9TAri5sSse8yAB-10qjJU3F+YgfXHtEVDTVoUK3Q@mail.gmail.com>

On Wed, Apr 10, 2013 at 8:32 AM, Arijit Ukil <arijit.ukil at tcs.com> wrote:
>
> python my_python.py 1 3  2

Adding Python's installation directory to PATH is for starting the
interpreter with specific options (-O, -vv, etc), running a module on
Python's sys.path (-m), running a command (-c), or starting an
interactive shell. Otherwise you can run the script directly:

    my_python.py 1 3 2

With pylauncher (py.exe) installed to %WINDIR% you don't even need the
installation directory on PATH. See PEP 397.

http://www.python.org/dev/peps/pep-0397
http://bitbucket.org/vinay.sajip/pylauncher

I still add the scripts directory to PATH, which in your case might be
"C:\Python26\Scripts". I recommend you do this if you want
my_python.py to run as a command-line utility (of course you first
have to copy my_python.py to the scripts directory). You can even
avoid using the .py extension if you add .PY to the PATHEXT
environment variable.

Beyond the Windows details, your script needs to import sys and get
the argument list, sys.argv[1:]. The arguments are strings, so you'll
need to convert to float or int as required. Also, why do you import
the math module? You're not using it.

From dyoo at hashcollision.org  Wed Apr 10 17:32:55 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 10 Apr 2013 09:32:55 -0600
Subject: [Tutor] Phyton script for fasta file (seek help)
In-Reply-To: <CAEmF0k6rvtrXFESOs=ESz0sB_w0upo8Jas=iOGq--sqq9oK+NA@mail.gmail.com>
References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com>
	<CAGZAPF5pr4VBG1RA_94hMQrM2ECR_znWztEha1uRZeta6nBvXg@mail.gmail.com>
	<CAEmF0k6rvtrXFESOs=ESz0sB_w0upo8Jas=iOGq--sqq9oK+NA@mail.gmail.com>
Message-ID: <CAGZAPF5x8zarnX+Qwg4LXd4+Y8D93ndZPE0vmjBJ49XrD1bjJQ@mail.gmail.com>

Hi Ali,

Again, I recommend not reinventing a FASTA parser unless you really
need something custom here.  In this particular case, the function
ReadFasta here is slow on large inputs.  The culprit is the set of
lines:

            if line[0]=='>':
                prevLine=line[1:]
                dictFasta[prevLine]=''
            else:
                dictFasta[prevLine]=dictFasta[prevLine]+line
which looks innocent on its own, but it is an O(n^2) string-appending
algorithm if we walk across a very long sequence such as a
chromosome. The folks who have written the Biopython FASTA parser have
almost certainly already considered this pitfall.

From sayanchatterjee at gmail.com  Wed Apr 10 17:44:50 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Wed, 10 Apr 2013 21:14:50 +0530
Subject: [Tutor] Appending an extra column in a data file
Message-ID: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>

Dear All,

I have some data files with numpy arrays stored in it in 2 columns. I want
to add a third column with just floating point numbers(not numpy array) and
plot them later with Matplotlib in 3d. How is it done? Could you please
illuminate me?

Bests,
Sayan

-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/4d2862ff/attachment.html>

From walksloud at gmail.com  Wed Apr 10 17:53:12 2013
From: walksloud at gmail.com (Andre' Walker-Loud)
Date: Wed, 10 Apr 2013 08:53:12 -0700
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
Message-ID: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>

Hi Sayan,

This question would be better suited to the matplotlib list.
Also, a more precise description of your existing data, and what you hope it would look like would make it easier to help answer your question.  Eg., from your description, it is not clear if your existing data is in a table, and in the table you have numpy arrays, or if you have one numpy array of rank 2 with data in it.


Regards,

Andre



On Apr 10, 2013, at 8:44 AM, Sayan Chatterjee wrote:

> Dear All,
> 
> I have some data files with numpy arrays stored in it in 2 columns. I want to add a third column with just floating point numbers(not numpy array) and plot them later with Matplotlib in 3d. How is it done? Could you please illuminate me?
> 
> Bests,
> Sayan
> 
> -- 
> 
> 
> --------------------------------------------------------------------------
> Sayan  Chatterjee
> Dept. of Physics and Meteorology
> IIT Kharagpur
> Lal Bahadur Shastry Hall of Residence
> Room AB 205
> Mob: +91 9874513565
> blog: www.blissprofound.blogspot.com
> 
> Volunteer , Padakshep
> www.padakshep.org
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From davea at davea.name  Wed Apr 10 18:22:29 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 10 Apr 2013 12:22:29 -0400
Subject: [Tutor] File not found error, but it is in the folder!
In-Reply-To: <CAPwGs2rZJ57dG9-4XCgf2CK2KZkUprvfgJ0LgE4oUJ5dKiO7CQ@mail.gmail.com>
References: <CAPwGs2rZJ57dG9-4XCgf2CK2KZkUprvfgJ0LgE4oUJ5dKiO7CQ@mail.gmail.com>
Message-ID: <516591C5.9020207@davea.name>

On 04/10/2013 10:44 AM, Woody 544 wrote:
> I have a script that worked before I moved it to another folder.  I
> cannot understand why I am getting a 'No such file or directory'
> error, when the file is in the folder.
>
> Any clues would be much appreciated.  Thanks!
>
> MJ
>
> Here is a copy and paste of the script up to the error, output/error
> and a check for the file:
>
> SCRIPT:
> import os, string, codecs
> os.chdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS')
>
> folder = 'W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses'
> files = os.listdir(folder)
>
> #os.walk(folder)
>
> fy13q1dict = {'country' : 'countryname', 'title':'titlename',
> 'travel':'traveldata',
> 'publications':'pubdata','conferences':'confdata','highlights':'higlightdata','upcoming':'upcomingdata'}
> countryname = ()
> titlename = ()
>
> for i in files:
>      fy13q1dict = {'country' : 'countryname', 'title':'titlename'}
>      fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
>      data = str(fp.read())
>      data = data.replace('\xa0',' ')
>      data = data.split()
>
> OUTPUT:
>>>>
>
> Traceback (most recent call last):
>    File "W:\BEP\DOS reports\Q1 FY13\BEP_Tool4DOS\bep_dos_tool.py", line
> 22, in <module>
>      fp = codecs.open(i,mode='rb',encoding=None,errors='replace',buffering=1)
>    File "C:\Python27\lib\codecs.py", line 881, in open
>      file = __builtin__.open(filename, mode, buffering)
> IOError: [Errno 2] No such file or directory: 'Algeria_688_RVF.txt'
>
> CHECK FOR FILE IN FOLDER:
>>>> os.listdir('W:\\BEP\\DOS reports\\Q1 FY13\\BEP_Tool4DOS\\FY13Q1_responses')
> ['Algeria_688_RVF.txt', 'Egypt_31060_RVFEnvir


As Mark points out, your problem is that you've used a different 
directory for os.chdir.

I'd like to point out that I'm heavily biased against ever changing 
"current working directory" in a non-trivial application.  The current 
directory is analogous to a global variable, and they should all be 
constant.  Now, if you want to change it once, at program entry, then 
it's like a constant that gets iniialized once.

But if you are going to use the chkdir, then all your code that deals 
with that directory should use relative paths.  If you'd done 
os.listdir(".") you'd have seen the problem.

My preference is to use absolute directories for every reference, in 
which case you'd use something like
     ...open(os.path.join(directory, i), ...

With of course a better name than 'i', which is traditionally an 
integer.  (since 1967, anyway)

-- 
DaveA

From sayanchatterjee at gmail.com  Wed Apr 10 18:58:59 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Wed, 10 Apr 2013 22:28:59 +0530
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
Message-ID: <CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>

Thank Andre for your prompt answer.

I'll figure out the plotting issue once the dat files are made. So it's the
primary concern.
For an example I am attaching a dat file herewith. The two columns here are
2 numpy arrays.I want to add a third column, to be precise, I want to print
a parameter value on the third column of the file.

Sayan


On 10 April 2013 21:23, Andre' Walker-Loud <walksloud at gmail.com> wrote:

> Hi Sayan,
>
> This question would be better suited to the matplotlib list.
> Also, a more precise description of your existing data, and what you hope
> it would look like would make it easier to help answer your question.  Eg.,
> from your description, it is not clear if your existing data is in a table,
> and in the table you have numpy arrays, or if you have one numpy array of
> rank 2 with data in it.
>
>
> Regards,
>
> Andre
>
>
>
> On Apr 10, 2013, at 8:44 AM, Sayan Chatterjee wrote:
>
> > Dear All,
> >
> > I have some data files with numpy arrays stored in it in 2 columns. I
> want to add a third column with just floating point numbers(not numpy
> array) and plot them later with Matplotlib in 3d. How is it done? Could you
> please illuminate me?
> >
> > Bests,
> > Sayan
> >
> > --
> >
> >
> >
> --------------------------------------------------------------------------
> > Sayan  Chatterjee
> > Dept. of Physics and Meteorology
> > IIT Kharagpur
> > Lal Bahadur Shastry Hall of Residence
> > Room AB 205
> > Mob: +91 9874513565
> > blog: www.blissprofound.blogspot.com
> >
> > Volunteer , Padakshep
> > www.padakshep.org
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > To unsubscribe or change subscription options:
> > http://mail.python.org/mailman/listinfo/tutor
>
>


-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/e12db00f/attachment-0001.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: file_0.02.dat
Type: application/octet-stream
Size: 18480 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/e12db00f/attachment-0001.obj>

From walksloud at gmail.com  Wed Apr 10 19:08:51 2013
From: walksloud at gmail.com (Andre' Walker-Loud)
Date: Wed, 10 Apr 2013 10:08:51 -0700
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
Message-ID: <CA555F72-2974-46C4-A2BA-3E2FBE83BF72@gmail.com>

Hi Sayan,

> Thank Andre for your prompt answer. 

No problem.

> I'll figure out the plotting issue once the dat files are made. So it's the primary concern.
> For an example I am attaching a dat file herewith. The two columns here are 2 numpy arrays.I want to add a third column, to be precise, I want to print a parameter value on the third column of the file.

Let me try again.
The reason the matplotlib list would be a better place is this is a general python list, and most people are not familiar with numpy.  However, most people who use matplotlib are familiar with numpy.

I am hoping you can describe precisely the structure of the data.  Maybe show a little code on how it is created, or how you access it.  I am not keen to open "random" files from the internet.  As two examples of how I think your code might be packed

1/
'''
x = numpy.zeros([10]) # 1D numpy array of dimension 10
y = numpy.zeros([10]) # 1D numpy array of dimension 10
your_data = []
your_data.append(x)
your_data.append(y)
'''

so now your data is a table with two entries, and each entry is a numpy array.
You have in mind adding a third entry to the table with just floats.

2/
'''
your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all zeros
for i in range(your_data.shape[0]):
    for j in range(your_data.shape[1]):
        your_data[i,j] = data[i][j] # I am assuming the data is imported already and called data and is in a python list/table format
'''

Now you want to make a new column or row for your data file, which contains floats.  Well, all the entries inside the numpy array are already floats, so it is not clear to me why you want a new column that is not a numpy array. So it would be nice if you could precisely describe what you currently have and what you want.


Hope this helps,

Andre



From alan.gauld at btinternet.com  Wed Apr 10 19:26:29 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 10 Apr 2013 18:26:29 +0100
Subject: [Tutor] Running python from windows command prompt
In-Reply-To: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
References: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
Message-ID: <kk47c1$f6p$1@ger.gmane.org>

On 10/04/13 13:32, Arijit Ukil wrote:
> I like to run a python program "my_python.py" from windows command
> prompt. This program ( a function called testing) takes input as block
> data (say data = [1,2,3,4] and outputs processed single data.
>

Hopefully the code below is not your entire program. If it is it won't 
work. You define 2 functions but never call them.

Also you don't print anything so there is no visible output.
Finally this a code does not read the values from sys.argv.
(See my tutorial topic 'Talking to the user')

As for the error message, others have replied but basically you need
to either change to the folder that your file exists in or specify
the full path at the command prompt.

> import math
>
> def avrg(data):
>     return sum(data)/len(data)
>
> def testing (data):
>     val = avrg(data)
>     out = pow(val,2)
>     return out

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


From sayanchatterjee at gmail.com  Wed Apr 10 19:26:06 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Wed, 10 Apr 2013 22:56:06 +0530
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CA555F72-2974-46C4-A2BA-3E2FBE83BF72@gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CA555F72-2974-46C4-A2BA-3E2FBE83BF72@gmail.com>
Message-ID: <CAAT-4OStXVwKT2ef_ZGnd9uQ-t1ULD7BBv38T=ExWaCh5KcHGQ@mail.gmail.com>

Hi Andre,

Well,this is the concerned snippet of the code:


while *t < 1*:


  pp_za = pp_init + t*K*np.sin(K*pp_init)

# Periodic Boundary Condition

  for i in range(0,999):

    if pp_za[i] < 0:
      pp_za[i] = 2 - abs(pp_za[i])
    if pp_za[i] > 2:
      pp_za[i] = pp_za[i] % 2

  pv_za = +K*np.sin(K*pp_init)

  fname = 'file_' + str(t) + '.dat'

# Generating dataset for Phase Space diagram

  *np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f')*

  t = t + 0.01

And the sample data generated is :

0.105728 0.098678
0.126865 0.118406
0.147998 0.138128
0.169126 0.157845
0.190247 0.177556
0.211362 0.197259
0.232469 0.216955
0.253567 0.236643
0.274657 0.256321
0.295737 0.275989
0.316806 0.295646

Precisely what I want is, I want to add the 't' (over which the while loop
is run) in the 3 rd column. 't' is float and constant for each looping. If
you know what a phase plot is(doesn't matter if you don't), I want to see
the phase plot evolving with time. Thus the need of a time axis and hence
plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z axis).

I hope your first example might help.Though,I think,I need some tweaking to
fit to my needs.

Regards,
Sayan


On 10 April 2013 22:38, Andre' Walker-Loud <walksloud at gmail.com> wrote:

> Hi Sayan,
>
> > Thank Andre for your prompt answer.
>
> No problem.
>
> > I'll figure out the plotting issue once the dat files are made. So it's
> the primary concern.
> > For an example I am attaching a dat file herewith. The two columns here
> are 2 numpy arrays.I want to add a third column, to be precise, I want to
> print a parameter value on the third column of the file.
>
> Let me try again.
> The reason the matplotlib list would be a better place is this is a
> general python list, and most people are not familiar with numpy.  However,
> most people who use matplotlib are familiar with numpy.
>
> I am hoping you can describe precisely the structure of the data.  Maybe
> show a little code on how it is created, or how you access it.  I am not
> keen to open "random" files from the internet.  As two examples of how I
> think your code might be packed
>
> 1/
> '''
> x = numpy.zeros([10]) # 1D numpy array of dimension 10
> y = numpy.zeros([10]) # 1D numpy array of dimension 10
> your_data = []
> your_data.append(x)
> your_data.append(y)
> '''
>
> so now your data is a table with two entries, and each entry is a numpy
> array.
> You have in mind adding a third entry to the table with just floats.
>
> 2/
> '''
> your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all
> zeros
> for i in range(your_data.shape[0]):
>     for j in range(your_data.shape[1]):
>         your_data[i,j] = data[i][j] # I am assuming the data is imported
> already and called data and is in a python list/table format
> '''
>
> Now you want to make a new column or row for your data file, which
> contains floats.  Well, all the entries inside the numpy array are already
> floats, so it is not clear to me why you want a new column that is not a
> numpy array. So it would be nice if you could precisely describe what you
> currently have and what you want.
>
>
> Hope this helps,
>
> Andre
>
>
>


-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/6407f86e/attachment.html>

From alan.gauld at btinternet.com  Wed Apr 10 19:37:48 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 10 Apr 2013 18:37:48 +0100
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
Message-ID: <kk4818$ltt$1@ger.gmane.org>

On 10/04/13 16:44, Sayan Chatterjee wrote:

> I have some data files with numpy arrays stored in it in 2 columns. I

Can you define what that means?
All files on a computer are data files in some sense.
They exist as text files or binary files. If they are text files then 
the content of your arrays must be encoded somehow as strings. If they 
are binary files you must have dumped them to file somehow and adding 
floats is something you probably need to figure out yourself!

How did you create these files? (Or how were they created buy somebody 
else?)

> want to add a third column with just floating point numbers(not numpy
> array) and plot them later with Matplotlib in 3d. How is it done? Could
> you please illuminate me?

The fact you use the term column suggests that maybe they are text files 
of some kind in which case you likely have the content of the numpy 
arrays but not their structure, in which case adding an extra column 
should be easy by following the pattern of how you created the files. 
Don't forget to modify the functions that read the data back to match.

But with no idea of the exact nature of your "data files" we can't give 
very specific help.

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


From walksloud at gmail.com  Wed Apr 10 19:47:08 2013
From: walksloud at gmail.com (Andre' Walker-Loud)
Date: Wed, 10 Apr 2013 10:47:08 -0700
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAAT-4OStXVwKT2ef_ZGnd9uQ-t1ULD7BBv38T=ExWaCh5KcHGQ@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CA555F72-2974-46C4-A2BA-3E2FBE83BF72@gmail.com>
	<CAAT-4OStXVwKT2ef_ZGnd9uQ-t1ULD7BBv38T=ExWaCh5KcHGQ@mail.gmail.com>
Message-ID: <BA86B92F-5273-4029-A4D1-1126C24FE95A@gmail.com>

Hi Sayan,

> Well,this is the concerned snippet of the code:
> 
> 
> while t < 1:
> 
>   
>   pp_za = pp_init + t*K*np.sin(K*pp_init)
>   
> # Periodic Boundary Condition
>   
>   for i in range(0,999):
> 
>     if pp_za[i] < 0:
>       pp_za[i] = 2 - abs(pp_za[i])
>     if pp_za[i] > 2:
>       pp_za[i] = pp_za[i] % 2 
> 
>   pv_za = +K*np.sin(K*pp_init)
>   
>   fname = 'file_' + str(t) + '.dat'
> 
> # Generating dataset for Phase Space diagram
> 
>   np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f')
>   
>   t = t + 0.01

To answer your question, to add "t" to the array, you can simply replace the current np.array command with either of the following

np.array([pp_za,pv_za,t])

or 

np.array([t,pp_za,pv_za])

depending if you want "t" is the first element of the data or the last.
Also, you are "transposing" the array with the ".T", so this will write the data in sequential lines, rather than a single line (row) with multiple entries.  I just bring it up because it is not the "obvious" way to pack the data.

Also, it looks like you are generating a separate file for each "t".
Is this what you want?
I assume you want a single data file that stores this info, not many data files.


Andre





> 
> And the sample data generated is : 
> 
> 0.105728 0.098678
> 0.126865 0.118406
> 0.147998 0.138128
> 0.169126 0.157845
> 0.190247 0.177556
> 0.211362 0.197259
> 0.232469 0.216955
> 0.253567 0.236643
> 0.274657 0.256321
> 0.295737 0.275989
> 0.316806 0.295646
> 
> Precisely what I want is, I want to add the 't' (over which the while loop is run) in the 3 rd column. 't' is float and constant for each looping. If you know what a phase plot is(doesn't matter if you don't), I want to see the phase plot evolving with time. Thus the need of a time axis and hence plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z axis).
> 
> I hope your first example might help.Though,I think,I need some tweaking to fit to my needs.
> 
> Regards,
> Sayan
> 
> 
> On 10 April 2013 22:38, Andre' Walker-Loud <walksloud at gmail.com> wrote:
> Hi Sayan,
> 
> > Thank Andre for your prompt answer.
> 
> No problem.
> 
> > I'll figure out the plotting issue once the dat files are made. So it's the primary concern.
> > For an example I am attaching a dat file herewith. The two columns here are 2 numpy arrays.I want to add a third column, to be precise, I want to print a parameter value on the third column of the file.
> 
> Let me try again.
> The reason the matplotlib list would be a better place is this is a general python list, and most people are not familiar with numpy.  However, most people who use matplotlib are familiar with numpy.
> 
> I am hoping you can describe precisely the structure of the data.  Maybe show a little code on how it is created, or how you access it.  I am not keen to open "random" files from the internet.  As two examples of how I think your code might be packed
> 
> 1/
> '''
> x = numpy.zeros([10]) # 1D numpy array of dimension 10
> y = numpy.zeros([10]) # 1D numpy array of dimension 10
> your_data = []
> your_data.append(x)
> your_data.append(y)
> '''
> 
> so now your data is a table with two entries, and each entry is a numpy array.
> You have in mind adding a third entry to the table with just floats.
> 
> 2/
> '''
> your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all zeros
> for i in range(your_data.shape[0]):
>     for j in range(your_data.shape[1]):
>         your_data[i,j] = data[i][j] # I am assuming the data is imported already and called data and is in a python list/table format
> '''
> 
> Now you want to make a new column or row for your data file, which contains floats.  Well, all the entries inside the numpy array are already floats, so it is not clear to me why you want a new column that is not a numpy array. So it would be nice if you could precisely describe what you currently have and what you want.
> 
> 
> Hope this helps,
> 
> Andre
> 
> 
> 
> 
> 
> -- 
> 
> 
> --------------------------------------------------------------------------
> Sayan  Chatterjee
> Dept. of Physics and Meteorology
> IIT Kharagpur
> Lal Bahadur Shastry Hall of Residence
> Room AB 205
> Mob: +91 9874513565
> blog: www.blissprofound.blogspot.com
> 
> Volunteer , Padakshep
> www.padakshep.org


From sayanchatterjee at gmail.com  Wed Apr 10 19:46:46 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Wed, 10 Apr 2013 23:16:46 +0530
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <kk4818$ltt$1@ger.gmane.org>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<kk4818$ltt$1@ger.gmane.org>
Message-ID: <CAAT-4OSC7zqbsBCWavBZOk8aucuWNTBm=x9jnge6c7zFCJBoEQ@mail.gmail.com>

Hi Alan,

Sorry for the ambiguity I have created.

 I have added the snippet of code just in the previous mail and also the
sample data in the text file. Have you had a look on them?

I am copy pasting it in this email:

Hi Andre,

Well,this is the concerned snippet of the code:


while *t < 1*:


  pp_za = pp_init + t*K*np.sin(K*pp_init)

# Periodic Boundary Condition

  for i in range(0,999):

    if pp_za[i] < 0:
      pp_za[i] = 2 - abs(pp_za[i])
    if pp_za[i] > 2:
      pp_za[i] = pp_za[i] % 2

  pv_za = +K*np.sin(K*pp_init)

  fname = 'file_' + str(t) + '.dat'

# Generating dataset for Phase Space diagram

  *np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f')*

  t = t + 0.01

And the sample data generated is :

0.105728 0.098678
0.126865 0.118406
0.147998 0.138128
0.169126 0.157845
0.190247 0.177556
0.211362 0.197259
0.232469 0.216955
0.253567 0.236643
0.274657 0.256321
0.295737 0.275989
0.316806 0.295646

Precisely what I want is, I want to add the 't' (over which the while loop
is run) in the 3 rd column. 't' is float and constant for each looping. If
you know what a phase plot is(doesn't matter if you don't), I want to see
the phase plot evolving with time. Thus the need of a time axis and hence
plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z axis).


Regards,
Sayan




On 10 April 2013 23:07, Alan Gauld <alan.gauld at btinternet.com> wrote:

> On 10/04/13 16:44, Sayan Chatterjee wrote:
>
>  I have some data files with numpy arrays stored in it in 2 columns. I
>>
>
> Can you define what that means?
> All files on a computer are data files in some sense.
> They exist as text files or binary files. If they are text files then the
> content of your arrays must be encoded somehow as strings. If they are
> binary files you must have dumped them to file somehow and adding floats is
> something you probably need to figure out yourself!
>
> How did you create these files? (Or how were they created buy somebody
> else?)
>
>
>  want to add a third column with just floating point numbers(not numpy
>> array) and plot them later with Matplotlib in 3d. How is it done? Could
>> you please illuminate me?
>>
>
> The fact you use the term column suggests that maybe they are text files
> of some kind in which case you likely have the content of the numpy arrays
> but not their structure, in which case adding an extra column should be
> easy by following the pattern of how you created the files. Don't forget to
> modify the functions that read the data back to match.
>
> But with no idea of the exact nature of your "data files" we can't give
> very specific help.
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>



-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/6befa229/attachment.html>

From dfjennings at gmail.com  Wed Apr 10 19:50:02 2013
From: dfjennings at gmail.com (Don Jennings)
Date: Wed, 10 Apr 2013 13:50:02 -0400
Subject: [Tutor] building a website with python
In-Reply-To: <A3983D31-87D0-42B3-A778-D55DDE3BC160@gmail.com>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
	<C52014F1-E32C-4711-911B-4F811ABD9242@gmail.com>
	<A3983D31-87D0-42B3-A778-D55DDE3BC160@gmail.com>
Message-ID: <E1B2239F-F352-455F-B4AB-B2ABC1AAAF6B@gmail.com>


On Apr 9, 2013, at 11:07 PM, Benjamin Fishbein wrote:

>> 
>> You've gotten some good feedback, but I suspect you will get better information if you provide more information about your goals for the site.
>> 
> 
> Thanks for your help, everyone. There are some specific things I want the site to do, and I'm not sure which would be the best developing tool or hosting for these.
> The python software I developed is for selling used books.
> It takes book ISBN numbers as input and returns the best prices being offered.
> It uses the selenium module...I'm not sure how that would translate into a website.

Checking the documentation [1], selenium will interact with a browser running remotely using the selenium-server. However, I don't imagine the latter option being viable if you plan to have any significant traffic. I would think a better plan is to forego the gui browser, perhaps re-writing the interaction with other sites using requests [2], a very nice way to work with HTTP. Do you need to interact with javascript on those pages?

> There are many websites that offer similar book price comparisons, but mine is different...it's user-friendly. Any volunteer at a thrift shop or library can use it...just a series of simple directions and yes/no questions, taking the user all the way from scanning or typing in an ISBN to dropping the parcel off at the post office. (The local libraries I worked with more than doubled their used-book revenues.) I want to expand this nationwide, and bookchicken.com seems to be the way to do it.
> So much of the program is simple enough. But there's two parts of the program that I anticipate being important to what host, development tool I use:
> 1. ISBNs (the books the thrift shop/ library has) being sent to various websites and returning the data to my site to be analyzed by my program.
> 2. Maneuvering through the website of the company buying the books. I don't want to send the user off to a warehouse's site with a list of books to sell to them. They'll still be entering their address and name, but it'll be on my site, that I then send to the warehouse's page, get a packing slip and shipping label from the warehouse, and give these documents to the user to print out.
> 
> I'm not sure if this changes anyone's ideas about which host/ developer I should use. Please let me know.

Obviously my recommendations for producing a static site missed the mark! I do think that one of the microframeworks folks have mentioned will get you up and running faster.

Take care,
Don

[1] http://docs.seleniumhq.org/docs/03_webdriver.jsp
[2] http://docs.python-requests.org/en/latest/user/quickstart/

From sayanchatterjee at gmail.com  Wed Apr 10 19:54:12 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Wed, 10 Apr 2013 23:24:12 +0530
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <BA86B92F-5273-4029-A4D1-1126C24FE95A@gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CA555F72-2974-46C4-A2BA-3E2FBE83BF72@gmail.com>
	<CAAT-4OStXVwKT2ef_ZGnd9uQ-t1ULD7BBv38T=ExWaCh5KcHGQ@mail.gmail.com>
	<BA86B92F-5273-4029-A4D1-1126C24FE95A@gmail.com>
Message-ID: <CAAT-4OTLJZ=oVN21e74gxadcqBAC-1CQdE36i1Si0oPWMy44JQ@mail.gmail.com>

Yup it's exactly what I want!

I want *many* data files,not one...to make an animation out of it. For a
data file t is constant.

the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is
giving the following error:


Traceback (most recent call last):
  File "ZA_Phase_Plot.py", line 38, in <module>
    np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f')
  File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979, in
savetxt
    fh.write(asbytes(format % tuple(row) + newline))
TypeError: float argument required, not numpy.ndarray

What to do? :-|

Sayan



On 10 April 2013 23:17, Andre' Walker-Loud <walksloud at gmail.com> wrote:

> Hi Sayan,
>
> > Well,this is the concerned snippet of the code:
> >
> >
> > while t < 1:
> >
> >
> >   pp_za = pp_init + t*K*np.sin(K*pp_init)
> >
> > # Periodic Boundary Condition
> >
> >   for i in range(0,999):
> >
> >     if pp_za[i] < 0:
> >       pp_za[i] = 2 - abs(pp_za[i])
> >     if pp_za[i] > 2:
> >       pp_za[i] = pp_za[i] % 2
> >
> >   pv_za = +K*np.sin(K*pp_init)
> >
> >   fname = 'file_' + str(t) + '.dat'
> >
> > # Generating dataset for Phase Space diagram
> >
> >   np.savetxt(fname, np.array([pp_za,pv_za]).T, '%f')
> >
> >   t = t + 0.01
>
> To answer your question, to add "t" to the array, you can simply replace
> the current np.array command with either of the following
>
> np.array([pp_za,pv_za,t])
>
> or
>
> np.array([t,pp_za,pv_za])
>
> depending if you want "t" is the first element of the data or the last.
> Also, you are "transposing" the array with the ".T", so this will write
> the data in sequential lines, rather than a single line (row) with multiple
> entries.  I just bring it up because it is not the "obvious" way to pack
> the data.
>
> Also, it looks like you are generating a separate file for each "t".
> Is this what you want?
> I assume you want a single data file that stores this info, not many data
> files.
>
>
> Andre
>
>
>
>
>
> >
> > And the sample data generated is :
> >
> > 0.105728 0.098678
> > 0.126865 0.118406
> > 0.147998 0.138128
> > 0.169126 0.157845
> > 0.190247 0.177556
> > 0.211362 0.197259
> > 0.232469 0.216955
> > 0.253567 0.236643
> > 0.274657 0.256321
> > 0.295737 0.275989
> > 0.316806 0.295646
> >
> > Precisely what I want is, I want to add the 't' (over which the while
> loop is run) in the 3 rd column. 't' is float and constant for each
> looping. If you know what a phase plot is(doesn't matter if you don't), I
> want to see the phase plot evolving with time. Thus the need of a time axis
> and hence plot with V(velocity-Yaxis), X ( Position -X axis) and t (Time-Z
> axis).
> >
> > I hope your first example might help.Though,I think,I need some tweaking
> to fit to my needs.
> >
> > Regards,
> > Sayan
> >
> >
> > On 10 April 2013 22:38, Andre' Walker-Loud <walksloud at gmail.com> wrote:
> > Hi Sayan,
> >
> > > Thank Andre for your prompt answer.
> >
> > No problem.
> >
> > > I'll figure out the plotting issue once the dat files are made. So
> it's the primary concern.
> > > For an example I am attaching a dat file herewith. The two columns
> here are 2 numpy arrays.I want to add a third column, to be precise, I want
> to print a parameter value on the third column of the file.
> >
> > Let me try again.
> > The reason the matplotlib list would be a better place is this is a
> general python list, and most people are not familiar with numpy.  However,
> most people who use matplotlib are familiar with numpy.
> >
> > I am hoping you can describe precisely the structure of the data.  Maybe
> show a little code on how it is created, or how you access it.  I am not
> keen to open "random" files from the internet.  As two examples of how I
> think your code might be packed
> >
> > 1/
> > '''
> > x = numpy.zeros([10]) # 1D numpy array of dimension 10
> > y = numpy.zeros([10]) # 1D numpy array of dimension 10
> > your_data = []
> > your_data.append(x)
> > your_data.append(y)
> > '''
> >
> > so now your data is a table with two entries, and each entry is a numpy
> array.
> > You have in mind adding a third entry to the table with just floats.
> >
> > 2/
> > '''
> > your_data = numpy.zeros([10,10]) # initialize a 2D numpy array with all
> zeros
> > for i in range(your_data.shape[0]):
> >     for j in range(your_data.shape[1]):
> >         your_data[i,j] = data[i][j] # I am assuming the data is imported
> already and called data and is in a python list/table format
> > '''
> >
> > Now you want to make a new column or row for your data file, which
> contains floats.  Well, all the entries inside the numpy array are already
> floats, so it is not clear to me why you want a new column that is not a
> numpy array. So it would be nice if you could precisely describe what you
> currently have and what you want.
> >
> >
> > Hope this helps,
> >
> > Andre
> >
> >
> >
> >
> >
> > --
> >
> >
> >
> --------------------------------------------------------------------------
> > Sayan  Chatterjee
> > Dept. of Physics and Meteorology
> > IIT Kharagpur
> > Lal Bahadur Shastry Hall of Residence
> > Room AB 205
> > Mob: +91 9874513565
> > blog: www.blissprofound.blogspot.com
> >
> > Volunteer , Padakshep
> > www.padakshep.org
>
>


-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/7a562b3c/attachment.html>

From torkamani at gmail.com  Wed Apr 10 19:56:12 2013
From: torkamani at gmail.com (Ali Torkamani)
Date: Wed, 10 Apr 2013 10:56:12 -0700
Subject: [Tutor] Phyton script for fasta file (seek help)
In-Reply-To: <CAGZAPF5x8zarnX+Qwg4LXd4+Y8D93ndZPE0vmjBJ49XrD1bjJQ@mail.gmail.com>
References: <13d9b2944c8.-4757810490957638786.6251647252550083523@zoho.com>
	<CAGZAPF5pr4VBG1RA_94hMQrM2ECR_znWztEha1uRZeta6nBvXg@mail.gmail.com>
	<CAEmF0k6rvtrXFESOs=ESz0sB_w0upo8Jas=iOGq--sqq9oK+NA@mail.gmail.com>
	<CAGZAPF5x8zarnX+Qwg4LXd4+Y8D93ndZPE0vmjBJ49XrD1bjJQ@mail.gmail.com>
Message-ID: <CAEmF0k46KCjB=T2DOVjP5H+rMTR3xXSc1-jKn4RV=qM0j-+ZqQ@mail.gmail.com>

On Wed, Apr 10, 2013 at 8:32 AM, Danny Yoo <dyoo at hashcollision.org> wrote:

> Hi Ali,
>
> Again, I recommend not reinventing a FASTA parser unless you really
> need something custom here.  In this particular case, the function
> ReadFasta here is slow on large inputs.  The culprit is the set of
> lines:
>
>             if line[0]=='>':
>                 prevLine=line[1:]
>                 dictFasta[prevLine]=''
>             else:
>

Sure, I myself use biopythin as well, but just wanted to mention that it's
not a big hassle, in particular if you need to load it just once. You have
a very legitimate point about the order of execution of my suggested code.

Ali
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/e4eb4b06/attachment.html>

From eryksun at gmail.com  Wed Apr 10 19:59:23 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 10 Apr 2013 13:59:23 -0400
Subject: [Tutor] File not found error, but it is in the folder!
In-Reply-To: <516591C5.9020207@davea.name>
References: <CAPwGs2rZJ57dG9-4XCgf2CK2KZkUprvfgJ0LgE4oUJ5dKiO7CQ@mail.gmail.com>
	<516591C5.9020207@davea.name>
Message-ID: <CACL+1av0EjdKVR0+w7w+2zdj9SgD1Je=3Jy6x8djr2u1P-D_yw@mail.gmail.com>

On Wed, Apr 10, 2013 at 12:22 PM, Dave Angel <davea at davea.name> wrote:
> My preference is to use absolute directories for every reference, in which
> case you'd use something like
>     ...open(os.path.join(directory, i), ...

+1

> With of course a better name than 'i', which is traditionally an integer.
> (since 1967, anyway)

At least 1958. I'm not familiar with pre-77 FORTRAN, but I found an
old manual for FORTRAN II on UNIVAC systems, written by Knuth in 1962.
 It states that any variable name starting with the letters I through
N is implicitly typed integer; otherwise it's implicitly a float.
FORTRAN 77 introduced "IMPLICIT NONE" to disable this feature.

From walksloud at gmail.com  Wed Apr 10 20:06:46 2013
From: walksloud at gmail.com (Andre' Walker-Loud)
Date: Wed, 10 Apr 2013 11:06:46 -0700
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAAT-4OTLJZ=oVN21e74gxadcqBAC-1CQdE36i1Si0oPWMy44JQ@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CA555F72-2974-46C4-A2BA-3E2FBE83BF72@gmail.com>
	<CAAT-4OStXVwKT2ef_ZGnd9uQ-t1ULD7BBv38T=ExWaCh5KcHGQ@mail.gmail.com>
	<BA86B92F-5273-4029-A4D1-1126C24FE95A@gmail.com>
	<CAAT-4OTLJZ=oVN21e74gxadcqBAC-1CQdE36i1Si0oPWMy44JQ@mail.gmail.com>
Message-ID: <DF1F2829-69CE-4B6B-9CFB-51CD8944F586@gmail.com>

Hi Sayan,

> Yup it's exactly what I want!
> 
> I want many data files,not one...to make an animation out of it. For a data file t is constant.

You should not need many data files to make an animation.  If you write your loops correctly, you can take a single data file with all the data.  If you are using code you did not write, and just want to get it to work, I understand that, but would encourage you also to figure out how to do it all with single data file.  Less files makes a files system and user happier.

> the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is giving the following error:
> 
> 
> Traceback (most recent call last):
>   File "ZA_Phase_Plot.py", line 38, in <module>
>     np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f')
>   File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979, in savetxt
>     fh.write(asbytes(format % tuple(row) + newline))
> TypeError: float argument required, not numpy.ndarray
> 
> What to do? :-|

There are pieces of the code snipet you sent which are not defined, so it is not clear why you are getting this error.  How long is the file "ZA_Phase_Plot.py"?  At least you can send from line 0 to where you did before, so all the variables are defined.  That should help.

Andre




From sayanchatterjee at gmail.com  Wed Apr 10 20:22:03 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Wed, 10 Apr 2013 23:52:03 +0530
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <DF1F2829-69CE-4B6B-9CFB-51CD8944F586@gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CA555F72-2974-46C4-A2BA-3E2FBE83BF72@gmail.com>
	<CAAT-4OStXVwKT2ef_ZGnd9uQ-t1ULD7BBv38T=ExWaCh5KcHGQ@mail.gmail.com>
	<BA86B92F-5273-4029-A4D1-1126C24FE95A@gmail.com>
	<CAAT-4OTLJZ=oVN21e74gxadcqBAC-1CQdE36i1Si0oPWMy44JQ@mail.gmail.com>
	<DF1F2829-69CE-4B6B-9CFB-51CD8944F586@gmail.com>
Message-ID: <CAAT-4OTpKOAcCsUxGmh7mJ1MPuB=kz0p3bxQi3Md-9VsxfQe2Q@mail.gmail.com>

Hi Andre,

Is it that? We can have different plots and hence animation from a single
data file.Very good!...if you have some time in your disposal, it will be
kind of you to illumine in this matter...may be some useful link will do.

I have written this small code from scratch,there's no 'get it to work'
business...:)

Here is the total code...not attaching as you might have problem opening
random files from internet....:)

#!usr/bin/python

import numpy as np
import matplotlib.pyplot as plt
import itertools as i
import pylab

K = 3.14
t = 0

# Allotment of particles

pp_init = np.linspace(0,1.99799799,999)

print pp_init

# Velocity array

while t < 1:


  pp_za = pp_init + t*K*np.sin(K*pp_init)

# Periodic Boundary Condition

  for i in range(0,999):

    if pp_za[i] < 0:
      pp_za[i] = 2 - abs(pp_za[i])
    if pp_za[i] > 2:
      pp_za[i] = pp_za[i] % 2

  pv_za = +K*np.sin(K*pp_init)

  fname = 'file_' + str(t) + '.dat'

# Generating dataset for Phase Space diagram
  np.savetxt(fname, np.array([pp_za,pv_za,t]), '%f')

  t = t + 0.01

# Plot using Matplotlib

i = 0

while i < 1:
  fname = 'file_' + str(i) + '.dat'
  f=open(fname,"r")
  x,y = np.loadtxt(fname, unpack=True)
  #plt.plot(x,y,linewidth=2.0)
  plt.scatter(x,y)
  plt.ylim(-8,8)
  plt.xlim(0,2)
  plt.ylabel('Velocity')
  plt.xlabel('X')
  pylab.savefig(fname + '.png')
  plt.cla()
  f.close()
  i = i  + 0.001

Regards,
Sayan




On 10 April 2013 23:36, Andre' Walker-Loud <walksloud at gmail.com> wrote:

> Hi Sayan,
>
> > Yup it's exactly what I want!
> >
> > I want many data files,not one...to make an animation out of it. For a
> data file t is constant.
>
> You should not need many data files to make an animation.  If you write
> your loops correctly, you can take a single data file with all the data.
>  If you are using code you did not write, and just want to get it to work,
> I understand that, but would encourage you also to figure out how to do it
> all with single data file.  Less files makes a files system and user
> happier.
>
> > the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is
> giving the following error:
> >
> >
> > Traceback (most recent call last):
> >   File "ZA_Phase_Plot.py", line 38, in <module>
> >     np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f')
> >   File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979,
> in savetxt
> >     fh.write(asbytes(format % tuple(row) + newline))
> > TypeError: float argument required, not numpy.ndarray
> >
> > What to do? :-|
>
> There are pieces of the code snipet you sent which are not defined, so it
> is not clear why you are getting this error.  How long is the file
> "ZA_Phase_Plot.py"?  At least you can send from line 0 to where you did
> before, so all the variables are defined.  That should help.
>
> Andre
>
>
>
>


-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/b04a3e69/attachment.html>

From oscar.j.benjamin at gmail.com  Wed Apr 10 20:47:53 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Wed, 10 Apr 2013 19:47:53 +0100
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
Message-ID: <CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>

On 10 April 2013 17:58, Sayan Chatterjee <sayanchatterjee at gmail.com> wrote:
> Thank Andre for your prompt answer.
>
> I'll figure out the plotting issue once the dat files are made. So it's the
> primary concern.
> For an example I am attaching a dat file herewith. The two columns here are
> 2 numpy arrays.I want to add a third column, to be precise, I want to print
> a parameter value on the third column of the file.

The file you attached is a space-delimited text file. If you want to
add a third column with the value '1.0' on every row you can just do:

with open('old.dat') as fin, open('new.dat', 'w') as fout:
    for line in fin:
        fout.write(line[:-1] + ' 1.0\n')


Oscar

From sayanchatterjee at gmail.com  Wed Apr 10 20:48:05 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Thu, 11 Apr 2013 00:18:05 +0530
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAAT-4OTpKOAcCsUxGmh7mJ1MPuB=kz0p3bxQi3Md-9VsxfQe2Q@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CA555F72-2974-46C4-A2BA-3E2FBE83BF72@gmail.com>
	<CAAT-4OStXVwKT2ef_ZGnd9uQ-t1ULD7BBv38T=ExWaCh5KcHGQ@mail.gmail.com>
	<BA86B92F-5273-4029-A4D1-1126C24FE95A@gmail.com>
	<CAAT-4OTLJZ=oVN21e74gxadcqBAC-1CQdE36i1Si0oPWMy44JQ@mail.gmail.com>
	<DF1F2829-69CE-4B6B-9CFB-51CD8944F586@gmail.com>
	<CAAT-4OTpKOAcCsUxGmh7mJ1MPuB=kz0p3bxQi3Md-9VsxfQe2Q@mail.gmail.com>
Message-ID: <CAAT-4OTEz0PAzESuAHnAqxLsX8H5jise=Yne4T_h1sKAe-1JQA@mail.gmail.com>

Hi Andre,

I figured it out. Need not reply of np.savetxt for storing array simply
f.wite() is doing fine.

while i < 999:
    print i
    fo.write('{0:f}  {1:f}  {2:f}\n'.format(pp_za[i], pv_za[i],t))
    i = i + 1

Eager to know that single file thing though!

Sayan


On 10 April 2013 23:52, Sayan Chatterjee <sayanchatterjee at gmail.com> wrote:

> Hi Andre,
>
> Is it that? We can have different plots and hence animation from a single
> data file.Very good!...if you have some time in your disposal, it will be
> kind of you to illumine in this matter...may be some useful link will do.
>
> I have written this small code from scratch,there's no 'get it to work'
> business...:)
>
> Here is the total code...not attaching as you might have problem opening
> random files from internet....:)
>
> #!usr/bin/python
>
> import numpy as np
> import matplotlib.pyplot as plt
> import itertools as i
> import pylab
>
> K = 3.14
> t = 0
>
> # Allotment of particles
>
> pp_init = np.linspace(0,1.99799799,999)
>
> print pp_init
>
> # Velocity array
>
> while t < 1:
>
>
>   pp_za = pp_init + t*K*np.sin(K*pp_init)
>
> # Periodic Boundary Condition
>
>   for i in range(0,999):
>
>     if pp_za[i] < 0:
>       pp_za[i] = 2 - abs(pp_za[i])
>     if pp_za[i] > 2:
>       pp_za[i] = pp_za[i] % 2
>
>   pv_za = +K*np.sin(K*pp_init)
>
>   fname = 'file_' + str(t) + '.dat'
>
> # Generating dataset for Phase Space diagram
>   np.savetxt(fname, np.array([pp_za,pv_za,t]), '%f')
>
>   t = t + 0.01
>
> # Plot using Matplotlib
>
> i = 0
>
> while i < 1:
>   fname = 'file_' + str(i) + '.dat'
>   f=open(fname,"r")
>   x,y = np.loadtxt(fname, unpack=True)
>   #plt.plot(x,y,linewidth=2.0)
>   plt.scatter(x,y)
>   plt.ylim(-8,8)
>   plt.xlim(0,2)
>   plt.ylabel('Velocity')
>   plt.xlabel('X')
>   pylab.savefig(fname + '.png')
>   plt.cla()
>   f.close()
>   i = i  + 0.001
>
> Regards,
> Sayan
>
>
>
>
> On 10 April 2013 23:36, Andre' Walker-Loud <walksloud at gmail.com> wrote:
>
>> Hi Sayan,
>>
>> > Yup it's exactly what I want!
>> >
>> > I want many data files,not one...to make an animation out of it. For a
>> data file t is constant.
>>
>> You should not need many data files to make an animation.  If you write
>> your loops correctly, you can take a single data file with all the data.
>>  If you are using code you did not write, and just want to get it to work,
>> I understand that, but would encourage you also to figure out how to do it
>> all with single data file.  Less files makes a files system and user
>> happier.
>>
>> > the solution you have just mentioned i.e np.array([t,pp_za,pv_za]) is
>> giving the following error:
>> >
>> >
>> > Traceback (most recent call last):
>> >   File "ZA_Phase_Plot.py", line 38, in <module>
>> >     np.savetxt(fname, np.array([pp_za,pv_za,t]).T, '%f')
>> >   File "/usr/lib/python2.7/dist-packages/numpy/lib/npyio.py", line 979,
>> in savetxt
>> >     fh.write(asbytes(format % tuple(row) + newline))
>> > TypeError: float argument required, not numpy.ndarray
>> >
>> > What to do? :-|
>>
>> There are pieces of the code snipet you sent which are not defined, so it
>> is not clear why you are getting this error.  How long is the file
>> "ZA_Phase_Plot.py"?  At least you can send from line 0 to where you did
>> before, so all the variables are defined.  That should help.
>>
>> Andre
>>
>>
>>
>>
>
>
> --
>
>
> --------------------------------------------------------------------------
> *Sayan  Chatterjee*
> Dept. of Physics and Meteorology
> IIT Kharagpur
> Lal Bahadur Shastry Hall of Residence
> Room AB 205
> Mob: +91 9874513565
> blog: www.blissprofound.blogspot.com
>
> Volunteer , Padakshep
> www.padakshep.org
>



-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130411/aa27143a/attachment-0001.html>

From sayanchatterjee at gmail.com  Wed Apr 10 20:48:54 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Thu, 11 Apr 2013 00:18:54 +0530
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
Message-ID: <CAAT-4OT1UYcjM7ZUvvcpS08m7wS1d3qnNiEEqe08O8R3zwx8Vg@mail.gmail.com>

Thanks Oscar figured it out...:)


On 11 April 2013 00:17, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:

> On 10 April 2013 17:58, Sayan Chatterjee <sayanchatterjee at gmail.com>
> wrote:
> > Thank Andre for your prompt answer.
> >
> > I'll figure out the plotting issue once the dat files are made. So it's
> the
> > primary concern.
> > For an example I am attaching a dat file herewith. The two columns here
> are
> > 2 numpy arrays.I want to add a third column, to be precise, I want to
> print
> > a parameter value on the third column of the file.
>
> The file you attached is a space-delimited text file. If you want to
> add a third column with the value '1.0' on every row you can just do:
>
> with open('old.dat') as fin, open('new.dat', 'w') as fout:
>     for line in fin:
>         fout.write(line[:-1] + ' 1.0\n')
>
>
> Oscar
>



-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130411/ccb92a4b/attachment.html>

From oscar.j.benjamin at gmail.com  Wed Apr 10 21:04:55 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Wed, 10 Apr 2013 20:04:55 +0100
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAAT-4OTEz0PAzESuAHnAqxLsX8H5jise=Yne4T_h1sKAe-1JQA@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CA555F72-2974-46C4-A2BA-3E2FBE83BF72@gmail.com>
	<CAAT-4OStXVwKT2ef_ZGnd9uQ-t1ULD7BBv38T=ExWaCh5KcHGQ@mail.gmail.com>
	<BA86B92F-5273-4029-A4D1-1126C24FE95A@gmail.com>
	<CAAT-4OTLJZ=oVN21e74gxadcqBAC-1CQdE36i1Si0oPWMy44JQ@mail.gmail.com>
	<DF1F2829-69CE-4B6B-9CFB-51CD8944F586@gmail.com>
	<CAAT-4OTpKOAcCsUxGmh7mJ1MPuB=kz0p3bxQi3Md-9VsxfQe2Q@mail.gmail.com>
	<CAAT-4OTEz0PAzESuAHnAqxLsX8H5jise=Yne4T_h1sKAe-1JQA@mail.gmail.com>
Message-ID: <CAHVvXxQrURB7StjZ_0Et+u73PDLyaZdhQAMFvt5o280obs615Q@mail.gmail.com>

On 10 April 2013 19:48, Sayan Chatterjee <sayanchatterjee at gmail.com> wrote:
> Hi Andre,
>
> I figured it out. Need not reply of np.savetxt for storing array simply
> f.wite() is doing fine.
>
> while i < 999:
>     print i
>     fo.write('{0:f}  {1:f}  {2:f}\n'.format(pp_za[i], pv_za[i],t))
>     i = i + 1
>
> Eager to know that single file thing though!

The animation module in matplotlib can do animations for you without
you needing to explicitly write your data out to files. The code below
is taken from some matplotlib documentation or wiki. I don't remember
exactly where I got it from but I do remember that I needed to modify
it slightly to get it to work. If you run the script it will create
200 png image files and then call an external program (mencoder or
ffmpeg - need to install those separately) to convert the png files
into an mp4 video file.

#!/usr/bin/env python
"""
Matplotlib Animation Example

author: Jake Vanderplas
email: vanderplas at astro.washington.edu
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

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

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,

# animation function.  This is called sequentially
def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save('./basic_animation.mp4', fps=30)


Oscar

From walksloud at gmail.com  Wed Apr 10 21:14:29 2013
From: walksloud at gmail.com (Andre' Walker-Loud)
Date: Wed, 10 Apr 2013 12:14:29 -0700
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAAT-4OTpKOAcCsUxGmh7mJ1MPuB=kz0p3bxQi3Md-9VsxfQe2Q@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CA555F72-2974-46C4-A2BA-3E2FBE83BF72@gmail.com>
	<CAAT-4OStXVwKT2ef_ZGnd9uQ-t1ULD7BBv38T=ExWaCh5KcHGQ@mail.gmail.com>
	<BA86B92F-5273-4029-A4D1-1126C24FE95A@gmail.com>
	<CAAT-4OTLJZ=oVN21e74gxadcqBAC-1CQdE36i1Si0oPWMy44JQ@mail.gmail.com>
	<DF1F2829-69CE-4B6B-9CFB-51CD8944F586@gmail.com>
	<CAAT-4OTpKOAcCsUxGmh7mJ1MPuB=kz0p3bxQi3Md-9VsxfQe2Q@mail.gmail.com>
Message-ID: <D5B9425A-4C48-4277-A369-DA7C8871D39C@gmail.com>

Hi Sayan,

> Is it that? We can have different plots and hence animation from a single data file.Very good!...if you have some time in your disposal, it will be kind of you to illumine in this matter...may be some useful link will do.
> 
> I have written this small code from scratch,there's no 'get it to work' business...:)
> 
> Here is the total code...not attaching as you might have problem opening random files from internet....:)

I will leave the complete code snippet for the list memory.
A couple things.

With the code you have now, you do not even have to save any files.  You can simply implant the plotting into the initial while loop.  Right now, your saved files serve only as a temporary holding file for the data you had just created.  Since your initial data is not read from another file, but simply generated in your code, there is no reason to write any thing to disk, except the figures you are saving.

One thing to notice, your "t" and "i" while loops iterate over different counters.  You have
	t = t + 0.01
	i = i + 0.001
so your second loop will produce many calls that don't match anything (the files you created don't exist).

The previous error is because the pp_za and pv_za are already 1D numpy arrays of dimension 999.  That is why combining them with a single float, "np.array([pp_za,pv_za,t])", did not work - the dimension of "pp_za" and "t" don't match, so writing them with numpy.savetxt() gave an error.

How do you want to include the "t" information in the figure?
Do you want to make different plots with a time axis?  Or, it sounds like you are talking about a 3D plot?

If you want to store the time with the data, then make a t_array like so

''' inside your t while loop '''
# make an array filled with ones the same dimension as your pp_init, and then multiply each entry by "t"
t_array = t * numpy.ones_like(pp_init) 

''' then pack your data as '''
np.array([pp_za,pv_za,t_array])

but to have a single data file containing all of this:

t_array = np.arange(0,1,.001) # initialize all the times you care about
pp_init = np.linspace(0,1.99799799,999)  #just taking from your code
# initialize an array of zeros
# first dimension spans time
# second dimension is 3 to store value of pp_za, pv_za, t
# third dimension is actual length of data
all_data = np.zeros([len(t_array),3,len(pp_init)]) 

for i,t in enumerate(t_array):
    # make your pp_za and pv_za as in your code
    t_tmp = t * numpy.ones_like(pp_init)
    all_data[i] = np.array([pp_za,pv_za,t])


'''
now you have a single object (np.array) which contains all of your data.
You could either make each of the figures in the above loop, or you can use a second loop to make them.
I see Oscar has given you some advice on the plotting - so you could use this single object and his example to do what you want.


Andre



From fomcl at yahoo.com  Wed Apr 10 22:45:33 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 10 Apr 2013 13:45:33 -0700 (PDT)
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
Message-ID: <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>



> Subject: Re: [Tutor] Appending an extra column in a data file
> 
<snip>
?
> The file you attached is a space-delimited text file. If you want to
> add a third column with the value '1.0' on every row you can just do:
> 
> with open('old.dat') as fin, open('new.dat', 'w') as 
> fout:
> ? ? for line in fin:
> ? ? ? ? fout.write(line[:-1] + ' 1.0\n')

Is that Python 3.x? I thought this "double context manager" could only be done with contextlib.nested, e.g.:
>>> with contextlib.nested(open(fn, "rb"), open(fn[:-4] + "_out.dat", "wb")) as (r, w):
...???? for inline in r:
...???????????? w.write(inline + " " + "somevalue" + "\n")

Your code looks cleaner though.

Regards,
Albert-Jan

From eryksun at gmail.com  Wed Apr 10 23:17:00 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 10 Apr 2013 17:17:00 -0400
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
	<1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <CACL+1atWy5H1UHwaxPUMkWqBeu7bfJhaaTWKsHBmvNBPTX3RQQ@mail.gmail.com>

On Wed, Apr 10, 2013 at 4:45 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
>> with open('old.dat') as fin, open('new.dat', 'w') as fout:
>
> Is that Python 3.x?

It's the same syntax as an import statement such as the following:

    import numpy as np, matplotlib as mpl

A downside with this is the inability to split long lines by adding
parentheses. Obviously you can break at the open() call:

    with open('old.dat') as fin, open(
     'new.dat', 'w') as fout:
        for line in fin:

But I think it's more readable to break up a long line like this:

    fin = open('old.dat')
    fout = open('new.dat', 'w')

    with fin, fout:
        for line in fin:

From oscar.j.benjamin at gmail.com  Wed Apr 10 23:46:20 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Wed, 10 Apr 2013 22:46:20 +0100
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
	<1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <CAHVvXxSyREiP+So_ua=dBE01C7YyxBymXe7-ynvw-zsWCKWG0A@mail.gmail.com>

On 10 April 2013 21:45, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
>
>> Subject: Re: [Tutor] Appending an extra column in a data file
>>
> <snip>
>
>> The file you attached is a space-delimited text file. If you want to
>> add a third column with the value '1.0' on every row you can just do:
>>
>> with open('old.dat') as fin, open('new.dat', 'w') as
>> fout:
>>     for line in fin:
>>         fout.write(line[:-1] + ' 1.0\n')
>
> Is that Python 3.x? I thought this "double context manager" could only be done with contextlib.nested, e.g.:
>>>> with contextlib.nested(open(fn, "rb"), open(fn[:-4] + "_out.dat", "wb")) as (r, w):
> ...     for inline in r:
> ...             w.write(inline + " " + "somevalue" + "\n")

The contextlib.nested context manager does not work properly. The docs
http://docs.python.org/2/library/contextlib.html#contextlib.nested
say that it was deprecated in Python 2.7. To quote:

'''Deprecated since version 2.7: The with-statement now supports this
functionality directly (without the confusing error prone quirks).'''

The reason for its deprecation was that it cannot catch errors raised
during the function calls that create the underlying context managers.
This means that if the first open succeeds and the second fails (e.g.
because the file doesn't exist) then the with statement has no way of
guaranteeing that the first file gets closed.

Eryksun has pointed out the downside in relation to breaking long
lines. My preferred solution is just to literally nest the with
statements:

with open('old.dat'):
    with open('new.dat', 'w'):
        for line in fin:
            fout.write(line[:-1] + ' 1.0\n')

If your use case is more complicated then Python 3.3 gives you the ExitStack:
http://docs.python.org/3.3/library/contextlib.html#contextlib.ExitStack


Oscar

From oscar.j.benjamin at gmail.com  Wed Apr 10 23:49:07 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Wed, 10 Apr 2013 22:49:07 +0100
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CACL+1atWy5H1UHwaxPUMkWqBeu7bfJhaaTWKsHBmvNBPTX3RQQ@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
	<1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<CACL+1atWy5H1UHwaxPUMkWqBeu7bfJhaaTWKsHBmvNBPTX3RQQ@mail.gmail.com>
Message-ID: <CAHVvXxRS8ZiLszxzzHaopZG6m70uP7KGHoPG0bxH1anmeP5mVw@mail.gmail.com>

On 10 April 2013 22:17, eryksun <eryksun at gmail.com> wrote:
>
> But I think it's more readable to break up a long line like this:
>
>     fin = open('old.dat')
>     fout = open('new.dat', 'w')
>
>     with fin, fout:
>         for line in fin:

This has the same problems as contextlib.nested: An error raised while
opening 'new.dat' could prevent 'old.dat' from being closed properly.


Oscar

From eryksun at gmail.com  Thu Apr 11 00:09:13 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 10 Apr 2013 18:09:13 -0400
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAHVvXxRS8ZiLszxzzHaopZG6m70uP7KGHoPG0bxH1anmeP5mVw@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
	<1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<CACL+1atWy5H1UHwaxPUMkWqBeu7bfJhaaTWKsHBmvNBPTX3RQQ@mail.gmail.com>
	<CAHVvXxRS8ZiLszxzzHaopZG6m70uP7KGHoPG0bxH1anmeP5mVw@mail.gmail.com>
Message-ID: <CACL+1asS15TQFoNm9Z52M+uU7M5jwQGGGnbwx28PBgYzkq2E-w@mail.gmail.com>

On Wed, Apr 10, 2013 at 5:49 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
>>     fin = open('old.dat')
>>     fout = open('new.dat', 'w')
>>
>>     with fin, fout:
>>         for line in fin:
>
> This has the same problems as contextlib.nested: An error raised while
> opening 'new.dat' could prevent 'old.dat' from being closed properly.

Thanks for pointing out the potential bug there. It's not a big
problem in this case with the file open for reading. But, yeah, I'm
hanging my head in shame here... ;)

From therealdotcomboy at gmail.com  Thu Apr 11 02:18:41 2013
From: therealdotcomboy at gmail.com (Rodney Lewis)
Date: Wed, 10 Apr 2013 17:18:41 -0700
Subject: [Tutor] Python bz2 "IOError: invalid data stream" when trying to
	decompress
Message-ID: <CAJChYO0N=puLdqw_52NZ8999YgsmsdT5Zc78AhdGpf+oMA=fBw@mail.gmail.com>

My question is at StackOverflow so I won't repeat it here.

http://stackoverflow.com/questions/15938629/python-bz2-ioerror-invalid-data-stream-when-trying-to-decompress

Thanks so much in advance for any help you can provide regarding this.

http://www.squidoo.com/introductiontopython

-- 
Rodney Lewis
Please Visit My Homepage:
http://www.squidoo.com/dotcomboy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/8ee87167/attachment.html>

From davea at davea.name  Thu Apr 11 03:23:26 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 10 Apr 2013 21:23:26 -0400
Subject: [Tutor] Python bz2 "IOError: invalid data stream" when trying
 to decompress
In-Reply-To: <CAJChYO0N=puLdqw_52NZ8999YgsmsdT5Zc78AhdGpf+oMA=fBw@mail.gmail.com>
References: <CAJChYO0N=puLdqw_52NZ8999YgsmsdT5Zc78AhdGpf+oMA=fBw@mail.gmail.com>
Message-ID: <5166108E.2000204@davea.name>

On 04/10/2013 08:18 PM, Rodney Lewis wrote:
> My question is at StackOverflow so I won't repeat it here.
>
> http://stackoverflow.com/questions/15938629/python-bz2-ioerror-invalid-data-stream-when-trying-to-decompress
>
> Thanks so much in advance for any help you can provide regarding this.
>
> http://www.squidoo.com/introductiontopython
>
>

Works for me, after I turned the fragment into a program.  Python 2.7.3 
and Linux.

Perhaps you could be a bit more thorough in your problem description. 
Supply the whole program (40 lines isn't too big), and show the exact 
command line you used for both runs.  And show the full traceback, not 
just a summary.




-- 
DaveA

From amitsaha.in at gmail.com  Thu Apr 11 03:28:43 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Thu, 11 Apr 2013 11:28:43 +1000
Subject: [Tutor] Sharing Code Snippets
Message-ID: <CANODV3ksw9h6s0YgDUhhOLJbLrTOi7tVUjHQvB1Kd-ffr_pE0w@mail.gmail.com>

Hello everyone,

I am not sure if this has been shared on this list. However, to help
both those seeking help and those wanting to help, may I suggest that
for all of you posting your programs, how about using a service such
as GitHub's Gists [1]. It allows you to post entire programs with
advantages such as intact code formatting, syntax highlighting and
perhaps others such as version control.

I hope that's a useful suggestion.

[1] https://gist.github.com/

Best,
Amit.

--
http://amitsaha.github.com/

From eryksun at gmail.com  Thu Apr 11 04:16:48 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 10 Apr 2013 22:16:48 -0400
Subject: [Tutor] Python bz2 "IOError: invalid data stream" when trying
	to decompress
In-Reply-To: <CAJChYO0N=puLdqw_52NZ8999YgsmsdT5Zc78AhdGpf+oMA=fBw@mail.gmail.com>
References: <CAJChYO0N=puLdqw_52NZ8999YgsmsdT5Zc78AhdGpf+oMA=fBw@mail.gmail.com>
Message-ID: <CACL+1aunX3J1Vx7fxxxMho7v8bOxoekHnSfAu66zoGZ2dH_A7A@mail.gmail.com>

On Wed, Apr 10, 2013 at 8:18 PM, Rodney Lewis
<therealdotcomboy at gmail.com> wrote:
> My question is at StackOverflow so I won't repeat it here.

Short link:
http://stackoverflow.com/q/15938629/205580

Your function worked fine for me on Windows Python 2.7.3,
compressing/decompressing a text file that's about 150 KiB.

The bz2 module raises IOError("invalid data stream") for the error
codes BZ_DATA_ERROR and BZ_DATA_ERROR_MAGIC:

http://hg.python.org/cpython/file/70274d53c1dd/Modules/bz2module.c#l192

According to the bzip2 docs, BZ_DATA_ERROR is raised when the computed
CRC fails to match the stored CRC, or there's some other anomaly in
the data. BZ_DATA_ERROR_MAGIC means the compressed data didn't start
with the 'BZh' magic bytes.

http://www.bzip.org/1.0.5/bzip2-manual-1.0.5.html#err-handling

From sayanchatterjee at gmail.com  Thu Apr 11 08:04:16 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Thu, 11 Apr 2013 11:34:16 +0530
Subject: [Tutor] Sharing Code Snippets
In-Reply-To: <CANODV3ksw9h6s0YgDUhhOLJbLrTOi7tVUjHQvB1Kd-ffr_pE0w@mail.gmail.com>
References: <CANODV3ksw9h6s0YgDUhhOLJbLrTOi7tVUjHQvB1Kd-ffr_pE0w@mail.gmail.com>
Message-ID: <CAAT-4OREWiWSLLjfqw2KCU6GOrWNdz5gYdSDpz7bk8z5AcrdYg@mail.gmail.com>

Tried it out.It's really cool.From next time on, shall try to make use of
this. Thanks. :)


On 11 April 2013 06:58, Amit Saha <amitsaha.in at gmail.com> wrote:

> Hello everyone,
>
> I am not sure if this has been shared on this list. However, to help
> both those seeking help and those wanting to help, may I suggest that
> for all of you posting your programs, how about using a service such
> as GitHub's Gists [1]. It allows you to post entire programs with
> advantages such as intact code formatting, syntax highlighting and
> perhaps others such as version control.
>
> I hope that's a useful suggestion.
>
> [1] https://gist.github.com/
>
> Best,
> Amit.
>
> --
> http://amitsaha.github.com/
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130411/a2c8fad1/attachment.html>

From arijit.ukil at tcs.com  Thu Apr 11 08:08:25 2013
From: arijit.ukil at tcs.com (Arijit Ukil)
Date: Thu, 11 Apr 2013 11:38:25 +0530
Subject: [Tutor] Running python from windows command prompt
In-Reply-To: <kk47c1$f6p$1@ger.gmane.org>
References: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
	<kk47c1$f6p$1@ger.gmane.org>
Message-ID: <OF0F3BBBA5.08F7A1D1-ON65257B4A.00216D63-65257B4A.0021BB2D@tcs.com>

Thanks for the help. Now I have modifed the code as:

import sys

def main(argv):

    data = int(sys.argv[1])
 
    avg = average (data)
 
    print "Average:", avg

def average(num_list):
    return sum(num_list)/len(num_list)

if __name__ == "__main__":
   main(sys.argv[1:])

When running in command line I am getting these errors:
In case 1. data = sys.argv[1]
In case 2, data = float(sys.argv[1])
In case 3, data = int (sys.argv[1])





Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.ukil at tcs.com
Website: http://www.tcs.com
____________________________________________
Experience certainty.   IT Services
                        Business Solutions
                        Outsourcing
____________________________________________



From:
Alan Gauld <alan.gauld at btinternet.com>
To:
tutor at python.org
Date:
04/10/2013 10:58 PM
Subject:
Re: [Tutor] Running python from windows command prompt
Sent by:
"Tutor" <tutor-bounces+arijit.ukil=tcs.com at python.org>



On 10/04/13 13:32, Arijit Ukil wrote:
> I like to run a python program "my_python.py" from windows command
> prompt. This program ( a function called testing) takes input as block
> data (say data = [1,2,3,4] and outputs processed single data.
>

Hopefully the code below is not your entire program. If it is it won't 
work. You define 2 functions but never call them.

Also you don't print anything so there is no visible output.
Finally this a code does not read the values from sys.argv.
(See my tutorial topic 'Talking to the user')

As for the error message, others have replied but basically you need
to either change to the folder that your file exists in or specify
the full path at the command prompt.

> import math
>
> def avrg(data):
>     return sum(data)/len(data)
>
> def testing (data):
>     val = avrg(data)
>     out = pow(val,2)
>     return out

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

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


=====-----=====-----=====
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130411/ce7a1e8f/attachment-0001.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/gif
Size: 14160 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20130411/ce7a1e8f/attachment-0001.gif>

From pasokan at talentsprint.com  Thu Apr 11 08:24:17 2013
From: pasokan at talentsprint.com (Asokan Pichai)
Date: Thu, 11 Apr 2013 11:54:17 +0530
Subject: [Tutor] Running python from windows command prompt
In-Reply-To: <OF0F3BBBA5.08F7A1D1-ON65257B4A.00216D63-65257B4A.0021BB2D@tcs.com>
References: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
	<kk47c1$f6p$1@ger.gmane.org>
	<OF0F3BBBA5.08F7A1D1-ON65257B4A.00216D63-65257B4A.0021BB2D@tcs.com>
Message-ID: <CAJAvg=GVneoVwB9aC+f+Cor2nYyjuM+Bq5ZmL0QexWEFoLSq+A@mail.gmail.com>

On Thu, Apr 11, 2013 at 11:38 AM, Arijit Ukil <arijit.ukil at tcs.com> wrote:

> Thanks for the help. Now I have modifed the code as:
>
> import sys
>
> def main(argv):
>
>     data = int(sys.argv[1])
>
>     avg = average (data)
>
>     print "Average:", avg
>
> def average(num_list):
>     return sum(num_list)/len(num_list)
>
> if __name__ == "__main__":
>    main(sys.argv[1:])
>


Two major problems:
One:
The __main__ methods processes (correctly) the args and drops argv[0]

But your main() function is calling sys.argv again

Two:
sum() and len() expect a list -- more accurately an iterable.
when you say
 data = argv[1]
data is a scalar.

If you know of list comprehensions, it can be easier or else,
think of a function to convert a list of strings (argv[1:] to a list
of floats; more general than int)

--------------------
def arg2list(arg):
      args = []
      for a in arg:
           args.append(float(a))
      return args
--------------------
Now replace the data = line with

data = arg2list(argv) # NOT sys.argv

HTH

Asokan Pichai

"Expecting the world to treat you fairly because you are a good person is a
little like expecting the bull to not attack you because you are a
vegetarian"
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130411/1b93846d/attachment.html>

From alan.gauld at btinternet.com  Thu Apr 11 08:29:32 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 11 Apr 2013 07:29:32 +0100
Subject: [Tutor] Running python from windows command prompt
In-Reply-To: <OF0F3BBBA5.08F7A1D1-ON65257B4A.00216D63-65257B4A.0021BB2D@tcs.com>
References: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
	<kk47c1$f6p$1@ger.gmane.org>
	<OF0F3BBBA5.08F7A1D1-ON65257B4A.00216D63-65257B4A.0021BB2D@tcs.com>
Message-ID: <kk5l88$3s7$1@ger.gmane.org>

On 11/04/13 07:08, Arijit Ukil wrote:
> Thanks for the help. Now I have modifed the code as:
>
> import sys
>
> def main(argv):
>      data = int(sys.argv[1])
>      avg = average (data)
>      print "Average:", avg
>
> def average(num_list):
>      return sum(num_list)/len(num_list)
>
> if __name__ == "__main__":
>     main(sys.argv[1:])
>
> When running in command line I am getting these errors:
> In case 1. data = sys.argv[1]
> In case 2, data = float(sys.argv[1])
> In case 3, data = int (sys.argv[1])

Try printing data to see what you are doing wrong in each case.
You need data to be a list of numbers. None of your three cases produces 
that.



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


From after1990s at gmail.com  Thu Apr 11 12:41:37 2013
From: after1990s at gmail.com (w qj)
Date: Thu, 11 Apr 2013 18:41:37 +0800
Subject: [Tutor] Looks like a judgment bug.
Message-ID: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>

I found this under Windows Python3
>>> l="http://f/"
>>> l[-1] is not '/'
False
>>>

and this under Linux Python3
>>> l = "http://ff.f/"
>>> l[-1]
'/'
>>> l[-1] is not '/'
True

It's Looks like a python bug?

From timomlists at gmail.com  Thu Apr 11 13:20:43 2013
From: timomlists at gmail.com (Timo)
Date: Thu, 11 Apr 2013 13:20:43 +0200
Subject: [Tutor] Looks like a judgment bug.
In-Reply-To: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>
References: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>
Message-ID: <51669C8B.2050001@gmail.com>

Op 11-04-13 12:41, w qj schreef:
> I found this under Windows Python3
>>>> l="http://f/"
>>>> l[-1] is not '/'
> False
> and this under Linux Python3
>>>> l = "http://ff.f/"
>>>> l[-1]
> '/'
>>>> l[-1] is not '/'
> True
>
> It's Looks like a python bug?
This looks like a "is not" versus "!=" thing. Someone (I think Steven 
Apprano) posted a couple of days ago on this mailing list to only use 
"is" and "is not" when comparing to None.

It works fine with regular operators.

$ python3
Python 3.2.3 (default, Oct 19 2012, 19:53:16)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> l = "http://ff.f/"
 >>> l[-1]
'/'
 >>> l[-1] is not '/'
True
 >>> l[-1] != '/'
False


Timo

> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From fomcl at yahoo.com  Thu Apr 11 13:24:31 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 11 Apr 2013 04:24:31 -0700 (PDT)
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CACL+1asS15TQFoNm9Z52M+uU7M5jwQGGGnbwx28PBgYzkq2E-w@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
	<1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<CACL+1atWy5H1UHwaxPUMkWqBeu7bfJhaaTWKsHBmvNBPTX3RQQ@mail.gmail.com>
	<CAHVvXxRS8ZiLszxzzHaopZG6m70uP7KGHoPG0bxH1anmeP5mVw@mail.gmail.com>
	<CACL+1asS15TQFoNm9Z52M+uU7M5jwQGGGnbwx28PBgYzkq2E-w@mail.gmail.com>
Message-ID: <1365679471.57539.YahooMailNeo@web163806.mail.gq1.yahoo.com>



> Subject: Re: [Tutor] Appending an extra column in a data file
> 
> On Wed, Apr 10, 2013 at 5:49 PM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>>> ? ? fin = open('old.dat')
>>> ? ? fout = open('new.dat', 'w')
>>> 
>>> ? ? with fin, fout:
>>> ? ? ? ? for line in fin:
>> 
>> This has the same problems as contextlib.nested: An error raised while
>> opening 'new.dat' could prevent 'old.dat' from being closed 
> properly.
> 
> Thanks for pointing out the potential bug there. It's not a big
> problem in this case with the file open for reading. But, yeah, I'm
> hanging my head in shame here... ;)

Cool. This solves a problem it had with contextlib.nested some time ago.
(sorry for kinda hijacking this thread, but..)
Would it be safe (both __exit__ calls are guaranteed to be made) to use
code?like this (if it worked, that is!)?

import sys
import contextlib

def someCloseFunc():
? print "Yaaay properly closed!"

@contextlib.contextmanager
def funcOne(arg):
? e = None
? try:
??? yield arg
? except:
??? e = sys.exc_info()[1]
??? print e
? finally:
??? someCloseFunc()
??? if e:
????? yield e
??? yield None

funcTwo = funcOne
with contextlib.nested(funcOne("one-ish"), funcTwo("two-ish")) as (one, two):
? print one, two

* traceback
one-ish two-ish
Yaaay properly closed!
generator didn't stop
Yaaay properly closed!

Traceback (most recent call last):
? File "F:/mgr.py", line 23, in <module>
??? print one, two
? File "C:\Program Files\Python27\lib\contextlib.py", line 24, in __exit__
??? self.gen.next()
? File "C:\Program Files\Python27\lib\contextlib.py", line 121, in nested
??? if exit(*exc):
? File "C:\Program Files\Python27\lib\contextlib.py", line 36, in __exit__
??? raise RuntimeError("generator didn't stop after throw()")
RuntimeError: generator didn't stop after throw()
>>> 

From fomcl at yahoo.com  Thu Apr 11 13:33:56 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 11 Apr 2013 04:33:56 -0700 (PDT)
Subject: [Tutor] Sharing Code Snippets
In-Reply-To: <CANODV3ksw9h6s0YgDUhhOLJbLrTOi7tVUjHQvB1Kd-ffr_pE0w@mail.gmail.com>
References: <CANODV3ksw9h6s0YgDUhhOLJbLrTOi7tVUjHQvB1Kd-ffr_pE0w@mail.gmail.com>
Message-ID: <1365680036.67436.YahooMailNeo@web163806.mail.gq1.yahoo.com>

> Subject: [Tutor] Sharing Code Snippets
> 
> Hello everyone,
> 
> I am not sure if this has been shared on this list. However, to help
> both those seeking help and those wanting to help, may I suggest that
> for all of you posting your programs, how about using a service such
> as GitHub's Gists [1]. It allows you to post entire programs with
> advantages such as intact code formatting, syntax highlighting and
> perhaps others such as version control.
> 
> I hope that's a useful suggestion.
> 
> [1] https://gist.github.com/

Hi,
?
Is this better than e.g. http://www.pastebin.com/? I wouldn't like it if the emails contain *only* links to such sites.
That way the information is lost forever if github decides to remove the code. Often these sites have expiration
dates for their contents.

Albert-Jan

From oscar.j.benjamin at gmail.com  Thu Apr 11 13:56:05 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Thu, 11 Apr 2013 12:56:05 +0100
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <1365679471.57539.YahooMailNeo@web163806.mail.gq1.yahoo.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
	<1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<CACL+1atWy5H1UHwaxPUMkWqBeu7bfJhaaTWKsHBmvNBPTX3RQQ@mail.gmail.com>
	<CAHVvXxRS8ZiLszxzzHaopZG6m70uP7KGHoPG0bxH1anmeP5mVw@mail.gmail.com>
	<CACL+1asS15TQFoNm9Z52M+uU7M5jwQGGGnbwx28PBgYzkq2E-w@mail.gmail.com>
	<1365679471.57539.YahooMailNeo@web163806.mail.gq1.yahoo.com>
Message-ID: <CAHVvXxS9dS5vui+i_qLq9jZxBXaRc51QW+_vB4vHykinpueJOA@mail.gmail.com>

On 11 April 2013 12:24, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>
>
>> Subject: Re: [Tutor] Appending an extra column in a data file
>>
>> On Wed, Apr 10, 2013 at 5:49 PM, Oscar Benjamin
>> <oscar.j.benjamin at gmail.com> wrote:
>>>>     fin = open('old.dat')
>>>>     fout = open('new.dat', 'w')
>>>>
>>>>     with fin, fout:
>>>>         for line in fin:
>>>
>>> This has the same problems as contextlib.nested: An error raised while
>>> opening 'new.dat' could prevent 'old.dat' from being closed
>> properly.
>>
>> Thanks for pointing out the potential bug there. It's not a big
>> problem in this case with the file open for reading. But, yeah, I'm
>> hanging my head in shame here... ;)
>
> Cool. This solves a problem it had with contextlib.nested some time ago.
> (sorry for kinda hijacking this thread, but..)
> Would it be safe (both __exit__ calls are guaranteed to be made) to use
> code like this (if it worked, that is!)?

Partly because it doesn't work I really can't figure out what you're
trying to do.

>
> import sys
> import contextlib
>
> def someCloseFunc():
>   print "Yaaay properly closed!"
>
> @contextlib.contextmanager
> def funcOne(arg):
>   e = None
>   try:
>     yield arg
>   except:
>     e = sys.exc_info()[1]
>     print e
>   finally:
>     someCloseFunc()
>     if e:

I guess you already know that the lines two lines below will break the
contextmanager decorator:

>       yield e
>     yield None
>

What effect are you actually wanting from the two lines below (I'm
assuming that you didn't want the error message shown)? Is it
significant that funcTwo is funcOne, or is that just to keep the
demonstration simple?

> funcTwo = funcOne
> with contextlib.nested(funcOne("one-ish"), funcTwo("two-ish")) as (one, two):
>   print one, two
>
> * traceback
> one-ish two-ish
> Yaaay properly closed!
> generator didn't stop
> Yaaay properly closed!
>
> Traceback (most recent call last):
>   File "F:/mgr.py", line 23, in <module>
>     print one, two
>   File "C:\Program Files\Python27\lib\contextlib.py", line 24, in __exit__
>     self.gen.next()
>   File "C:\Program Files\Python27\lib\contextlib.py", line 121, in nested
>     if exit(*exc):
>   File "C:\Program Files\Python27\lib\contextlib.py", line 36, in __exit__
>     raise RuntimeError("generator didn't stop after throw()")
> RuntimeError: generator didn't stop after throw()
>>>>


Oscar

From wayne at waynewerner.com  Thu Apr 11 14:16:26 2013
From: wayne at waynewerner.com (Wayne Werner)
Date: Thu, 11 Apr 2013 07:16:26 -0500 (CDT)
Subject: [Tutor] Looks like a judgment bug.
In-Reply-To: <51669C8B.2050001@gmail.com>
References: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>
	<51669C8B.2050001@gmail.com>
Message-ID: <alpine.DEB.2.02.1304110706460.3322@gilgamesh>

On Thu, 11 Apr 2013, Timo wrote:

> Op 11-04-13 12:41, w qj schreef:
>> I found this under Windows Python3
>>>>> l="http://f/"
>>>>> l[-1] is not '/'
>> False
>> and this under Linux Python3
>>>>> l = "http://ff.f/"
>>>>> l[-1]
>> '/'
>>>>> l[-1] is not '/'
>> True
>> 
>> It's Looks like a python bug?
> This looks like a "is not" versus "!=" thing. Someone (I think Steven 
> Apprano) posted a couple of days ago on this mailing list to only use "is" 
> and "is not" when comparing to None.

You're absolutely correct.

`is` compares the identity (basically id('/') == id('/') )

*sometimes* CPython will use a trick that caches smaller strings, so this 
might work one time:

     >>> x = '/'
     >>> y = '/'
     >>> x is y
     True

But then the next time you do the same thing it could return False. Or on 
a different OS. There's nothing (that I'm aware of) that will guarantee 
either result in this case.

In the example case we were comparing that `l[-1]` referred to the same 
spot in memory as the literal string `/`. And as the example showed, 
sometimes it will be, other times it won't.


The takeaway is to use `is` when you want to compare identity, and `==` 
when you want equaltiy. For example,

    That car is *my* car.

The car I'm referring to is one specific car. But if I were to say...

    My car is a Chevette.

That would be more like saying `car.model == 'Chevette'` - many different 
cars may actually be a Chevette.

HTH,
Wayne

From fomcl at yahoo.com  Thu Apr 11 14:25:35 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Thu, 11 Apr 2013 05:25:35 -0700 (PDT)
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <CAHVvXxS9dS5vui+i_qLq9jZxBXaRc51QW+_vB4vHykinpueJOA@mail.gmail.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
	<1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<CACL+1atWy5H1UHwaxPUMkWqBeu7bfJhaaTWKsHBmvNBPTX3RQQ@mail.gmail.com>
	<CAHVvXxRS8ZiLszxzzHaopZG6m70uP7KGHoPG0bxH1anmeP5mVw@mail.gmail.com>
	<CACL+1asS15TQFoNm9Z52M+uU7M5jwQGGGnbwx28PBgYzkq2E-w@mail.gmail.com>
	<1365679471.57539.YahooMailNeo@web163806.mail.gq1.yahoo.com>
	<CAHVvXxS9dS5vui+i_qLq9jZxBXaRc51QW+_vB4vHykinpueJOA@mail.gmail.com>
Message-ID: <1365683135.79702.YahooMailNeo@web163801.mail.gq1.yahoo.com>

<snip>

>> Cool. This solves a problem it had with contextlib.nested some time ago.
>> (sorry for kinda hijacking this thread, but..)
>> Would it be safe (both __exit__ calls are guaranteed to be made) to use
>> code like this (if it worked, that is!)?
> 
> Partly because it doesn't work I really can't figure out what you're
> trying to do.

You are right, I should have stated the goal: make contextlib.nested work in a way
that it does not have the shortcoming that caused it become deprecated, namely,
?__exit__?is not guaranteed to be called if the outer "with" raises an exception.
?

>> import sys
>> import contextlib
>> 
>> def someCloseFunc():
>> ? print "Yaaay properly closed!"
>> 
>> @contextlib.contextmanager
>> def funcOne(arg):
>> ? e = None
>> ? try:
>> ? ? yield arg
>> ? except:
>> ? ? e = sys.exc_info()[1]
>> ? ? print e
>> ? finally:
>> ? ? someCloseFunc()
>> ? ? if e:
> 
> I guess you already know that the lines two lines below will break the
> contextmanager decorator:
> 
>> ? ? ? yield e
>> ? ? yield None
>> 

?
Nope, I didn't realize that. Thank you.
?
> 
> What effect are you actually wanting from the two lines below (I'm
> assuming that you didn't want the error message shown)? Is it
> significant that funcTwo is funcOne, or is that just to keep the
> demonstration simple?
?
This is merely to keep the demonstration simple. And yes, I didn't want the error message.
?
> 
>> funcTwo = funcOne
>> with contextlib.nested(funcOne("one-ish"), 
> funcTwo("two-ish")) as (one, two):
>> ? print one, two
>> 
>> * traceback
>> one-ish two-ish
>> Yaaay properly closed!
>> generator didn't stop
>> Yaaay properly closed!
>> 
?
Two times "Yaaay properly closed!" means that __exit__ is called twice, right?
Anyway, the code below at least runs without errors. Too bad the outcommented
version with tuple unpacking raises an AttributeError.
?
import sys
import contextlib
?
def someCloseFunc():
? print "Yaaay properly closed!"
?
@contextlib.contextmanager
def funcOne(arg):
? try:
??? yield arg
? except:
??? yield sys.exc_info()[1]
? finally:
??? someCloseFunc()
funcTwo = funcOne

?
with contextlib.nested(funcOne("one-ish"), funcTwo("two-ish")) as (one, two):
? print one, two
?
##funcs = (funcOne, funcTwo)
##with contextlib.nested(*funcs) as (one, two):
##? print one("one-ish"), two("two-ish")

From oscar.j.benjamin at gmail.com  Thu Apr 11 14:49:15 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Thu, 11 Apr 2013 13:49:15 +0100
Subject: [Tutor] Appending an extra column in a data file
In-Reply-To: <1365683135.79702.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <CAAT-4OTNWEE_9B_0LcOHcMf7yqGc=+n4tzh0FTFs7YzyKD+A8g@mail.gmail.com>
	<7EB24525-9584-4F53-82BD-7DDC3E1102C3@gmail.com>
	<CAAT-4OSiN0qGimBaaHcNOkcGwFoSYt-aUx_Qw4FcWSnrfCbP5A@mail.gmail.com>
	<CAHVvXxSsifWTc4rcbKPgpLs2Zc+HE33mmW0sXr4L_2HCtR9sAg@mail.gmail.com>
	<1365626733.29241.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<CACL+1atWy5H1UHwaxPUMkWqBeu7bfJhaaTWKsHBmvNBPTX3RQQ@mail.gmail.com>
	<CAHVvXxRS8ZiLszxzzHaopZG6m70uP7KGHoPG0bxH1anmeP5mVw@mail.gmail.com>
	<CACL+1asS15TQFoNm9Z52M+uU7M5jwQGGGnbwx28PBgYzkq2E-w@mail.gmail.com>
	<1365679471.57539.YahooMailNeo@web163806.mail.gq1.yahoo.com>
	<CAHVvXxS9dS5vui+i_qLq9jZxBXaRc51QW+_vB4vHykinpueJOA@mail.gmail.com>
	<1365683135.79702.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <CAHVvXxTtJP3hTfRm-Ebn8G2UH6qzsT3PHaj5_Br4G--VLOEbWg@mail.gmail.com>

On 11 April 2013 13:25, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
> <snip>
>
>>> Cool. This solves a problem it had with contextlib.nested some time ago.
>>> (sorry for kinda hijacking this thread, but..)
>>> Would it be safe (both __exit__ calls are guaranteed to be made) to use
>>> code like this (if it worked, that is!)?
>>
>> Partly because it doesn't work I really can't figure out what you're
>> trying to do.
>
> You are right, I should have stated the goal: make contextlib.nested work in a way
> that it does not have the shortcoming that caused it become deprecated, namely,
>  __exit__ is not guaranteed to be called if the outer "with" raises an exception.

The problem with contextlib.nested is that it cannot catch errors
raised while its arguments are generated because nested hasn't even
been called yet. For example in the code

with nested(open('foo'), open('bar')) as foo, bar:
    do_stuff()

the expressions used as arguments to the nested function are evaluated
before nested is called. This is always true of function calls:

>>> def f1():
...     print('Calling f1')
...
>>> def f2():
...     print('Calling f2')
...
>>> def g(arg1, arg2):
...     print('Calling g')
...
>>> g(f1(), f2())
Calling f1
Calling f2
Calling g
>>> def f_broken():
...     raise ValueError
...
>>> g(f1(), f_broken())
Calling f1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in f_broken
ValueError

So if open raises an error nested is never called and the nested
context manager does not exist in order to call the __exit__ methods
of its arguments.

> Two times "Yaaay properly closed!" means that __exit__ is called twice, right?

Yes it does.

> Anyway, the code below at least runs without errors. Too bad the outcommented
> version with tuple unpacking raises an AttributeError.
>
> import sys
> import contextlib
>
> def someCloseFunc():
>   print "Yaaay properly closed!"
>
> @contextlib.contextmanager
> def funcOne(arg):
>   try:
>     yield arg
>   except:
>     yield sys.exc_info()[1]

Why do you want the two lines below? Attempting to yield twice gives
an error like the one you showed before:

>>> from contextlib import contextmanager
>>> @contextmanager
... def f():
...     try:
...         yield
...     except:
...         yield
...
>>> with f():
...     raise ValueError
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "q:\tools\Python27\lib\contextlib.py", line 36, in __exit__
    raise RuntimeError("generator didn't stop after throw()")
RuntimeError: generator didn't stop after throw()

The contextmanager decorator should be used with a generator function
that hits exactly one yield in its execution. That yield statement
corresponds to the code block in the with statement. There is nothing
for any other yield to correspond to.

>   finally:
>     someCloseFunc()
> funcTwo = funcOne
>
>
> with contextlib.nested(funcOne("one-ish"), funcTwo("two-ish")) as (one, two):
>   print one, two

Since there isn't really any way that funcOne or funcTwo would raise
an error when called there isn't any problem with using nested *in
this case*. The error would have to be raised before the yield
statement. If that's not really possible for any of the context
managers that you want to use then nested is fine and you can use it
without worry.

>
> ##funcs = (funcOne, funcTwo)
> ##with contextlib.nested(*funcs) as (one, two):
> ##  print one("one-ish"), two("two-ish")

That's because you're passing functions into nested rather than
calling the functions and passing the result into nested. Try this:

context_managers = (funcOne('one'), funcTwo('two'))
with contextlib.nested(*context_managers) as cms:
    # blah blah

Note that if you're happy using nested there's no problem with
creating the context managers on the line above.


Oscar

From ramit.prasad at jpmorgan.com  Thu Apr 11 22:01:48 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Thu, 11 Apr 2013 20:01:48 +0000
Subject: [Tutor] Running python from windows command prompt
In-Reply-To: <kk5l88$3s7$1@ger.gmane.org>
References: <OFAD847E91.059899AB-ON65257B49.0043D2EC-65257B49.0044EBB4@tcs.com>
	<kk47c1$f6p$1@ger.gmane.org>
	<OF0F3BBBA5.08F7A1D1-ON65257B4A.00216D63-65257B4A.0021BB2D@tcs.com>
	<kk5l88$3s7$1@ger.gmane.org>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474182E39B8@SCACMX008.exchad.jpmchase.net>

On 11/04/13 07:08, Arijit Ukil wrote:
> Thanks for the help. Now I have modifed the code as:
>
> import sys
>
> def main(argv):
>      data = int(sys.argv[1])
>      avg = average (data)
>      print "Average:", avg
>
> def average(num_list):
>      return sum(num_list)/len(num_list)

Note that in Python 2.2-2.7 if sum returns an integer the division
may not be what you expect. 
>>> 3/2
1
>>> 3/2.0
1.5

You may want to convert either the numerator or denominator
to a float. It does not matter which as long as one of them is 
a float.


~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.  

From etanes.rm at gmail.com  Fri Apr 12 00:33:16 2013
From: etanes.rm at gmail.com (Scurvy Scott)
Date: Thu, 11 Apr 2013 17:33:16 -0500
Subject: [Tutor] Guidance if possible
Message-ID: <CALyVa3WLiQE04wqpr71TuQ69=hv4O9NGC-8DKZawQ-7rGyvK8g@mail.gmail.com>

Hello again wonderful python tutor mailing list.

I've got I guess more of a broad question than is usually asked on
this list and perhaps some of you might find it annoying, that's fine,
if it's inappropriate feel free to say so.

I want to start work on a new python project that would visit a
specific companies contest site daily and everyday fill out the active
contest forms, as they allow you to enter once a day.

I've got an outline in my head but am a little green to know any of
the good web scraping/manipulation frameworks or if one is better than
the other for something like this. I have no intention of doing
anything professional/shady/annoying with this code and want to write
it purely for my own amusement as well as to learn and obviously to
perhaps win something cool.

Any information anyone feels like providing would be awesome, I'm
running Lubuntu 12.10, 2gb ram, old crappy notebook.

My basic outline goes something like this..

Everyday the program visits the site and scrapes the links for all the contests.
The program visits each contest page and verifies there is an entry
form, indicating that the contest is active
If the contest is active at that moment, it adds the title of the page
to a text file, if the contest is inactive it adds the title of the
page to a text file.
If the contest is active, it fills out the form with my details and sends it off
If the contest is inactive the title of the page is added to the
permanently blacklisted text file and never messed with again.

This might be a bit convoluted as well and any pointers are appreciated.

Scott

From alan.gauld at btinternet.com  Fri Apr 12 01:43:59 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 12 Apr 2013 00:43:59 +0100
Subject: [Tutor] Guidance if possible
In-Reply-To: <CALyVa3WLiQE04wqpr71TuQ69=hv4O9NGC-8DKZawQ-7rGyvK8g@mail.gmail.com>
References: <CALyVa3WLiQE04wqpr71TuQ69=hv4O9NGC-8DKZawQ-7rGyvK8g@mail.gmail.com>
Message-ID: <kk7hrr$kek$1@ger.gmane.org>

On 11/04/13 23:33, Scurvy Scott wrote:

> the other for something like this. I have no intention of doing
> anything professional/shady/annoying with this code and want to write
> it purely for my own amusement as well as to learn and obviously to
> perhaps win something cool.

Which is fine but you should still check the terms and conditions of the 
web sites because many such sites explicitly prohibit the use of  web 
scrapers. Using one could disqualify you from winning, and disguising 
the fact you are using one is non trivial.

> Everyday the program visits the site and scrapes the links for all the contests.
> The program visits each contest page and verifies there is an entry
> form, indicating that the contest is active
> If the contest is active at that moment, it adds the title of the page
> to a text file, if the contest is inactive it adds the title of the
> page to a text file.
> If the contest is active, it fills out the form with my details and sends it off
> If the contest is inactive the title of the page is added to the
> permanently blacklisted text file and never messed with again.
>
> This might be a bit convoluted as well and any pointers are appreciated.


Seems reasonable to me.

Try looking at the http, urllib and cookie stuff in the stdlib.
And then look at tools like Beautiful Soup and Element Tree for the 
content scraping bits.


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


From amitsaha.in at gmail.com  Fri Apr 12 02:28:47 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Fri, 12 Apr 2013 10:28:47 +1000
Subject: [Tutor] Sharing Code Snippets
In-Reply-To: <1365680036.67436.YahooMailNeo@web163806.mail.gq1.yahoo.com>
References: <CANODV3ksw9h6s0YgDUhhOLJbLrTOi7tVUjHQvB1Kd-ffr_pE0w@mail.gmail.com>
	<1365680036.67436.YahooMailNeo@web163806.mail.gq1.yahoo.com>
Message-ID: <CANODV3=jFYMnA8n-j7HSvSJtwkiSVM35E4M6zEghPeiO1Ng28A@mail.gmail.com>

On Thu, Apr 11, 2013 at 9:33 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
>> Subject: [Tutor] Sharing Code Snippets
>>
>> Hello everyone,
>>
>> I am not sure if this has been shared on this list. However, to help
>> both those seeking help and those wanting to help, may I suggest that
>> for all of you posting your programs, how about using a service such
>> as GitHub's Gists [1]. It allows you to post entire programs with
>> advantages such as intact code formatting, syntax highlighting and
>> perhaps others such as version control.
>>
>> I hope that's a useful suggestion.
>>
>> [1] https://gist.github.com/
>
> Hi,
>
> Is this better than e.g. http://www.pastebin.com/? I wouldn't like it if the emails contain *only* links to such sites.
> That way the information is lost forever if github decides to remove the code. Often these sites have expiration
> dates for their contents.

GitHub's Gists doesn't have an expiration date, since its primary
purpose is not a paste bin. But yes, I understand that if GitHub
decides to remove this service some day, the code is lost.

-Amit.



>
> Albert-Jan



--
http://amitsaha.github.com/

From steve at pearwood.info  Fri Apr 12 03:10:03 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 12 Apr 2013 11:10:03 +1000
Subject: [Tutor] Looks like a judgment bug.
In-Reply-To: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>
References: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>
Message-ID: <51675EEB.2050003@pearwood.info>

On 11/04/13 20:41, w qj wrote:
> I found this under Windows Python3
>>>> l="http://f/"
>>>> l[-1] is not '/'
> False
>>>>
>
> and this under Linux Python3
>>>> l = "http://ff.f/"
>>>> l[-1]
> '/'
>>>> l[-1] is not '/'
> True
>
> It's Looks like a python bug?



No, it is a bug in your understanding. The "is" and "is not" operators are for testing object identity, not equality. Python makes very few promises about object identity, and in this case both examples are fine. When you write this code:


l[-1] is not '/'  # where l[-1] == '/'


how does Python evaluate this expression?

First, it looks up l[-1], which creates a new object equal to the single-character string '/'. Then, Python evaluates the literal '/'. Now it has a choice: it might *reuse* the object that was just created a microsecond ago, or it might create a *new* object with the same value. Both behaviours are allowed, the language does not specify one or the other.

In the first case, you get one object referenced twice, and "is not" returns False. In the second case, you get two distinct objects referenced once each, and "is not" returns True. Both behaviours are correct, since Python doesn't promise when it will or won't create a new object in cases like this.

Whether Python creates two distinct objects or not will depend on the version of Python you use, the implementation, the operating system, possibly even the day of the week. (Well, probably not the last one, but it *could*.) No promises are made, and you cannot rely on one behaviour or the other.

You almost never need to use object identity, and should nearly always use == and != instead. Almost the only exception is when testing for the None singleton object.

# if one of the values is None, always use "is" or "is not":
if x is None

# for everything else, always use == or !=
x == '/'


There are some other exceptions, but they are rare.


For interest, I ran this expression under various different versions of Python:

print ('http://f/'[-1] is '/')


And these are the results I got:

Jython 2.5: False
IronPython 2.6: False
CPython:
   1.5: True
   2.4: True
   2.5: True
   2.6: True
   2.7: True
   3.1: False
   3.2: False
   3.3: True


Unless you have the exact same versions, built with the exact same compiler, on the exact same operating systems, you may get different results.




-- 
Steven

From steve at pearwood.info  Fri Apr 12 03:37:50 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 12 Apr 2013 11:37:50 +1000
Subject: [Tutor] Sharing Code Snippets
In-Reply-To: <CANODV3ksw9h6s0YgDUhhOLJbLrTOi7tVUjHQvB1Kd-ffr_pE0w@mail.gmail.com>
References: <CANODV3ksw9h6s0YgDUhhOLJbLrTOi7tVUjHQvB1Kd-ffr_pE0w@mail.gmail.com>
Message-ID: <5167656E.7040202@pearwood.info>

On 11/04/13 11:28, Amit Saha wrote:
> Hello everyone,
>
> I am not sure if this has been shared on this list. However, to help
> both those seeking help and those wanting to help, may I suggest that
> for all of you posting your programs, how about using a service such
> as GitHub's Gists [1]. It allows you to post entire programs with
> advantages such as intact code formatting, syntax highlighting and
> perhaps others such as version control.


Please don't. Small code snippets should be posted directly in the
body of the email, not on some external website.

They should be posted in PLAIN TEXT (do not use so-called
"rich-text", HTML formatted emails, since they destroy critical
indentation and make it difficult for those using plain-text email
clients to read your code). Like this:


import random

def coin_toss():
     if random.random() > 0.5:
         return "head"
     else:
         return "tail"


It's much less work for everyone to read code snippets in the email:
compare:

SENDER: copy and paste code directly into email

READER: read email
         write response


versus:

SENDER: open browser
         log in to external site
         copy and paste code into external site
         make sure code has been saved
         copy and paste url into email

READER: read email
         open browser
         copy and paste url
         fix url if it has been mangled by line-wrapping
         read code
         copy and paste back to email for the response


to say nothing about how it may effect those who use a screen reader. (They
generally work well with email, not so well with many websites.)

People may have access to their email, and be able to read and answer your
question, but they may not have access to the web. Perhaps they are behind
a firewall that blocks the website. For whatever reason, just because
somebody is reading your email doesn't mean that they can or will follow
to a website to read the important bit (the actual code). You should make
it *easy* for people to answer, not harder.

Code sharing sites are great for posting entire programs, but you, the
reader, shouldn't be posting entire programs and expecting us to work out
where the problem lies. Identify where the problem lies, and eliminate all
unnecessary code. Please read this for more details:

http://sscce.org/


-- 
Steven

From amitsaha.in at gmail.com  Fri Apr 12 04:53:04 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Fri, 12 Apr 2013 12:53:04 +1000
Subject: [Tutor] Looks like a judgment bug.
In-Reply-To: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>
References: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>
Message-ID: <CANODV3moNaqrB4nFyH+G6OpmkE6H_jV8oApKy0EL+Cztrk-oOg@mail.gmail.com>

On Thu, Apr 11, 2013 at 8:41 PM, w qj <after1990s at gmail.com> wrote:
> I found this under Windows Python3
>>>> l="http://f/"
>>>> l[-1] is not '/'
> False
>>>>
>
> and this under Linux Python3
>>>> l = "http://ff.f/"
>>>> l[-1]
> '/'
>>>> l[-1] is not '/'
> True
>
> It's Looks like a python bug?

No, this is not. The 'is' and 'is not' tests in Python are for
checking the identities of Python objects - a string, a single
character, a single number, everything is an object.

So for example:

>>> a=1
>>> b=1
>>> a is b
True
>>> id(a) == id(b)
True

When you perform the check, 'a is b', you are actually checking id(a)
== id(b). In this case, since I am really referring to the same
object, 1 with two different bindings - the identifier is the same.

In  your case, the check 'failed' on Windows and 'passed' on Linux, is
because in one case, the identifiers were the same, and in another
case it wasn't.  So, when are identifiers same and when not? That
depends on the type of object - mutable or immutable. You may want to
read up on Python's data model to learn more about this. Also, more on
"string interning" here. [1]

[1] http://stackoverflow.com/questions/15541404/python-string-interning

HTH,
Amit.



--
http://amitsaha.github.com/

From steve at pearwood.info  Fri Apr 12 05:36:33 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 12 Apr 2013 13:36:33 +1000
Subject: [Tutor] Looks like a judgment bug.
In-Reply-To: <CANODV3moNaqrB4nFyH+G6OpmkE6H_jV8oApKy0EL+Cztrk-oOg@mail.gmail.com>
References: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>
	<CANODV3moNaqrB4nFyH+G6OpmkE6H_jV8oApKy0EL+Cztrk-oOg@mail.gmail.com>
Message-ID: <51678141.6070809@pearwood.info>

On 12/04/13 12:53, Amit Saha wrote:

> So for example:
>
>>>> a=1
>>>> b=1
>>>> a is b
> True
>>>> id(a) == id(b)
> True


This is not a very good example, because that behaviour itself is implementation-dependent and not guaranteed. For example, in IronPython 2.6 I get completely different behaviour:

>>> a = 1
>>> b = 1
>>> a is b
False
>>> print id(a), id(b)
43 44


Even in CPython, the implementation you are probably using, the behaviour will depend on all sorts of factors, such as the type of the object, and even the value:

py> a = 10001
py> b = 10001
py> a is b
False

py> a = 1.0
py> b = 1.0
py> a is b
False




>So, when are identifiers same and when not? That
> depends on the type of object - mutable or immutable.

No, not really. The best you can say is this:

If Python has a choice between creating a new object, and re-using an existing object, and the object is mutable, Python will never re-use the object since that might introduce bugs. If the object is immutable, Python *may* re-use it, or it may not.


When does Python have a choice between re-using existing objects? That's a complicated question, and there's no straightforward answer. The best I can do is give some examples:


# References to a name will ALWAYS use the same object:
x is x  # always True


# References to another identifier MIGHT re-use the same object:
x.attr is x.attr  # sometimes True, sometimes False
x[index] is x[index]  # the same


# References to a literal MIGHT re-use the same object, if it is immutable:
'x' is 'x'  # might be True
['x'] is ['x']  # always False


# The same literal on the same line of code MIGHT be re-used:
x = 123.5; y = 123.5; x is y  # might be True

# ...even if they aren't re-used when on separate lines.
x = 123.5
y = 123.5
x is y  # probably will be False


# If two or more identifiers are assigned to a value at the same time,
# Python GUARANTEES to use the same object:
x = y = anything_you_like()
x is y  # always True


# Assignment in general never makes a new object:
x = something()
y = x
x is y  # always True[1]


Object identity is almost never important. About the only time it is important is when comparing things to None.

But in practice, you can expect (but not rely on!) CPython to re-use the following:

* Small integers. Which values count as small depend on the version, but -1 to 100 is common.

* Strings that look like identifiers, e.g. "x", "item", but not "hello world" or "?".

But don't rely on this, as it is not guaranteed and could go away at any time.




[1] Technically, if you change the current namespace to a custom dict type, you could do anything you like. But that's cheating, and it's harder than it sounds to change the current namespace.

-- 
Steven

From amitsaha.in at gmail.com  Fri Apr 12 05:42:50 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Fri, 12 Apr 2013 13:42:50 +1000
Subject: [Tutor] Looks like a judgment bug.
In-Reply-To: <51678141.6070809@pearwood.info>
References: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>
	<CANODV3moNaqrB4nFyH+G6OpmkE6H_jV8oApKy0EL+Cztrk-oOg@mail.gmail.com>
	<51678141.6070809@pearwood.info>
Message-ID: <CANODV3mWK7URKUvepDyqv_JUKGreO1+7R0SpPHBV8DiD=nVbRg@mail.gmail.com>

On Fri, Apr 12, 2013 at 1:36 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 12/04/13 12:53, Amit Saha wrote:
>
>> So for example:
>>
>>>>> a=1
>>>>> b=1
>>>>> a is b
>>
>> True
>>>>>
>>>>> id(a) == id(b)
>>
>> True
>
>
>
> This is not a very good example, because that behaviour itself is
> implementation-dependent and not guaranteed. For example, in IronPython 2.6
> I get completely different behaviour:
>
>>>> a = 1
>>>> b = 1
>>>> a is b
>
> False
>>>>
>>>> print id(a), id(b)
>
> 43 44
>
>
> Even in CPython, the implementation you are probably using, the behaviour
> will depend on all sorts of factors, such as the type of the object, and
> even the value:
>
> py> a = 10001
> py> b = 10001
> py> a is b
> False
>
> py> a = 1.0
> py> b = 1.0
> py> a is b
> False
>
>
>
>
>
>> So, when are identifiers same and when not? That
>> depends on the type of object - mutable or immutable.
>
>
> No, not really. The best you can say is this:
>
> If Python has a choice between creating a new object, and re-using an
> existing object, and the object is mutable, Python will never re-use the
> object since that might introduce bugs. If the object is immutable, Python
> *may* re-use it, or it may not.

Indeed. My point was to give the original poster at  least *some* idea
of what the issue really is. If he/she takes that hint and
experiments, reads the Python data model, and finds something weird
with that statement - he/she will discover the finer/exactly correct
details. So, thanks for clarifying this.


>
>
> When does Python have a choice between re-using existing objects? That's a
> complicated question, and there's no straightforward answer. The best I can
> do is give some examples:
>
>
> # References to a name will ALWAYS use the same object:
> x is x  # always True
>
>
> # References to another identifier MIGHT re-use the same object:
> x.attr is x.attr  # sometimes True, sometimes False
> x[index] is x[index]  # the same
>
>
> # References to a literal MIGHT re-use the same object, if it is immutable:
> 'x' is 'x'  # might be True
> ['x'] is ['x']  # always False
>
>
> # The same literal on the same line of code MIGHT be re-used:
> x = 123.5; y = 123.5; x is y  # might be True
>
> # ...even if they aren't re-used when on separate lines.
> x = 123.5
> y = 123.5
> x is y  # probably will be False
>
>
> # If two or more identifiers are assigned to a value at the same time,
> # Python GUARANTEES to use the same object:
> x = y = anything_you_like()
> x is y  # always True
>
>
> # Assignment in general never makes a new object:
> x = something()
> y = x
> x is y  # always True[1]
>
>
> Object identity is almost never important. About the only time it is
> important is when comparing things to None.
>
> But in practice, you can expect (but not rely on!) CPython to re-use the
> following:
>
> * Small integers. Which values count as small depend on the version, but -1
> to 100 is common.
>
> * Strings that look like identifiers, e.g. "x", "item", but not "hello
> world" or "?".

The link to the SO question discusses string interning to some detail.

>
> But don't rely on this, as it is not guaranteed and could go away at any
> time.

Yes, the 'is' check shouldn't really be relied on checks such as those
for None objects.

-Amit.
--
http://amitsaha.github.com/

From amitsaha.in at gmail.com  Fri Apr 12 05:45:26 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Fri, 12 Apr 2013 13:45:26 +1000
Subject: [Tutor] Looks like a judgment bug.
In-Reply-To: <CANODV3mWK7URKUvepDyqv_JUKGreO1+7R0SpPHBV8DiD=nVbRg@mail.gmail.com>
References: <CA+kK4UZhv94_QE-dCAy544aVLLD4j2vRLhyUYkd7T+BwRRdeBQ@mail.gmail.com>
	<CANODV3moNaqrB4nFyH+G6OpmkE6H_jV8oApKy0EL+Cztrk-oOg@mail.gmail.com>
	<51678141.6070809@pearwood.info>
	<CANODV3mWK7URKUvepDyqv_JUKGreO1+7R0SpPHBV8DiD=nVbRg@mail.gmail.com>
Message-ID: <CANODV3kFSmFOfJ3NfZdaqi_+KwZkNC6F_Qx_y9M24G7oAfaERw@mail.gmail.com>

On Fri, Apr 12, 2013 at 1:42 PM, Amit Saha <amitsaha.in at gmail.com> wrote:
> On Fri, Apr 12, 2013 at 1:36 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> On 12/04/13 12:53, Amit Saha wrote:
>>
>>> So for example:
>>>
>>>>>> a=1
>>>>>> b=1
>>>>>> a is b
>>>
>>> True
>>>>>>
>>>>>> id(a) == id(b)
>>>
>>> True
>>
>>
>>
>> This is not a very good example, because that behaviour itself is
>> implementation-dependent and not guaranteed. For example, in IronPython 2.6
>> I get completely different behaviour:
>>
>>>>> a = 1
>>>>> b = 1
>>>>> a is b
>>
>> False
>>>>>
>>>>> print id(a), id(b)
>>
>> 43 44
>>
>>
>> Even in CPython, the implementation you are probably using, the behaviour
>> will depend on all sorts of factors, such as the type of the object, and
>> even the value:
>>
>> py> a = 10001
>> py> b = 10001
>> py> a is b
>> False
>>
>> py> a = 1.0
>> py> b = 1.0
>> py> a is b
>> False
>>
>>
>>
>>
>>
>>> So, when are identifiers same and when not? That
>>> depends on the type of object - mutable or immutable.
>>
>>
>> No, not really. The best you can say is this:
>>
>> If Python has a choice between creating a new object, and re-using an
>> existing object, and the object is mutable, Python will never re-use the
>> object since that might introduce bugs. If the object is immutable, Python
>> *may* re-use it, or it may not.
>
> Indeed. My point was to give the original poster at  least *some* idea
> of what the issue really is. If he/she takes that hint and
> experiments, reads the Python data model, and finds something weird
> with that statement - he/she will discover the finer/exactly correct
> details. So, thanks for clarifying this.
>
>
>>
>>
>> When does Python have a choice between re-using existing objects? That's a
>> complicated question, and there's no straightforward answer. The best I can
>> do is give some examples:
>>
>>
>> # References to a name will ALWAYS use the same object:
>> x is x  # always True
>>
>>
>> # References to another identifier MIGHT re-use the same object:
>> x.attr is x.attr  # sometimes True, sometimes False
>> x[index] is x[index]  # the same
>>
>>
>> # References to a literal MIGHT re-use the same object, if it is immutable:
>> 'x' is 'x'  # might be True
>> ['x'] is ['x']  # always False
>>
>>
>> # The same literal on the same line of code MIGHT be re-used:
>> x = 123.5; y = 123.5; x is y  # might be True
>>
>> # ...even if they aren't re-used when on separate lines.
>> x = 123.5
>> y = 123.5
>> x is y  # probably will be False
>>
>>
>> # If two or more identifiers are assigned to a value at the same time,
>> # Python GUARANTEES to use the same object:
>> x = y = anything_you_like()
>> x is y  # always True
>>
>>
>> # Assignment in general never makes a new object:
>> x = something()
>> y = x
>> x is y  # always True[1]
>>
>>
>> Object identity is almost never important. About the only time it is
>> important is when comparing things to None.
>>
>> But in practice, you can expect (but not rely on!) CPython to re-use the
>> following:
>>
>> * Small integers. Which values count as small depend on the version, but -1
>> to 100 is common.
>>
>> * Strings that look like identifiers, e.g. "x", "item", but not "hello
>> world" or "?".
>
> The link to the SO question discusses string interning to some detail.
>
>>
>> But don't rely on this, as it is not guaranteed and could go away at any
>> time.
>
> Yes, the 'is' check shouldn't really be relied on checks such as those
> for None objects.


Correction: Yes, the 'is' check shouldn't really be relied on checks
other than checks for None objects (for example).


--
http://amitsaha.github.com/

From wayne at waynewerner.com  Fri Apr 12 13:11:33 2013
From: wayne at waynewerner.com (Wayne Werner)
Date: Fri, 12 Apr 2013 06:11:33 -0500 (CDT)
Subject: [Tutor] Guidance if possible
In-Reply-To: <kk7hrr$kek$1@ger.gmane.org>
References: <CALyVa3WLiQE04wqpr71TuQ69=hv4O9NGC-8DKZawQ-7rGyvK8g@mail.gmail.com>
	<kk7hrr$kek$1@ger.gmane.org>
Message-ID: <alpine.DEB.2.02.1304120609180.3322@gilgamesh>

On Fri, 12 Apr 2013, Alan Gauld wrote:

> On 11/04/13 23:33, Scurvy Scott wrote:
>
>> the other for something like this. I have no intention of doing
>> anything professional/shady/annoying with this code and want to write
>> it purely for my own amusement as well as to learn and obviously to
>> perhaps win something cool.
>
> Seems reasonable to me.
>
> Try looking at the http, urllib and cookie stuff in the stdlib.

Ick httplib/urllib - if you want to write code for getting information off 
a website, the 
requests module is the way to go:

http://docs.python-requests.org/en/latest/

It makes http requests pretty trivial.

HTH,
Wayne

From sbjaved at gmail.com  Sat Apr 13 01:52:52 2013
From: sbjaved at gmail.com (Saad Bin Javed)
Date: Sat, 13 Apr 2013 04:52:52 +0500
Subject: [Tutor] creating dictionary from a list
Message-ID: <51689E54.1010708@gmail.com>

Hi, I'm using a script to fetch my calendar events. I split the output 
at newline which produced a list 'lst'. I'm trying to clean it up and 
create a dictionary with date:event key value pairs. However this is 
throwing up a bunch of errors.

lst = ['', 'Thu Apr 04           Weigh In', '', 'Sat Apr 06 
Collect NIC', \
'                     Finish PTI Video', '', 'Wed Apr 10           Serum 
uric acid test', \
'', 'Sat Apr 13   1:00pm  Get flag from dhariwal', '', 'Sun Apr 14 
      Louis CK Oh My God', '', '']

dict = {}
same_day = ''
for x in lst:
	c = x.split('           ')
	if c[0] is '':
		for q in c:
			if q is not '':
				dict.update({same_day: dict[same_day] + ', ' + q.strip()})
				break
	else:
		if c[0].find('  '):
			print c[0]
			a = c[0].split('  ', 1)
			same_day = a[0]
			print a[0], a[1].lstrip()
			dict.update({a[0] : a[1].lstrip()})
		else:
			same_day = c[0]
			dict.update({c[0] : c[1]})

I want a dictionary thats like this {'Thu Apr 04': 'Weigh In', 'Sat Apr 
13': '1:00pm  Get flag from dhariwal'...}

Saad

From steve at pearwood.info  Sat Apr 13 03:22:37 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 13 Apr 2013 11:22:37 +1000
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <51689E54.1010708@gmail.com>
References: <51689E54.1010708@gmail.com>
Message-ID: <5168B35D.2060207@pearwood.info>

On 13/04/13 09:52, Saad Bin Javed wrote:
> Hi, I'm using a script to fetch my calendar events. I split the output at newline which produced a list 'lst'. I'm trying to clean it up and create a dictionary with date:event key value pairs. However this is throwing up a bunch of errors.


Would you like us to guess what the errors are? Please copy and paste the complete traceback, starting with the line

Traceback (most recent line last)

all the way to the end.


In the meantime, my comments are below, interleaved with your code:



> lst = ['', 'Thu Apr 04           Weigh In', '', 'Sat Apr 06 Collect NIC', \
> '                     Finish PTI Video', '', 'Wed Apr 10           Serum uric acid test', \
> '', 'Sat Apr 13   1:00pm  Get flag from dhariwal', '', 'Sun Apr 14      Louis CK Oh My God', '', '']


There's no need to use line-continuation backslash \ inside a list. Any form of bracket (round, square or curly) automatically continues the line.

Also, you might find it easier to process the list if you strip out empty items. There are two simple ways to do it:


lst = [x for x in list if x != '']
# or
lst = filter(None, lst)


Either way should work nicely on the data shown, and that might then simplify your processing below.



> dict = {}
> same_day = ''
> for x in lst:
>      c = x.split('           ')

It's best not to rely on an exact number of spaces for the separation, if you can. If you call split() with no argument, the string will be split on runs of whitespace. If you must depend on the difference between one space and two spaces, it's probably best to split on "  " (two spaces only), then delete any extra empty strings, as above.

Also, please try to use more meaningful variable names. In this case, I would suggest "words" instead of "c". ("c" for "character"?)



>      if c[0] is '':

Do you read the other emails on this tutor list? You should, you will learn a lot from other people's questions. We've just had a few emails explaining that you should never use "is" to test equality, since "is" tests for object identity. So, repeating myself from the last few emails:

* always use "if x is None" or "if x is not None" when comparing against None;

* otherwise, never use "is", always use == or != when comparing against (nearly) everything else.


("Always" and "never" of course are understood to be general rules which may be ignored by experts when necessary.)

So replace the line above with "if c[0] == '':".



>          for q in c:
>              if q is not '':

Likewise, replace this with "if q != '':".



>                  dict.update({same_day: dict[same_day] + ', ' + q.strip()})
>                  break

I'm not sure why you use a "break" here. That will stop processing the entire list. Is that intended? Maybe you meant to use "continue"?



>      else:
>          if c[0].find('  '):

You can save an indentation level by using "elif" here.


if test1:
     ...
else:
     if test2:
         ...
     else:
         ...

becomes more nicely written as:

if test1:
     ...
elif test2:
     ...
else:
     ...



>              print c[0]
>              a = c[0].split('  ', 1)
>              same_day = a[0]
>              print a[0], a[1].lstrip()

You can simplify your processing here by assigning directly to a list of names. Instead of:

a = c[0].split('  ', 1)
process(a[0])
process(a[1])


you can give each item a name directly:


same_day, text = c[0].split('  ', 1)
process(same_day)
process(text)


which makes your code cleaner and easier to understand.



>              dict.update({a[0] : a[1].lstrip()})
>          else:
>              same_day = c[0]
>              dict.update({c[0] : c[1]})

If you're going to assign a value to a name, why don't you actually use the name?

same_day = c[0]
dict.update({same_day: c[1]})



Try making the changes I've suggested, and see if that makes the code cleaner and easier to understand. It might even fix some of the errors that you are getting.

Good luck!



-- 
Steven

From sbjaved at gmail.com  Sat Apr 13 06:00:26 2013
From: sbjaved at gmail.com (Saad Bin Javed)
Date: Sat, 13 Apr 2013 09:00:26 +0500
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <51689E54.1010708@gmail.com>
References: <51689E54.1010708@gmail.com>
Message-ID: <5168D85A.10008@gmail.com>

Thank you Steven! I followed your tips and came up with this:

lst = filter(None, lst)
lst = [item.split('  ', 1) for item in lst]
lst = [item for sublist in lst for item in sublist]
lst = filter(None, lst)

dict = {}
for item in lst:
	if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
		
		dict.update({lst[lst.index(item)].lstrip(): 
lst[lst.index(item)+1].lstrip()})
print dict

The program lines have halved :)

From fomcl at yahoo.com  Sat Apr 13 09:34:42 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 13 Apr 2013 00:34:42 -0700 (PDT)
Subject: [Tutor] design question (Django?)
Message-ID: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>

Hi,

I am doing volunteer work for a charity. The job is to coordinate money collecting activities of people who
raise money with collecting-boxes. I am involved with one postal code? 4 (pc4) area (our postal codes have the format 1234 AB (postal code 6). So 'one postal code 4 area'? means [0-9]{4}[A-Z]{2} (1234AA, 1234AB, etc.). One pc4 area is typically divided over a group of 8 people who actually go out there to collect the money.

I would like to make a webtool that makes it possible for collectors to select what streets they want to visit.
Other collectors of their pc4 area should also be able to see their selection, once it's final (it's a BIG no-no that the same street is visited by multiple collectors in the same week). Selection would be done by selecting street names or pc6 (tick boxes). A selection would be visualized on a map (a different color for each collector). The number of households associated with the selection is shown to see if the selection is a realistic amount.

Now, this is where Python comes in. Or wait, maybe not quite yet. The problem should (I think) be divided into two major steps: (1) database design (2) UI design (Python, I hope!)

(1) Database design. Here are the database tables I think are necessary:
tblPostalcode: pc6, streetname, nHouseholds, isVisitable, remarks
tblCollectorSelection: collectorname, streetname, selectiondate

(2) UI design. Ah, finally, Python. ;-) I had Django in mind to create the web interface and GeoDjango to display the selection on a map. I am open for other suggestions though (D3?). I am not even sure how realistic this is, given that I have zilch experience with web programming (and Java script). The whole thing should be non-geeky, non-techy for users.

I would love to hear your thoughts about this. Does this make sense? Is Django a good choice?

Regards,
Albert-Jan

ps: sorry about the large amount of text. ;-)


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?

From alan.gauld at btinternet.com  Sat Apr 13 10:00:12 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 13 Apr 2013 09:00:12 +0100
Subject: [Tutor] design question (Django?)
In-Reply-To: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
Message-ID: <kkb3a8$b2a$1@ger.gmane.org>

Some clarification please.

> (1) Database design. Here are the database tables I think are necessary:
> tblPostalcode: pc6, streetname, nHouseholds, isVisitable, remarks
> tblCollectorSelection: collectorname, streetname, selectiondate

streetname is in both so presumably is the link between collector and 
the postcodes? Can a steetname be in multiple postcodes? So if a 
collector selects a street does he implicitly select multiple post codes?

And

Does a postcode only have a single street? (Ours can have several)

I assume isVisitable is a derived field that you are going to calculate 
each time based on the number of collectors who have selected the 
postcode? If so it may be easier and more efficient to have a mapping 
table to manage the relationship of collectors to postcodes and another 
table for the collector data (although you don't appear to be holding 
much collector data, which surprises me... I assume the users will be 
collectors with login credentials etc?)

As always when modelling data the important information is the 
relationships between the entities and I'm not sure I understand
the relationships between street, postcode and collector.

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


From fomcl at yahoo.com  Sat Apr 13 10:48:01 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 13 Apr 2013 01:48:01 -0700 (PDT)
Subject: [Tutor] design question (Django?)
In-Reply-To: <kkb3a8$b2a$1@ger.gmane.org>
References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkb3a8$b2a$1@ger.gmane.org>
Message-ID: <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com>

Hi Alan,

Thanks for your reply!


> Subject: Re: [Tutor] design question (Django?)

> 
> Some clarification please.
> 
>>  (1) Database design. Here are the database tables I think are necessary:
>>  tblPostalcode: pc6, streetname, nHouseholds, isVisitable, remarks
>>  tblCollectorSelection: collectorname, streetname, selectiondate
> 
> streetname is in both so presumably is the link between collector and the 
> postcodes? Can a steetname be in multiple postcodes? So if a collector selects a 
> street does he implicitly select multiple post codes?

Yes, a street name can be in multiple postcodes (typically odd and even street numbers of long streets have different postcodes). For example, postcodes (pc4) of the longest street of the country (in The Hague) are 2517, 2555:
http://www.postcode.nl/index.php?goto=postcoderesult&action=page&pagenum=0&address=den+haag%2C+Laan+van+Meerdervoort&TreeID=1 So, yes, the collector may select multiple postcodes when selecting just one street. Historically, pc6 is a concept from the mail service. One pc6 is (literally) a handful of mail for a mailman. One record in tblCollectorSelection = one pc6 selected by that collector. But since most people think in terms of street names rather than in pc6, the selection is made by ticking boxes with street names.

Come to think of it, I may also need a tblCollectors, with name, adress, postal code, phone number of the collector, preferredPostalCode (some collectors want to collect in another pc6 than where they live).
?
> Does a postcode only have a single street? (Ours can have several)

It's the same as with you in the UK/Scotland. Often one postcode has just one street, but there are exceptions.

> I assume isVisitable is a derived field that you are going to calculate each 
> time based on the number of collectors who have selected the postcode? 

isVisitable would be PO boxes, apartment buildings that do not admit any collectors at their main entrance,
industrial zones, dangerous neighbourhoods, and maybe a few more categories.

>If so it 
> may be easier and more efficient to have a mapping table to manage the 
> relationship of collectors to postcodes and another table for the collector data 
> (although you don't appear to be holding much collector data, which 
> surprises me... I assume the users will be collectors with login credentials 
> etc?)

yes, collectors are assigned to groups (of about 8 persons) and they should get login credentials (which are stored in tblCollectors (?)).

> As always when modelling data the important information is the relationships 
> between the entities and I'm not sure I understand
> the relationships between street, postcode and collector.

I think I have to make a diagram of this. This stuff is quite hard for me, but it's important to get the basis right.

From brian.van.den.broek at gmail.com  Sat Apr 13 10:51:59 2013
From: brian.van.den.broek at gmail.com (Brian van den Broek)
Date: Sat, 13 Apr 2013 04:51:59 -0400
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <5168B35D.2060207@pearwood.info>
References: <51689E54.1010708@gmail.com>
	<5168B35D.2060207@pearwood.info>
Message-ID: <CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>

On 12 Apr 2013 21:25, "Steven D&apos;Aprano" <steve at pearwood.info> wrote:

> Also, you might find it easier to process the list if you strip out empty
items. There are two simple ways to do it:
>
>
> lst = [x for x in list if x != '']
> # or
> lst = filter(None, lst)

Hi all,

For the first, I would use

lst = [x for x in list if x]

instead.

Best,

Brian vdB
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130413/8266449c/attachment.html>

From alan.gauld at btinternet.com  Sat Apr 13 14:11:50 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 13 Apr 2013 13:11:50 +0100
Subject: [Tutor] design question (Django?)
In-Reply-To: <1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com>
References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkb3a8$b2a$1@ger.gmane.org>
	<1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com>
Message-ID: <kkbi22$99c$1@ger.gmane.org>

On 13/04/13 09:48, Albert-Jan Roskam wrote:

> I think I have to make a diagram of this. This stuff is quite hard

You could use a simple UML class diagram (class -> table). See the OOP 
topic in my V3 tutorial for simple examples.

Or you could use a proper entity relationship diagram(ERD) - see 
wikipedia for details and examples (there are various notational variations)

They all show the same concepts. UML will be best if you plan
on using OOP in the python code. ERD is better for vanilla database design.

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


From sbjaved at gmail.com  Sat Apr 13 16:34:49 2013
From: sbjaved at gmail.com (Saad Bin Javed)
Date: Sat, 13 Apr 2013 19:34:49 +0500
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
Message-ID: <51696D09.4000103@gmail.com>

I ran into a bit of problem with my revised code based on Steven's 
suggestions.

lst = ['', 'Thu Apr 04           Weigh In', '', 'Sat Apr 06 Collect 
NIC', '                     Finish PTI Video', '', 'Wed Apr 10 
  Serum uric acid test', '', 'Sat Apr 13   1:00pm  Get flag from 
dhariwal', '', 'Sun Apr 14      Louis CK Oh My God', '', '']

lst = filter(None, lst)
lst = [item.split('  ') for item in lst]
lst = [item for sublist in lst for item in sublist]
lst = filter(None, lst)

This code would produce:

['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI 
Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm', 
'Get flag from dhariwal', 'Sun Apr 14', ' Download Louis CK Oh My God']

dict = {}
for item in lst:
     if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):

         dict.update({lst[lst.index(item)].lstrip(): 
lst[lst.index(item)+1].lstrip()})
print dict

Such a dictionary would only add the item next to the date as the value. 
But from the list you can see 'Sat Apr 06' has two items on the agenda 
while 'Sat Apr 13' show item and a time. So you can understand why such 
a dict would be useless.

I want all agenda items joined as a comma delimited string and added to 
the date key as a value. I've been mulling over how to go about it. One 
idea was to get indices of dates in the list and add all items in 
between them as values.

index_keys = [] #0, 2, 5, 7, 9
index_values = [] #1, 3, 4, 6, 8, 10
for item in lst:
	if item.lstrip().startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
		index_keys.append(lst.index(item))
	else:
		index_values.append(lst.index(item))

But I can't quite get it to understand that i want all items between 
position 0 and 2 in the list to be assigned to item at 0 in the 
dictionary and so forth.

Ideas?


From breamoreboy at yahoo.co.uk  Sat Apr 13 17:17:42 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 13 Apr 2013 16:17:42 +0100
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <51696D09.4000103@gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com>
Message-ID: <kkbssn$cei$1@ger.gmane.org>

On 13/04/2013 15:34, Saad Bin Javed wrote:
> I ran into a bit of problem with my revised code based on Steven's
> suggestions.
>
> lst = ['', 'Thu Apr 04           Weigh In', '', 'Sat Apr 06 Collect
> NIC', '                     Finish PTI Video', '', 'Wed Apr 10  Serum
> uric acid test', '', 'Sat Apr 13   1:00pm  Get flag from dhariwal', '',
> 'Sun Apr 14      Louis CK Oh My God', '', '']
>
> lst = filter(None, lst)
> lst = [item.split('  ') for item in lst]
> lst = [item for sublist in lst for item in sublist]
> lst = filter(None, lst)
>
> This code would produce:
>
> ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI
> Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm',
> 'Get flag from dhariwal', 'Sun Apr 14', ' Download Louis CK Oh My God']
>
> dict = {}
> for item in lst:
>      if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
>
>          dict.update({lst[lst.index(item)].lstrip():
> lst[lst.index(item)+1].lstrip()})
> print dict
>
> Such a dictionary would only add the item next to the date as the value.
> But from the list you can see 'Sat Apr 06' has two items on the agenda
> while 'Sat Apr 13' show item and a time. So you can understand why such
> a dict would be useless.
>
> I want all agenda items joined as a comma delimited string and added to
> the date key as a value. I've been mulling over how to go about it. One
> idea was to get indices of dates in the list and add all items in
> between them as values.
>
> index_keys = [] #0, 2, 5, 7, 9
> index_values = [] #1, 3, 4, 6, 8, 10
> for item in lst:
>      if
> item.lstrip().startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
>          index_keys.append(lst.index(item))
>      else:
>          index_values.append(lst.index(item))
>
> But I can't quite get it to understand that i want all items between
> position 0 and 2 in the list to be assigned to item at 0 in the
> dictionary and so forth.
>
> Ideas?
>

Don't fight Python, unlike this chap[1] :)  Basically if you're looping 
around any data structure you rarely need to use indexing, so try this 
approach.

for item in lst:
     if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
         myDict[item] = []
         saveItem = item
     else:
         myDict[saveItem].append(item.strip())


[1]http://www.bbc.co.uk/news/world-us-canada-22118773

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From sbjaved at gmail.com  Sat Apr 13 19:38:32 2013
From: sbjaved at gmail.com (Saad Javed)
Date: Sat, 13 Apr 2013 22:38:32 +0500
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <kkbssn$cei$1@ger.gmane.org>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
Message-ID: <CAJ5mJ2uf55Xg5VELQDV-M-c8Jq0WyWLRx40EXXp8On_-D7o4ZA@mail.gmail.com>

What just happened here? :)

I am trying to learn python so i'm sorry if my mistakes seem trivial.

On Saturday, April 13, 2013, Mark Lawrence wrote:

> On 13/04/2013 15:34, Saad Bin Javed wrote:
>
>> I ran into a bit of problem with my revised code based on Steven's
>> suggestions.
>>
>> lst = ['', 'Thu Apr 04           Weigh In', '', 'Sat Apr 06 Collect
>> NIC', '                     Finish PTI Video', '', 'Wed Apr 10  Serum
>> uric acid test', '', 'Sat Apr 13   1:00pm  Get flag from dhariwal', '',
>> 'Sun Apr 14      Louis CK Oh My God', '', '']
>>
>> lst = filter(None, lst)
>> lst = [item.split('  ') for item in lst]
>> lst = [item for sublist in lst for item in sublist]
>> lst = filter(None, lst)
>>
>> This code would produce:
>>
>> ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI
>> Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm',
>> 'Get flag from dhariwal', 'Sun Apr 14', ' Download Louis CK Oh My God']
>>
>> dict = {}
>> for item in lst:
>>      if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**:
>>
>>          dict.update({lst[lst.index(**item)].lstrip():
>> lst[lst.index(item)+1].lstrip(**)})
>> print dict
>>
>> Such a dictionary would only add the item next to the date as the value.
>> But from the list you can see 'Sat Apr 06' has two items on the agenda
>> while 'Sat Apr 13' show item and a time. So you can understand why such
>> a dict would be useless.
>>
>> I want all agenda items joined as a comma delimited string and added to
>> the date key as a value. I've been mulling over how to go about it. One
>> idea was to get indices of dates in the list and add all items in
>> between them as values.
>>
>> index_keys = [] #0, 2, 5, 7, 9
>> index_values = [] #1, 3, 4, 6, 8, 10
>> for item in lst:
>>      if
>> item.lstrip().startswith(('**Mon','Tue','Wed','Thu','Fri','**
>> Sat','Sun')):
>>          index_keys.append(lst.index(**item))
>>      else:
>>          index_values.append(lst.index(**item))
>>
>> But I can't quite get it to understand that i want all items between
>> position 0 and 2 in the list to be assigned to item at 0 in the
>> dictionary and so forth.
>>
>> Ideas?
>>
>>
> Don't fight Python, unlike this chap[1] :)  Basically if you're looping
> around any data structure you rarely need to use indexing, so try this
> approach.
>
> for item in lst:
>     if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**:
>         myDict[item] = []
>         saveItem = item
>     else:
>         myDict[saveItem].append(item.**strip())
>
>
> [1]http://www.bbc.co.uk/news/**world-us-canada-22118773<http://www.bbc.co.uk/news/world-us-canada-22118773>
>
> --
> If you're using GoogleCrap? please read this http://wiki.python.org/moin/*
> *GoogleGroupsPython <http://wiki.python.org/moin/GoogleGroupsPython>.
>
> Mark Lawrence
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130413/8346c1d7/attachment.html>

From sbjaved at gmail.com  Sat Apr 13 20:19:58 2013
From: sbjaved at gmail.com (Saad Javed)
Date: Sat, 13 Apr 2013 23:19:58 +0500
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <kkbssn$cei$1@ger.gmane.org>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
Message-ID: <CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>

>
> Don't fight Python, unlike this chap[1] :)  Basically if you're looping
> around any data structure you rarely need to use indexing, so try this
> approach.
>
> for item in lst:
>     if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**:
>         myDict[item] = []
>         saveItem = item
>     else:
>         myDict[saveItem].append(item.**strip())
>

This creates a dictionary whose keys are out of order in terms of dates.

{'Thu Apr 04': ['Weigh In'], 'Sat Apr 06': ['Collect NIC', 'Finish PTI
Video'], 'Wed Apr 10': ['Serum uric acid test'], 'Sun Apr 14': ['Download
Louis CK Oh My God', '4:00pm', 'UPS Guy'], 'Sat Apr 13': ['1:00pm', 'Get
flag from dhariwal']}

Sat Apr 13 is appearing after Sun Apr 14. How do you sort this?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130413/579ef478/attachment-0001.html>

From breamoreboy at yahoo.co.uk  Sat Apr 13 20:29:00 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 13 Apr 2013 19:29:00 +0100
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
Message-ID: <kkc83e$krr$1@ger.gmane.org>

On 13/04/2013 19:19, Saad Javed wrote:
>
>
>     Don't fight Python, unlike this chap[1] :)  Basically if you're
>     looping around any data structure you rarely need to use indexing,
>     so try this approach.
>
>     for item in lst:
>          if
>     item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__:
>              myDict[item] = []
>              saveItem = item
>          else:
>              myDict[saveItem].append(item.__strip())
>
>
> This creates a dictionary whose keys are out of order in terms of dates.
>
> {'Thu Apr 04': ['Weigh In'], 'Sat Apr 06': ['Collect NIC', 'Finish PTI
> Video'], 'Wed Apr 10': ['Serum uric acid test'], 'Sun Apr 14':
> ['Download Louis CK Oh My God', '4:00pm', 'UPS Guy'], 'Sat Apr 13':
> ['1:00pm', 'Get flag from dhariwal']}
>
> Sat Apr 13 is appearing after Sun Apr 14. How do you sort this?
>

http://docs.python.org/3/library/collections.html#collections.OrderedDict

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From sbjaved at gmail.com  Sat Apr 13 20:45:43 2013
From: sbjaved at gmail.com (Saad Javed)
Date: Sat, 13 Apr 2013 23:45:43 +0500
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <kkc83e$krr$1@ger.gmane.org>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
Message-ID: <CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>

>     for item in lst:
>>          if
>>     item.startswith(('Mon','Tue','**__Wed','Thu','Fri','Sat','Sun'**))__:
>>              myDict[item] = []
>>              saveItem = item
>>          else:
>>              myDict[saveItem].append(item._**_strip())
>>
>> Returns:
 File "gcalcli_agenda_test.py", line 38
    if item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__:
                                                                      ^
SyntaxError: invalid syntax
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130413/14f78b84/attachment.html>

From breamoreboy at yahoo.co.uk  Sat Apr 13 21:08:13 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 13 Apr 2013 20:08:13 +0100
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
	<CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
Message-ID: <kkcacv$a75$1@ger.gmane.org>

On 13/04/2013 19:45, Saad Javed wrote:
>
>              for item in lst:
>                   if
>
>         item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
>                       myDict[item] = []
>                       saveItem = item
>                   else:
>                       myDict[saveItem].append(item.____strip())
>
> Returns:
>   File "gcalcli_agenda_test.py", line 38
>      if item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__:
>                                                                        ^
> SyntaxError: invalid syntax
>

Please compare your original line with the line above and note the 
differences.  That'll account for the syntax error, which appears to 
have been introduced by your email client.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From sbjaved at gmail.com  Sat Apr 13 21:30:51 2013
From: sbjaved at gmail.com (Saad Bin Javed)
Date: Sun, 14 Apr 2013 00:30:51 +0500
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <kkcacv$a75$1@ger.gmane.org>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
	<CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
	<kkcacv$a75$1@ger.gmane.org>
Message-ID: <5169B26B.1050707@gmail.com>

On 04/14/2013 12:08 AM, Mark Lawrence wrote:
> On 13/04/2013 19:45, Saad Javed wrote:
>>
>>              for item in lst:
>>                   if
>>
>>
>> item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
>>                       myDict[item] = []
>>                       saveItem = item
>>                   else:
>>                       myDict[saveItem].append(item.____strip())
>>
>> Returns:
>>   File "gcalcli_agenda_test.py", line 38
>>      if item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__:
>>                                                                        ^
>> SyntaxError: invalid syntax
>>
>
> Please compare your original line with the line above and note the
> differences.  That'll account for the syntax error, which appears to
> have been introduced by your email client.
>
This is what I'm using:

for item in lst:
	if item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
		dict[item] = []
		saveItem = item
	else:
		dict[saveItem].append(item.____strip())

gives:
  File "gcalcli_agenda_test.py", line 39
     if 
item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
                                                                       ^
SyntaxError: invalid syntax



From breamoreboy at yahoo.co.uk  Sat Apr 13 21:56:55 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 13 Apr 2013 20:56:55 +0100
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <5169B26B.1050707@gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
	<CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
	<kkcacv$a75$1@ger.gmane.org> <5169B26B.1050707@gmail.com>
Message-ID: <kkcd8a$33b$1@ger.gmane.org>

On 13/04/2013 20:30, Saad Bin Javed wrote:
> On 04/14/2013 12:08 AM, Mark Lawrence wrote:
>> On 13/04/2013 19:45, Saad Javed wrote:
>>>
>>>              for item in lst:
>>>                   if
>>>
>>>
>>> item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
>>>                       myDict[item] = []
>>>                       saveItem = item
>>>                   else:
>>>                       myDict[saveItem].append(item.____strip())
>>>
>>> Returns:
>>>   File "gcalcli_agenda_test.py", line 38
>>>      if
>>> item.startswith(('Mon','Tue','__Wed','Thu','Fri','Sat','Sun'))__:
>>>                                                                        ^
>>> SyntaxError: invalid syntax
>>>
>>
>> Please compare your original line with the line above and note the
>> differences.  That'll account for the syntax error, which appears to
>> have been introduced by your email client.
>>
> This is what I'm using:
>
> for item in lst:
>      if
> item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
>          dict[item] = []
>          saveItem = item
>      else:
>          dict[saveItem].append(item.____strip())
>
> gives:
>   File "gcalcli_agenda_test.py", line 39
>      if
> item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
>                                                                        ^
> SyntaxError: invalid syntax
>

Please compare your original line with the line above and note the
differences.  That'll account for the syntax error, which appears to
have been introduced by your email client.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From sbjaved at gmail.com  Sat Apr 13 22:06:30 2013
From: sbjaved at gmail.com (Saad Javed)
Date: Sun, 14 Apr 2013 01:06:30 +0500
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <kkcd8a$33b$1@ger.gmane.org>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
	<CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
	<kkcacv$a75$1@ger.gmane.org> <5169B26B.1050707@gmail.com>
	<kkcd8a$33b$1@ger.gmane.org>
Message-ID: <CAJ5mJ2uq3ZykHCwX9n-ucitYdujz5_LLF4vBSnskOgPtgCbnpQ@mail.gmail.com>

I don't know what I'm doing wrong here. Ive tried copy-pasting the line.
I've tried entering underscores manually. doesn't work.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130414/bf6354e9/attachment.html>

From breamoreboy at yahoo.co.uk  Sat Apr 13 22:24:03 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 13 Apr 2013 21:24:03 +0100
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <CAJ5mJ2uq3ZykHCwX9n-ucitYdujz5_LLF4vBSnskOgPtgCbnpQ@mail.gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
	<CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
	<kkcacv$a75$1@ger.gmane.org> <5169B26B.1050707@gmail.com>
	<kkcd8a$33b$1@ger.gmane.org>
	<CAJ5mJ2uq3ZykHCwX9n-ucitYdujz5_LLF4vBSnskOgPtgCbnpQ@mail.gmail.com>
Message-ID: <kkcer5$imu$1@ger.gmane.org>

On 13/04/2013 21:06, Saad Javed wrote:
> I don't know what I'm doing wrong here. Ive tried copy-pasting the line.
> I've tried entering underscores manually. doesn't work.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

The underscores are the syntax error.  If you'd bothered to read my 
previous two replies and actually compared your original line of code to 
the line with the underscores you'd have seen this for yourself.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From ysoliman at uncc.edu  Sat Apr 13 22:53:29 2013
From: ysoliman at uncc.edu (Soliman, Yasmin)
Date: Sat, 13 Apr 2013 20:53:29 +0000
Subject: [Tutor] python lists/nested lists
Message-ID: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com>

How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) and then subtract the avg from the original numbers in the list and print? 

Also, if I have a nested list: 
sick_patients=[['Sam', 'M', 65, 'chest pain', 101.6], [['Sarah', 'F', 73, 'dizziness', 98.6], [['Susie', 'F', 34, 'headache', 99.7], [['Scott', 'M', 12, 'stom ache', 102.3]

and I would like to print out all the patients with a temp > 100 how would I do so?

From breamoreboy at yahoo.co.uk  Sat Apr 13 23:16:09 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 13 Apr 2013 22:16:09 +0100
Subject: [Tutor] python lists/nested lists
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <kkchss$do3$1@ger.gmane.org>

On 13/04/2013 21:53, Soliman, Yasmin wrote:
> How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) and then subtract the avg from the original numbers in the list and print?
>

lst = [2,5,8,7,3]
avg = sum(lst) / len(lst)
print(avg)
for n in lst:
     print(n - avg)

> Also, if I have a nested list:
> sick_patients=[['Sam', 'M', 65, 'chest pain', 101.6], [['Sarah', 'F', 73, 'dizziness', 98.6], [['Susie', 'F', 34, 'headache', 99.7], [['Scott', 'M', 12, 'stom ache', 102.3]
>
> and I would like to print out all the patients with a temp > 100 how would I do so?

for patient in sick_patients:
     if patient[-1] > 100:
         print(patient)

The above works if you fix the syntax errors in sick_patients, you do't 
need all the double brackets.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From eryksun at gmail.com  Sat Apr 13 23:29:01 2013
From: eryksun at gmail.com (eryksun)
Date: Sat, 13 Apr 2013 17:29:01 -0400
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <51689E54.1010708@gmail.com>
References: <51689E54.1010708@gmail.com>
Message-ID: <CACL+1athAYBj2=ViKrtBc8QYcsz2xPk3eyvL_eXRKewtFOr7mA@mail.gmail.com>

On Fri, Apr 12, 2013 at 7:52 PM, Saad Bin Javed <sbjaved at gmail.com> wrote:
> Hi, I'm using a script to fetch my calendar events. I split the output at
> newline which produced a list 'lst'. I'm trying to clean it up and create a
> dictionary with date:event key value pairs. However this is throwing up a
> bunch of errors.
>
> lst = ['', 'Thu Apr 04           Weigh In', '', 'Sat Apr 06 Collect NIC', \
> '                     Finish PTI Video', '', 'Wed Apr 10           Serum
> uric acid test', \
> '', 'Sat Apr 13   1:00pm  Get flag from dhariwal', '', 'Sun Apr 14
> Louis CK Oh My God', '', '']

Don't forget to handle entries with times such as "Sat Apr 13   1:00pm".

I think it would be simpler in the long run to use a module that
parses iCalendar files. Your calendar application should support
exporting to iCalendar (.ics, .ical).

http://en.wikipedia.org/wiki/ICalendar

Here's an example sorting the events in the Python event calendar:

    import urllib2
    import datetime

    # https://pypi.python.org/pypi/icalendar
    import icalendar

    pyevent_url = (
      'http://www.google.com/calendar/ical/'
      'j7gov1cmnqr9tvg14k621j7t5c%40'
      'group.calendar.google.com/public/basic.ics')

    pyevent_ics = urllib2.urlopen(pyevent_url).read()
    pyevent_cal = icalendar.Calendar.from_ical(pyevent_ics)

You need a key function to sort the VEVENT entries by DTSTART:

    def dtstart_key(vevent):
        try:
            dt = vevent['dtstart'].dt
        except KeyError:
            dt = datetime.datetime.min
        if isinstance(dt, datetime.date):
            dt = datetime.datetime.combine(dt, datetime.time.min)
        return dt

If dt is a datetime.date, this key function converts it to a
datetime.datetime set to midnight (datetime.time.min). If the DTSTART
field is missing it uses datetime.datetime.min (0001-01-01 00:00).

Use walk('vevent') to show only the VEVENT entries in the calendar
(i.e. filter out VTODO, VJOURNAL, etc):

    events = sorted(pyevent_cal.walk('vevent'), key=dtstart_key)

The last event (index -1) is PyCon DE 2013 on 14 Oct:

    >>> events[-1]['description']
    vText(u'<a href="https://2013.de.pycon.org/">PyCon DE 2013</a>')

    >>> events[-1]['dtstart'].dt
    datetime.date(2013, 10, 14)

From alan.gauld at btinternet.com  Sat Apr 13 23:30:20 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 13 Apr 2013 22:30:20 +0100
Subject: [Tutor] python lists/nested lists
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <kkcip8$lc7$1@ger.gmane.org>

On 13/04/13 21:53, Soliman, Yasmin wrote:
> How can I calculate the average of a list of numbers (eg [2,5,8,7,3] )
 > and then subtract the avg from the original numbers
 > in the list and print?

This sounds like homework which we don;t do for you.

However to calculate the average take the sum and divide by the count.
Do you know how to do those two things?

Once you have the average you need to iterate over your list and 
subtract the average you calculated (and stored) and print the result.

> Also, if I have a nested list:
> sick_patients=[
     ['Sam', 'M', 65, 'chest pain', 101.6],
     [   ['Sarah', 'F', 73, 'dizziness', 98.6],
         [   ['Susie', 'F', 34, 'headache', 99.7],
             [   ['Scott', 'M', 12, 'stom ache', 102.3]

I don't think that's really the structure you intended?
but if it is there is a bunch of missing brackets at the end...

> and I would like to print out all the patients with a temp > 100 how would I do so?

You would iterate over the list testing the temperature element of each 
sublist against 100 and if necessary printing the result.

Now try writing some code and if it doesn't work show us what you've 
done including any error messages(in full) that you get.

PS. As a matter of style your patient records should probably be tuples 
or dictionaries rather than lists. But that's a nicety to keep for 
another time...

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


From zac_vanessa1fan at yahoo.ca  Sun Apr 14 00:33:48 2013
From: zac_vanessa1fan at yahoo.ca (Mariel Jane Sanchez)
Date: Sat, 13 Apr 2013 15:33:48 -0700 (PDT)
Subject: [Tutor] Chapter 3 Projects
In-Reply-To: <1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com>
References: <1364168328.77990.YahooMailNeo@web141005.mail.bf1.yahoo.com>
	<kio66h$cvn$1@ger.gmane.org>
	<1365552412.1498.YahooMailNeo@web141006.mail.bf1.yahoo.com>
	<1365553797.57250.YahooMailNeo@web186001.mail.ir2.yahoo.com>
Message-ID: <1365892428.9389.YahooMailNeo@web141003.mail.bf1.yahoo.com>

Thank you for the help, it was really convenient.?


________________________________
 From: ALAN GAULD <alan.gauld at btinternet.com>
To: Mariel Jane Sanchez <zac_vanessa1fan at yahoo.ca> 
Cc: "tutor at python.org" <tutor at python.org> 
Sent: Tuesday, April 9, 2013 6:29:57 PM
Subject: Re: [Tutor] Chapter 3 Projects
 


Forwarded to group. Please use ReplyAll when responding to tutor posts.


>________________________________
> From: Mariel Jane Sanchez <zac_vanessa1fan at yahoo.ca>
>To: Alan Gauld <alan.gauld at btinternet.com> 
>Sent: Wednesday, 10 April 2013, 1:06
>Subject: Re: [Tutor] Chapter 3 Projects
> 
>
>
>Thank you so much, I finally figured out the 2nd project. I still have problems with 1 and 3 so I'll try to be more clear.?
>
>It would help if you posted your code. It shouldn't be long?and its much easier to see where you are getting confused if we can see the code!
Chapter 3 Booklet PDF is attached
>
>Chapter 3?
>Project 1 on page 90 on the PDF
>"1. Write a program that gets a score from the player and rates it on the following:
>- Given a score between 0-999, the program should display the message, 'Nothing to brag about."
>- Given a score between 1000-9999, the program should display the message, 'Good score.'
>- Given a score over 9999, the program should display the message, 'Very impressive!"
>- If the score is a negative number, the program should display the message, 'That is not a legal score!'"
>
>I'd do it like this

score = raw_input('score? ')
if score < 0: print 'That is not a legal score'
elif score > 9999: print 'Very impressive'
elif 9999 >= score >= 1000: print 'Good score.'
elif  # student to complete...


>
>I tried using range as another tutor suggested which would make sense since it's dealing with ranges but I still get the same result as before. Can you explain how to do this step by step, if you don't mind?
>
>You can use range by substituting the elif lines above with:

elif score in range(1000,10000): print 'Good score.'

Project 3 (Guess My Number code on page 35)
>"Modify the Guess My Number program from the chapter so that the player has only five guesses. If the player runs out of guesses, the program should end the game and display an appropriately chastising message"
>For my case, I somehow, accidentally programmed it to have only 5 tries and also put a message that says " You ran out of tries," which I think is a good progress. However, on the last try; when I put my guess, hit enter and got the guess wrong, the message loops.?
>
>I ?showed you the structure for this last time.
Without seeing your code I have no idea what?you did wrong.


When you first started on Python, how did you do this project so there's no loop at the end?
>
>I did not do those projects because I did not do the course that?you are doing.?
I did not in fact do any courses, I just read the official documents and made?
up my own projects. So I can't tell you how I did it. I can only comment on how I might?
do it now.
?
Alan Gauld
Author of the Learn To Program website

http://www.alan-g.me.uk/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130413/301be57e/attachment-0001.html>

From steve at pearwood.info  Sun Apr 14 03:36:31 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 14 Apr 2013 11:36:31 +1000
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <CAJ5mJ2uf55Xg5VELQDV-M-c8Jq0WyWLRx40EXXp8On_-D7o4ZA@mail.gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2uf55Xg5VELQDV-M-c8Jq0WyWLRx40EXXp8On_-D7o4ZA@mail.gmail.com>
Message-ID: <516A081F.5090407@pearwood.info>

On 14/04/13 03:38, Saad Javed wrote:

> What just happened here? :)
>
> I am trying to learn python so i'm sorry if my mistakes seem trivial.


I have to ask the same question -- what just happened here? Why are you
upset? Mark has given you some good advice, and even added some
light-hearted joviality about somebody fighting an actual python in
real life.

Mark's advice about not "fighting" Python the language is excellent advice,
but of course as a beginner you aren't expected to know what are the most
natural ways to write Python code. If Mark had just stopped there, you
would have reason to be annoyed. But he didn't, he gave you some ideas for
how to re-write the code to be more "Pythonic" (natural for the language).

Mark is correct -- you will very rarely need to use indexing in a for-loop.

# don't do this
for i in range(len(some_list)):
      value = some_list[i]
      process(value)


# instead do this
for value in some_list:
      process(value)


When you need both the value and the index, the most Pythonic way to do so
is to use the built-in function "enumerate":

for index, value in enumerate(some_list):
     some_list[index] = process(value)


Also, beware your email program, whatever it is (Outlook?). It has the
unfortunate habit of adding extra characters into the text. Mark wrote
these six lines:

# there are no asterisks or underscores in the following:
for item in lst:
     if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
         myDict[item] = []
         saveItem = item
     else:
         myDict[saveItem].append(item.strip())


but by the time it came back from you quoted, it contains extra asterisks
added:


# mangled by your email client, three lots of double asterisks added:
for item in lst:
     if item.startswith(('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**:
         myDict[item] = []
         saveItem = item
     else:
         myDict[saveItem].append(item.**strip())


and in a later email from you, somehow those asterisks had turned into
underscores! So beware of email clients that try to be "clever", and
mangle what is written.



-- 
Steven

From steve at pearwood.info  Sun Apr 14 03:50:32 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 14 Apr 2013 11:50:32 +1000
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
Message-ID: <516A0B68.8060602@pearwood.info>

On 14/04/13 04:19, Saad Javed wrote:

> This creates a dictionary whose keys are out of order in terms of dates.


Dictionaries are unordered. That is to say, they have no defined order, when
you print them, or iterate over them, items will appear in whatever order
they happen. If you modify a dict, the order can even change.

This is by design: access to items in the dict is extremely fast, especially
for large dicts, because Python doesn't have to search through the items one
at a time. Dicts are a type of "hash table", which is why dictionary keys must
be hashable.

(If you don't know what a hash table is, please ask.)

So you cannot rely on dicts being in any specific order.

There is an OrderedDict in the collections module which remembers the order
that items are inserted into the OrderedDict. But that's not quite the same
as items being sorted.


> {'Thu Apr 04': ['Weigh In'], 'Sat Apr 06': ['Collect NIC', 'Finish PTI
> Video'], 'Wed Apr 10': ['Serum uric acid test'], 'Sun Apr 14': ['Download
> Louis CK Oh My God', '4:00pm', 'UPS Guy'], 'Sat Apr 13': ['1:00pm', 'Get
> flag from dhariwal']}
>
> Sat Apr 13 is appearing after Sun Apr 14. How do you sort this?


You cannot sort a dictionary directly, but you can sort the keys, then iterate
over them in that order.

keys = sorted(mydict.keys())
for key in keys:
     print mydict[key]




-- 
Steven

From steve at pearwood.info  Sun Apr 14 03:57:21 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 14 Apr 2013 11:57:21 +1000
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <5169B26B.1050707@gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
	<CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
	<kkcacv$a75$1@ger.gmane.org> <5169B26B.1050707@gmail.com>
Message-ID: <516A0D01.6000903@pearwood.info>

On 14/04/13 05:30, Saad Bin Javed wrote:
> This is what I'm using:
>
> for item in lst:
>      if item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
>          dict[item] = []
>          saveItem = item
>      else:
>          dict[saveItem].append(item.____strip())
>
> gives:
>   File "gcalcli_agenda_test.py", line 39
>      if item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
>                                                                        ^
> SyntaxError: invalid syntax


Notice the little caret ^ on the line above "SyntaxError"? It points to where
Python discovers a problem with the syntax of your code.

The underscores do not belong there. They were added by your email program. Why,
I have no idea. Take them out. Likewise with the following underscores.

And with the '____Wed' string. This should be your first hint that something is
wrong. The days of the week start Mon, Tue, Wed, not Mon, Tue, ____Wed.


(I have no idea what your email program will do with these underscores. If in
doubt, your mail client should give you a way to look at the raw, untouched message
source. In Thunderbird, I can go to the View menu and select "Message Source", and
that will show the complete email, including all headers and raw attachments. That
at least ought to show you the text without any mangling. Hopefully.)




-- 
Steven

From steve at pearwood.info  Sun Apr 14 04:08:06 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 14 Apr 2013 12:08:06 +1000
Subject: [Tutor] python lists/nested lists
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A6BF5F62E@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <516A0F86.9080002@pearwood.info>

On 14/04/13 06:53, Soliman, Yasmin wrote:
> How can I calculate the average of a list of numbers (eg [2,5,8,7,3] ) and then subtract the avg from the original numbers in the list and print?


You calculate the average by summing the list, then dividing by the number of items.

To sum a list of numbers, use the sum() function.

total = sum(some_list)


To get the number of items, use the len() function.

num = len(some_list)


To divide, use the / operator. BUT beware, if you are using Python 2, there is a small problem with division: by default, Python will do integer division, which is not what you want. (Python 3 fixes this problem).

For example, if you say 17/3 in Python 2, you will get 5, instead of 5.666666666666667. You can fix that two ways: put this line at the very top of your program, before anything except comments:

from __future__ import division


Or, use floats instead of ints. If you say 17.0/3 you will get 5.666666666666667 as expected.

If you have a variable, you can convert it into a float using the float() function.


Once you have the average, you can print the differences like this:

for value in some_list:
     print value - average



> Also, if I have a nested list:
> sick_patients=[['Sam', 'M', 65, 'chest pain', 101.6], [['Sarah', 'F', 73, 'dizziness', 98.6], [['Susie', 'F', 34, 'headache', 99.7], [['Scott', 'M', 12, 'stom ache', 102.3]
>
> and I would like to print out all the patients with a temp > 100 how would I do so?


for record in sick_patients:
     temp = ... # you have to fill this in, replace the dots with code
     if temp > 100:
         print record


How would you extract the temperature from the internal lists?


(Hint: the patient's name is record[0], their sex is record[1].)



-- 
Steven

From fomcl at yahoo.com  Sun Apr 14 13:06:12 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sun, 14 Apr 2013 04:06:12 -0700 (PDT)
Subject: [Tutor] design question (Django?)
In-Reply-To: <kkbi22$99c$1@ger.gmane.org>
References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkb3a8$b2a$1@ger.gmane.org>
	<1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkbi22$99c$1@ger.gmane.org>
Message-ID: <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com>



?> Subject: Re: [Tutor] design question (Django?)
> 
> On 13/04/13 09:48, Albert-Jan Roskam wrote:
> 
>>  I think I have to make a diagram of this. This stuff is quite hard
> 
> You could use a simple UML class diagram (class -> table). See the OOP topic 
> in my V3 tutorial for simple examples.
> 
> Or you could use a proper entity relationship diagram(ERD) - see wikipedia for 
> details and examples (there are various notational variations)
> 
> They all show the same concepts. UML will be best if you plan
> on using OOP in the python code. ERD is better for vanilla database design.

Hi Alan, I am reading it now. Thanks for the suggestion. I have to read more about Django to decide whether this is the way to do it. First impression: yes. The database abstraction API also implies that I should use OOP. Step #1: defining the model ;-) https://docs.djangoproject.com/en/dev/topics/db/models/
Would it also be a good idea to simultaneously make a paper-and-pencil drawing of the UI? It seems like a good way to figure out what I really want. For me, the hardest part of software construction is the design stage.

Regards,
Albert-Jan

From dfjennings at gmail.com  Sun Apr 14 15:27:26 2013
From: dfjennings at gmail.com (Don Jennings)
Date: Sun, 14 Apr 2013 09:27:26 -0400
Subject: [Tutor] design question (Django?)
In-Reply-To: <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkb3a8$b2a$1@ger.gmane.org>
	<1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkbi22$99c$1@ger.gmane.org>
	<1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <B4EF0C7D-44E9-42C3-8EAC-3256C5F974A3@gmail.com>


On Apr 14, 2013, at 7:06 AM, Albert-Jan Roskam wrote:

> 
> 
>  > Subject: Re: [Tutor] design question (Django?)
>> 
>> On 13/04/13 09:48, Albert-Jan Roskam wrote:
>> 
>>> I think I have to make a diagram of this. This stuff is quite hard
>> 
>> You could use a simple UML class diagram (class -> table). See the OOP topic 
>> in my V3 tutorial for simple examples.
>> 
>> Or you could use a proper entity relationship diagram(ERD) - see wikipedia for 
>> details and examples (there are various notational variations)
>> 
>> They all show the same concepts. UML will be best if you plan
>> on using OOP in the python code. ERD is better for vanilla database design.
> 
> Hi Alan, I am reading it now. Thanks for the suggestion. I have to read more about Django to decide whether this is the way to do it. First impression: yes. The database abstraction API also implies that I should use OOP. Step #1: defining the model ;-) https://docs.djangoproject.com/en/dev/topics/db/models/
> Would it also be a good idea to simultaneously make a paper-and-pencil drawing of the UI?

Absolutely! Test it with three users. See Jakob Nielsen's brief take on the matter:

http://www.nngroup.com/articles/paper-prototyping/

Take care,
Don


From alan.gauld at btinternet.com  Sun Apr 14 16:45:00 2013
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Sun, 14 Apr 2013 15:45:00 +0100 (BST)
Subject: [Tutor] design question (Django?)
In-Reply-To: <1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkb3a8$b2a$1@ger.gmane.org>
	<1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkbi22$99c$1@ger.gmane.org>
	<1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <1365950700.87155.YahooMailNeo@web186005.mail.ir2.yahoo.com>


>Would it also be a good idea to simultaneously make a paper-and-pencil drawing of the UI??Personally I do. At work we call these UI sketches ?"wireframes" and they are used to figure?
out the interaction. The focus is on the relative position of controls and the workflow for?
the user rather than the cosmetics.?There are lots of articles and web sites on the science?
of UI design and usability.
the hardest part of software construction is the design stage.It always is and the bigger the project the more formal the design needs to be.
Most of the projects discussed on the tutor list can be done with little or no design?
(the equivalent of building a dog kennel or garden shed) but as you progress to?
more complex designs (think house extension) you need at least a basic design?
diagram to follow. And as you move into big projects with multiple developers?
or even multiple teams (think skyscraper or?airport terminal) you really need?
clear, formally expressed designs to keep?everything consistent. One of the things?
I like about UML is that it can be used at all levels, just pick the bits that are?
relevant to your project.

HTH,

Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130414/cf0c4c48/attachment.html>

From sbjaved at gmail.com  Sun Apr 14 18:46:35 2013
From: sbjaved at gmail.com (Saad Javed)
Date: Sun, 14 Apr 2013 21:46:35 +0500
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <516A0D01.6000903@pearwood.info>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
	<CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
	<kkcacv$a75$1@ger.gmane.org> <5169B26B.1050707@gmail.com>
	<516A0D01.6000903@pearwood.info>
Message-ID: <CAJ5mJ2u81rNpV7Ayq6+A8NnMUVnQCcHJnpEETdz2kxn_+hVAtQ@mail.gmail.com>

Steven,

You're right about Mark's email. I didn't get the humor and thought the
remark was kinda tough on me. You correctly pointed out his intent. So my
apologies to Mark.

As for the underscores, what happened is that *I didn't voluntarily add the
underscores to begin with. *If you read the emails again, after Mark's
answer about not looping, I asked that the dictionary created as a result
of his code wasn't ordered. In reply, he sent me a portion of his previous
email containing underscores before Wed (__Wed)! I thought it was the
strange but since I'm a beginner, I copied the code and applied it which of
course threw up a syntax error. What I wanted to ask Mark was that *why* had
*he* added underscores because they were throwing up errors for me. He kept
pointing me to his earlier email and asking me compare my line with his
line and I'll find out what the problem is.

In my mind, I thought I was not entering the underscores correctly or at
the right position. As you have explained it turns out it was the email
client which was adding stuff on its own. It added the underscores to
Mark's first response to my dictionary order question and I took it as *Mark's
answer.*

Regards,

Saad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130414/6b36f6f2/attachment-0001.html>

From dkemeza at gmail.com  Tue Apr  9 19:14:07 2013
From: dkemeza at gmail.com (David Kemeza)
Date: Tue, 9 Apr 2013 13:14:07 -0400
Subject: [Tutor] FYI: An Introduction to Interactive Programming in
	Python
In-Reply-To: <CABYizFKANj_ysn4i9ZjezpXHPwbeV5mdd=dyLzv+QsssQ6FthQ@mail.gmail.com>
References: <CABYizF+SAqDW2BD0JP22Tcw0m7rM+DPFd6i-vkxc7MULs3o73g@mail.gmail.com>
	<516359B2.2040300@pearwood.info>
	<CABYizFKANj_ysn4i9ZjezpXHPwbeV5mdd=dyLzv+QsssQ6FthQ@mail.gmail.com>
Message-ID: <CAPzY2QP5MteJ0yJt-Wi9xu4OA4HvWt=XGQuCigjC5+WqkrEVgA@mail.gmail.com>

I'd really be interested in see that code since.  I'm learning python right
now and looking at code helps with my learning process.

Thanx
-dave


On Tue, Apr 9, 2013 at 11:32 AM, brian arb <brianjamesarb at gmail.com> wrote:

> One game  wrote along time ago when I was first learning Python and App
> Engine is http://cdacabeecdebcabab.appspot.com/
> It's kind of a  non-interactive Sudoku puzzle, the only really
> interaction is to click "solve this" or "display next puzzle" then to watch
> the python code written attempt to solve the puzzle you click on the button
> "next iteration" until you reach a solution or the code fails to resolve
> any more of the cells.
>
>
>
>
> On Mon, Apr 8, 2013 at 7:58 PM, Steven D'Aprano <steve at pearwood.info>wrote:
>
>> On 09/04/13 06:38, brian arb wrote:
>>
>>> An Introduction to Interactive Programming in PythonJoe Warren, Scott
>>>
>>> Rixner, Stephen Wong and John Greiner
>>>
>>> This course is designed to be a fun introduction to the basics of
>>> programming in Python. Our main focus will be on building simple
>>> interactive games such as Pong, Blackjack and Asteroids.
>>>
>>> https://www.coursera.org/**course/interactivepython<https://www.coursera.org/course/interactivepython>
>>>
>>
>> Thanks for the link Brian.
>>
>> As an aside, I wonder, apart from Conway's Game of Life, which isn't
>> actually a game at all, what's a non-interactive game?
>>
>>
>>
>> --
>> Steven
>> ______________________________**_________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/5171d494/attachment.html>

From luckytsukune at gmail.com  Wed Apr 10 16:21:54 2013
From: luckytsukune at gmail.com (John Bochicchio)
Date: Wed, 10 Apr 2013 10:21:54 -0400
Subject: [Tutor] Issue With a Python Game
Message-ID: <CAC1EF+Et032xRjzXEeWHxZ0xA0kx+iLv66xN-3F1KiTi9nVzcg@mail.gmail.com>

I have a question about a game I am making. I finished the overall code,
but keep getting errors when I try to play. This is my most common error:
C:\Users\John\Documents\Python Games\Noah>python nickeladventuredemo.py
Traceback (most recent call last):
  File "nickeladventuredemo.py", line 451, in <module>
    main()
  File "nickeladventuredemo.py", line 78, in main
    levels = readLevelsFile('levels.txt')
  File "nickeladventuredemo.py", line 371, in readLevelsFile
    assert startx != None  and starty!= None, 'Level %s (around line %s) in
%s i
s missing a "@" or "+" to mark the start point.' % (levelNum+1, lineNum,
filenam
e)
AssertionError: Level 1 (around line 10) in levels.txt is missing a "@" or
"+" t
o mark the start point.

The error has something to do with the levels. I will attach the code and
levels, as they are fairly long.

-- 
A computer without a Microsoft operating system is like a dog without
bricks tied to its head.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/7f2c7982/attachment-0001.html>
-------------- next part --------------
; Starting demo level:
 ########
##      #
#   .   #
#   $   #
# .$@$. #
####$   #
   #.   #
   #   ##
   #####

; 1

   ###
  ## # ####
 ##  ###  #
## $      #
#   @$ #  #
### $###  #
  #  #..  #
 ## ##.# ##
 #      ##
 #     ##
 #######

; 2

 ## #####
## ## . #
# ## $. #
 ## $   #
## $@ ###
# $  ##
#.. ## ##
#   # ##
##### #

; 3

           #####
          ##   #
          #    #
    ####  # $ ##
    #  ####$ $#
    #     $ $ #
   ## ## $ $ $#
   #  .#  $ $ #
   #  .#      #
##### #########
#.... @  #
#....    #
##  ######
 ####

; 4

  ###########
 ##     #  @#
### $ $$#   #
# ##$    $$ #
#  #  $ #   #
###### ######
#.. ..$ #*##
# ..    ###
#  ..#####
#########

; 5

  ###########
 ##    #    ##
### $ $#$ $ ###
# #$ $ # $ $# #
# $  ..#..  $ #
#  $...#...$  #
# $ .. * .. $ #
###### @ ######
# $ ..   .. $ #
#  $...#...$  #
# $  ..#..  $ #
# #$ $ # $ $# #
### $ $#$ $ ###
 ##    #    ##
  ###########

; 6

  ###########
###.  .$.  .###
 ## $  $  $ ##
  ## ..$.. ##
   ##$#$#$##
    #.$ $.#
    #  @  #
    ### ###
   ## $ $ ##
   #.  $  .#
   ### . ###
     #####

; 7

           ######
    ####  ##    #
  ###  #  #  ## ###
###    #### #   $ #
#  $ @ ...*..  $  #
# $ $  ## ###   ###
### ###   # #####
 #      ###
 #   ####
 #####

; 8

    #######
    #     ##
##### ###  ##
#       #  ##
#@$***. ##$ #
#  #    ## .#
##  ##  # $ #
 ##  ####.$.#
  ##        #
   ######  ##
        ####

; 9

#########
#. .    #
#.$. .  #
## ###@ #
 #  $  ##
 # $$ ##
 #  $ #
 #  ###
 ####

; 10

      ######
      #    #
      # @  ###
####  #      #
#  ####..#.#$#####
# $ $ ##...      #
#     .....#$$   #
###### ##$## #####
     #  $    #
     #### ####
       #  #
       #  #####
     ### $    #
     #  $ $   #
     # #$# ####
     #     #
     #######

; 11

  ####
###  ####
#   @   ##
# #. .#.###
# $$$ $$$ #
###.#.#.# #
 ##       #
  ####  ###
     ####

; 12

              #####
              #   #
    #####     #   #######
    #   ##### #   ..... #
##### # ##  # #     # # #
# $ $ $ $ $ # ##   ## $ #
# # ##......#### ### $$ ###
#      ## * #    # #  $$  #
##########+$$   ## #      #
         #.$ $# #  ########
         #.##   #
         ########

; 13

   #######
 ###     ##
 #   ###  #
 #      # #
###$#@  # #
#   ##### #
#   #  *. #
##$$#  *.##
 #     *..#
 #### #...##
    # #$$$ #
    #   $  #
    #####  #
        ####

; 14

 #######
##     # #
#  *.$.#
#  *.#.###
# #$@$$  #
#   ## # #
######   #
     #####

; 15

   ####
   #@ #
  ##  #
  # .$#
  #$. #
###..$###
#  ..$  #
# $ $ # #
##### # #
    #   #
    #####

; 16

  ######
 ## #  ###
## #   # ##
# #   $.# #
##  $ $.# #
# #####. ##
#     $. @#
#     $. ####
### # #*# # ###
  #### .$     #
    #  .$     #
    ## .##### #
    # #.$ $  ##
    # #.$   # #
    ## #   # ##
     ###  # ##
       ######

; 17

    ###########
   ## . . . . ###
   #  $$ $ $ $  #
   #   ######## # #####
 #### ##  $     # #   #
 #    #  $ $ #  ### # #
##  # #   ####     $  #
#...  ##### $  #### ###
#... @     $     #    #
#...############ $  $ #
#####          #####  #
                   ####

; 18

    ####
#####  #
#      #
#$ $ $ #
#.*.*.*#
#*.*.*.#
# $ $ $#
#......#
#.*.*.*#
#$ $ $ #
# $ $ $#
#$ $ $ #
#      #
#@ #####
####

; 19

#####
#   #######
#  $      ##
## ######  ##
 # #    # # ########
 # # ##    $       ##
 # #.   #@###### $  ##
 # #.#  ###    ## $  ##
 # #.    #      ## $  ##
 # #.#   #  ##   ## $  ##
## #.#  ##  ###   ## $  #
#  #.#   #  #*##   ##   #
#   .# # #  ##*##   #####
######   #  ######
     #####

; 20

     ####
     #  #
######$.#
#   $ $.#
# $@$...#
# $$$..##
#  $ ..#
########

; 21

##### ########
#   ### . $  #
#   $ *.. #$ ##
## $# ..* $  @#
 #  $ . ###   #
 ######## #####

; 22

   ##### ####
   #@ .###  ###
####  $$ $    #
#   # . . ##  #
#  $ # . . ## #
## .  $ $$  # #
 # #  ###.  # #
 # #### ##### #
 #       #    #
 ####### # ####
       # .$ #
     ####   #
     ## #####
      ###

; 23

     #######
######     ######
#  . ..$#$.. .  #
#  $ $  .  $ $  #
###$####@####$###
#  $ $  .  $ $  #
#  . ..$#$.. .  #
######     ######
     #######

; 24

        ######
        #   ##
  ####### $  #
  # $ $ $ #$ #
  #   #. $   #
 ####.#.# $###
 #   ..... #
 #  $ ..##$#
### ## ..  #
#  $.#$ # $#
#   $   #  #
##@  #  ####
 ##  ####
  ####

; 25

         #####
     #####  #####
     #  .#$   $ #
     # #. $$$ @ ##
     #  .#$   $  #
     ###.#  $ $  #
       #.  ##$ ###
 #######*###.$ #
 # $    ....####
## #$#$$....#
#  $ $   #..#
#     $  #..#
#  ##########
#####

; 26

           ####
 ###########  #
 #  $ $ $ $   ##
 #  # # # # #$##
 ##. . . . . .#
  #$# # # # #$####
###. . . . . .   #
###$# # # # # @  #
  #   $ $ $ $  ###
  #  ###########
  ####

; 27

      ########
 ######      ##########
## $     ###          ##
# $ $ ## #  #########  #
#  $  #              # #
# $ $ # #  ######### # #
#  $  #  # #. . . .  # #
# $ $ # #    . . . .## #
#  $  # # # . . . . #  #
##$ $## #  #### # #   ##
 #   #@ #       #  ####
 ######  #####  #  #
      ##     #  #  #
       #####  ##  ##
           ##    ##
            ######

; 28

       ######
       #    ###
   ##### $ $  #
####   #.#    ##
#  $ #$#.##$#####
# $$. .#.$      ##
#  $.#.#.#####  ####
##  ....... @#     #
 ####$ #.### #$###$##
  ## $  .  #  $ $ $ #
   # $ ###          #
   #   # ############
   #####

; 29

####
#  #              ####
#  ######## #######  #
#         ###  ##  $ #
##.###### ...     #. #
 #.#      # .#   # $ #
 #$$$$#$$$ #.#   ##. #
 #.# $   $ #..      ##
 #.#  $  $   # #   ##
 #  #   $$ #   #####
 #.  ##$  ######
 #.   #  $.  #
##. @ ###.#$ #
#     # #    #
#    ## ######
######

; 30

     #####
     #   #
     #   #        ######
   ###  ## #####  #    ###
   #    #        ## #$$  #
  ##$   ########## $  $  #
###  ## ..........$  #$$@#
#    # $$# ####### $     #
#   $  #...#     ###  ####
#   #   $ ### ##   ####
########    #
       #    #
       #    #
       ######

; 31

       #########
       ###    ##  ####
#####  #    * ##  #  #
#   #### ****  ####$.##
# .$      *@*      $. #
##.$####  **** ####   #
 #  #  ## *    #  #####
 ####  ##    ###
       #########

; 32

                   #####
                   #   #
           ######### $ #
    ###### #   #   #   #
    #    # # $     $ #@#
  ### ## #### ### ## ###
  #   $  $     #   #   #
  #  $  $ # #$ # $$ $$ #
 ######  $  #  #   #   #
##    ## ###############
#  .#   $ #    #
#..    #  ######
#...####  #
#....# ####
#....#
######

; 33

   #######
  ##     ##
  #  ###  #
  # ## $  ####
  # # .#   $.####
  # # * *###.$  #
  # # *#   ### #####
  # # @ * *  # #   #
  # #  ### #*#  *  #
  # ## #  * *.# # #######
  # #  #     ....$  $   #
  # # ## $# $####$      #
###*   *     #    #######
#   ########## ####
#              #
##  ############
 ####

; 34

            #####
            # ..########
            # ......#  #
            #.. ##$$  $#
         #####.##   $  #
         #  ....# $  $$#
##### ## #  .. .#$  $  #
#   #    # ##.###  $$ $###
#   ###  # ## #  $  #    #
# @   #### #  # # ###$ # #
#             #  $    $  #
#   ####      ### ####$$##
#  ##  ####     #       #
#  #      ##    ######  #
####       ##     # # $ #
            ##    # #   #
             ###### #####

; 35

 #####
 #   #
## # #####
#    ##  #######
# #     $      ####
#   #### $  $$ #  #
#####  # $$$ $ #$ #
       # $  $ $ $ ######
     ###$   #$ $  $    #
     # $ $$      ### @ ##
     #  $ $$$$####...   #
     #  $     $ #. .#...#
     ### $$$$   ......  #
       #      ##..#.....#
       ###### ##.....####
            #   .....#   #
            ##########

; 36

               #####
   ####        #   ######
   #  #        # $    $ #
   #  ####     #  $##$  ###
   #     #########  # $ $ #
   #      ..........#   $ #
 ###### ##....@###  # $$  #
 #    # #####.## # ##   $ #
 #            #  #$  $$ $ #
#### #  ##### #  #  $  #  #
#    # #      #  ###   ####
#      #  #   #    #####
#   #     #####
#####     #
    #######

; 37

  #####       #########
  #   #       #       #
### #$### ##### # # # #####
# $. .  # #    . . . .    #
# # # #$### # # # # # # #$#
#  . . . .  $ $ $ $  . .  #
###$# # #$###########$# #$#
  #  . .  ##        #  .  #
  ###$# #$####### # #$# #$###
    #  . .$ $ $ #   #  . .  #
    #$# # # # # #####$# # # #
    #  . . . . .  $  . . .  #
    ### # # # # # # # # # # #
      # $ $. . .$ $ $ $ $ $ #
      ##### # # #############
          #  @  #
          #######

; 38

                      ####
  ####         ########  #
###@ ##        #      #  #
#     #        # ### $ $ #
# ....##########   #  #..#
# . #  ## $   $ $# #  #..#
### #     $  $$$ # # $ $ #
  # ...# $  $$   # #  #  #
  #  ..# $   $ $ # # ##  #
  ##...#  $ $$ $ #$# #####
   #   ## $  $ $   # #
   ### ######  ### # ###
   # .   ## #### .   . #
  ##   . #     # #.#.# #
  #  .   # # # #   #   #
  # . ####     #########
  #  ##
  ####

; 39

   ####           #####
   #  #######  ####   #
   # @  $   ####   $  #
   #  ###.#    #  $$  #
 ###.## $ #$ #    #  ##
 #  ..# $ ...# ###  ##
 # $ ...$##.##     ##
 ##.###$ $..   $$ ##
  #.  #. .### $ $ #
  #  $...## ## #  #
 ## ######   #   ##
##   ##      #####
# $$  #
#   $ #
### $ #
  #  ##
  ####

; 40

     #######
#### #     #
#  ### $$$ #
#  ....$  #####
#  ..# $  #  @#
###$##$#### # ######
 #.*....$  $  ###  #####
 # ..#####  ##   $ $   #
 #....*.... #  $$  # $ #
 ########## #$$ ## #   #
    # $.###        $  ##
    #       $###$# #  #
    #####   $    $ ####
        ####    ####
           ######

; 41

   #####
   #   #
 ###   ########
##  ***    # # #
 #  * *    ## # #####
##  ***   ## # ##   ##
 ###   #### # # #   #
   #   # # # ####$ $###
  ##   ## # ##  $...$ ##
   ##### # ##    . at .  #
        # # #   $...$ ##
         ########$ $###
                #   #
                #####

; 42

####
#  ######
#       ####
# $ $   #  #####
##### ###    $ #
 #  #   $  #   #
 #      ##$######
 # $###  # ...# #
 ## #@#$ ##.#.# #
 #    #   #...# #
 # $ ##$ $#...#####
 ### ##   #...    #
  #  #  $ $ $ # # #
  # $### ###### # #
  #             # #
  #############   #
              #####

; 43

   ####
  ##  #############
 ##    .......... #
##    #  ####$### ##
#      # #      #  ##
#     #  # $$$  # # #####
#####  # . .# ### . . . ##
    #   $. .#  # $$ $ $ @#
   ####### ### #   #######
   # $   $   # ## ###
   #    $  $ #  # ## # ####
   # $### ####  # # # ##  ####
   #  $ $$$  # ## #  ##      #
   ##        # ## #### $$$   #
    ## ####### .....     #####
    #  $         ######  #
    #   ######  ##    ####
    #####    ####

; 44

 #############
##       #   ###
#  $ $$$$$     #
### $   $  ### #
  # $ $ $### # #
  ##   $ ##  # ###
   ####   ####   #
     ###       # ###
   ####   ####     #
   #@ $   ###  #.# #####
   # $ $ ## #  ....    #
   # $$ ##  ####.....  #
  ## $  #     #..#.##  #
  # $ $ ##    #......  #
  #  $ $ #    # . ..# ##
  ##  $  #    ## ##.# #
   #    ##     #      #
   ######      ########

; 45

  ####      ########
  #  ##### ##   #  #
  #    $ ### $  $  #
  #  $ # ##    $   ####
  ###  #    # ###$##  #
#####  ###  ####   $  #
#   # $  $$## .. ##$  #
#  $$   # $          ##
##  # $##  #### # ####
### #  ##$ ###..#..#
#   ###..  #  .....###
#   #  *.### #  #..  #
##$$#  *.##@ #  #    #
 #     *. ####  ###  #
 ######   #  #       #
      #####  ##    ###
              #  ###
              ####

; 46

      #### ###################
  #####  ###            .$   #
###  $.       #####$####   # #
#    $.  #### #     .   ### .#
#  $ $.### ## # #### #  $.# $#
###  $.## # # # #  #  # $ #  #
  ###### # ## #$ $ ##   #. # #
        ##### #.#.  #  ### # #
 #####  #   # ### ###   #    #
 ##*##  #     .#  #   #$$*  ##
 #*### ### ## ## ## #  .#. ##
 ###*# #  .$ .# $.$.## ### #
 ##*## # #.####     # $.   ##
 #*### # $$   ### ###   ##  ##
 ###*# # #   . $@$  #######. #
 ##### # ### ####.#        $ #
       #     #  ###########  #
       #######            ####

; 47

#########
#       #    ######
#   $   ######    ###
# #$#$ $ $  # $     #
# $   $@$  $ $ $ $$ #
# $ $# $ #     $$$  #
#  $ $ #######   #####
##    ###....##### ..#
 ###$$# $$$$ #...* ..#
  #         ##   #.. #
  #  #  #$###....##*##
  #   ##..$. ....    #
  ### .*   .#....#   #
    ##################

; 48

   #### ####
  ##  # #  #  #######
###   ###$ ## #     ###
#  $      $ ###       #
# $ $ ###$   #  #     #
### ### #    #   #    #
#  $ #  ## ###    # ###
#    $   # #@        ##
# $# # ### ###   #   #
#  $ # # $ $ #  #  # #
##   #    $  # #.    #
 ##  # #   ## #..  ###
  ## # #  ## #... ##
 ### # #### #....##
 #          $.*.##
 ############..##
            ####

; 49 'Parallel Logic'

#########################
#  #  #  #  #  #  #  #  #
# $#$ # $#$ # $#$ # $#$ #
#  #  #  #  #  #  #  #  #
## # ### # ### # ### # ##
#  #  #  #  #  #  #  #  #
#     #     #     #     #
# ### # ### # ### # ### #
#  #  #  #  #  #  #  #  #
#  #     #  $  #     #  #
#  # ### # ### # ### #  #
#  . . .  . + .  . . .  #
#########################

; 50 'Particle Theory'

  # # # # # # # # # # # #
 # # # # # # # # # # # # #
#   .$    . $.  . $   .$  #
 # $# #$# # # #$# # # #  #
#  .  .    $.  .  .$ .  . #
 # #$# # # # #$#$ $# #$# #
# .     .$ .$    . $.  .  #
 # $# # # # #@# # # # #$ #
#  .  .$ .    $. $.     . #
 # #$# #$ $#$# # # # #$# #
# .  . $.  .  .$    .  .  #
 #  # # # #$# # # #$# #$ #
#  $.   $ .  .$ .    $.   #
 # # # # # # # # # # # # #
  # # # # # # # # # # # #
-------------- next part --------------
A non-text attachment was scrubbed...
Name: nickeladventuredemo.py
Type: application/octet-stream
Size: 16531 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20130410/7f2c7982/attachment-0001.obj>

From luckytsukune at gmail.com  Sat Apr 13 15:13:07 2013
From: luckytsukune at gmail.com (John Bochicchio)
Date: Sat, 13 Apr 2013 09:13:07 -0400
Subject: [Tutor] Issue With a Python Game
Message-ID: <CAC1EF+HYS9evt61WyP1+-9cxHz_u2zgS0Nhv3qZvpNGNg_885Q@mail.gmail.com>

I have a question about a game I am making. I finished the overall code,
but keep getting errors when I try to play. This is my most common error:
C:\Users\John\Documents\Python Games\Noah>python nickeladventuredemo.py
Traceback (most recent call last):
  File "nickeladventuredemo.py", line 451, in <module>
    main()
  File "nickeladventuredemo.py", line 78, in main
    levels = readLevelsFile('levels.txt')
  File "nickeladventuredemo.py", line 371, in readLevelsFile
    assert startx != None  and starty!= None, 'Level %s (around line %s) in
%s i
s missing a "@" or "+" to mark the start point.' % (levelNum+1, lineNum,
filenam
e)
AssertionError: Level 1 (around line 10) in levels.txt is missing a "@" or
"+" t
o mark the start point.

The Code:

import random, sys, copy, os, pygame

from pygame.locals import *



FPS = 30

WINWIDTH = 800

WINHEIGHT = 600

HALF_WINWIDTH = int(WINWIDTH / 2)

HALF_WINHEIGHT = int(WINHEIGHT / 2)



TILEWIDTH = 50

TILEHEIGHT = 85

TILEFLOORHEIGHT = 45



CAM_MOVE_SPEED = 5



OUTSIDE_DECORATION_PCT = 20



BRIGHTBLUE = ( 0, 170, 255)

WHITE      = (255, 255, 255)

BGCOLOR = BRIGHTBLUE

TEXTCOLOR = WHITE



UP = 'up'

DOWN = 'down'

LEFT = 'left'

RIGHT = 'right'





def main():

    global FPSCLOCK, DISPLAYSURF, IMAGESDICT, TILEMAPPING,
OUTSIDECOMAPPING, BASICFONT, PLAYERIMAGES, currentImage



    pygame.init()

    FPSCLOCK = pygame.time.Clock()



    DISPLAYSURF = pygame.display.set_mode((WINWIDTH, WINHEIGHT))



    pygame.display.set_caption('Noah Nickel Adventure!')

    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)



    IMAGESDICT = {'uncovered goal': pygame.image.load('RedSelector.png'),

                  'covered goal': pygame.image.load('Selector.png'),

                  'star': pygame.image.load('Star.png'),

                  'corner': pygame.image.load('Wall Block Tall.png'),

                  'wall': pygame.image.load('Wood Block Tall.png'),

                  'inside floor': pygame.image.load('Plain Block.png'),

                  'outside floor': pygame.image.load('Grass Block.png'),

                  'title': pygame.image.load('star_title.png'),

                  'solved': pygame.image.load('star_solved.png'),

                  'princess': pygame.image.load('princess.png'),

                  'boy': pygame.image.load('boy.png'),

                  'catgirl': pygame.image.load('catgirl.png'),

                  'horngirl': pygame.image.load('horngirl.png'),

                  'pinkgirl': pygame.image.load('pinkgirl.png'),

                  'rock': pygame.image.load('Rock.png'),

                  'short tree': pygame.image.load('Tree_Short.png'),

                  'tall tree': pygame.image.load('Tree_Tall.png'),

                  'ugly tree': pygame.image.load('Tree_Ugly.png')}



    TILEMAPPING = {'X': IMAGESDICT['corner'],

                   '#': IMAGESDICT['wall'],

                   'o': IMAGESDICT['inside floor'],

                   ' ': IMAGESDICT['outside floor']}



    OUTSIDECOMAPPING = {'1': IMAGESDICT['rock'],

                        '2': IMAGESDICT['short tree'],

                        '3': IMAGESDICT['tall tree'],

                        '4': IMAGESDICT['ugly tree']}

    #Super important to remember:

    #DEAR GOD REMEMBER THIS IS AN INDEX OF PLAYER IMAGES.

    currentImage = 0

    PLAYERIMAGES = [IMAGESDICT['princess'],

                    IMAGESDICT['boy'],

                    IMAGESDICT['catgirl'],

                    IMAGESDICT['horngirl'],

                    IMAGESDICT['pinkgirl']]

    startScreen()



    levels = readLevelsFile('levels.txt')

    currentLevelIndex = 0



    while True:

        result = runLevel(levels, currentLevelIndex)



        if result in ('solved', 'next'):

            currentLevelIndex += 1

            if currentLevelIndex >= len(levels):

                currentLevelIndex = 0



        elif result == 'back':

            currentLevelIndex -= 1

            if currentLevelIndex <0:

                currentLevelIndex = len(levels)-1



        elif result == 'reset':

            pass





def runLevel(levels, levelNum):

    global currentImage

    level0bj = levels[levelnum]

    map0bj = decorateMap(level0bj['map0bj'],
level0bj['startState']['player'])

    gameState0bj = copy.deepcopy(level0bj['startState'])

    mapNeedsRedraw = True

    levelSurf = BASICFONT.render('Level %s of %s' % (level0bj['levelNum']
+1, totalNumOfLevels), 1, TEXTCOLOR)

    levelRect = levelSurf.get_rect()

    levelRect.bottomleft = (20, WINHEIGHT - 35)

    mapWidth = len(map0bj) * TITLEWIDTH

    mapHeight = (len(map0bj[0]) - 1) * (TITLEHEIGHT - TILEFLOORHEIGHT) +
TILEHEIGHT

    MAX_CAM_X_PAN = abs(HALF_WINHEIGHT - int(mapHeight / 2)) + TILEWIDTH

    MAX_CAM_Y_PAN = abs(HALF_WINWIDTH - int(mapWidth / 2)) + TILEHEIGHT



    levelIsComplete = False

    camera0ffsetX = 0

    camera0ffsety = 0

    cameraUp = False

    cameraDown = False

    cameraLeft = False

    cameraRight = False



    while True:

        playerMoveTo = None

        kepPressed = False



        for event in pygame.event.get():

            if event.type == QUIT:

                terminate()



            elif event.type == KEYDOWN:

                keyPressed == True

                if event.key == K_LEFT:

                    playerMoveTo = LEFT

                elif event.key == K_RIGHT:

                    playerMoveTo = RIGHT

                elif event.key == K_UP:

                    playerMoveTo = UP

                elif event.key == K_DOWN:

                    playerMoveTo = DOWN

                elif event.key == K_a:

                    cameraLeft = True

                elif event.key == K_d:

                    cameraRight = True

                elif event.key == K_w:

                    cameraUp = True

                elif event.key == K_s:

                    cameraDown = True



                elif event.key == K_n:

                    return 'next'

                elif event.key == K_b:

                    return 'back'



                elif event.key == K_ESCAPE:

                    terminate() #Perhaps add a print box confirmation?

                elif event.key == K_BACKSPACE:

                    return 'reset' #Same confirmation for level reset.

                elif event.key == K_p:

                    currentImage += 1

                    if currentImage >= len(PLAYERIMAGES):

                        currentImage = 0

                        mapNeedsRedraw = True

                elif event.type == KEYUP:

                    if event.key == K_a:

                        cameraLeft = False

                    elif event.key == K_d:

                        cameraRight = False

                    elif event.key == K_w:

                        cameraUp = False

                    elif event.key == K_s:

                        cameraDown = False



                if playerMoveTo != None and not levelIsComplete:

                    moved = makeMove(map0bj, gameState0bj, playerMoveTo)



                    if moved:

                        gameState0bj['stepCounter'] += 1

                        mapNeedsRedraw = True



                    if isLevelFinished(level0bj, gameState0bj):

                        levelIsComplete = True

                        keyPressed = False



                DISPLAYSURF.fill(BGCOLOR)



                if mapNeedsRedraw:

                    mapSurf = drawMap(map0bj, gameState0bj,
level0bj['goals'])

                    mapNeedsRedraw = False



                if cameraUp and camera0ffsetY < MAX_CAM_X_PAN:

                    camera0ffsetY += CAM_MOVE_SPEED

                elif cameraDown and camera0ffsetY > -MAX_CAM_X_PAN:

                    camera0ffsetY -= CAM_MOVE_SPEED

                if cameraLeft and camera0ffsetX < MAX_CAM_Y_PAN:

                    camera0ffsetX += CAM_MOVE_SPEED

                elif cameraRight and camera0ffsetX > -MAX_CAM_Y_PAN:

                    camera0ffsetX -= CAM_MOVE_SPEED



                mapSurfRect = mapSurf.get_rect()

                mapSurfRect.center = (HALF_WINWIDTH + camera0ffsetX,
HALF_WINHEIGHT + camera0ffsetY)



                DISPLAYSURF.blit(mapSurf, levelRect)

                stepSurf = BASICFONT.render('Steps: %s'
%(gameState0bj['stepCounter']), 1, TEXTCOLOR)

                stepRect = stepSurf.get_rect()

                stepRect.bottomleft = (20, WINHEIGHT -10)

                DISPLAYSURF.blit(stepSurf, stepRect)



                if levelIsComplete:

                    solvedRect = IMAGESDICT['solved'].get_rect()

                    dolvedRect.center = (HALF_WINWIDTH, HALF_WINHEIGHT)

                    DISPLAYSURF.blit(IMAGESDICT['solved'], solvedRect)



                if keyPressed:

                    return 'solved'



                pygame.display.update()

                FPSCLOCK.tick()





def decorateMap(map0bj, startxy):



    startx, starty = startxy



    map0bjCopy = copy.deepcopy(map0bj)



    for x in range(len(map0bjCopy)):

        for y in range(len(map0bjCopy[0])):

            if map0bjCopy[x][y] in ('$', '.', '@', '+', '*'):

                map0bjCopy[x][y] = ' '



    floodFill(map0bjCopy, startx, starty, ' ', 'o')



    for x in range(len(map0bjCopy)):

        for y in range(len(map0bjCopy[0])):



            if (isWall(mapObjCopy, x, y-1) and isWall(mapObjCopy, x+1, y))
or \

               (isWall(mapObjCopy, x+1, y) and isWall(mapObjCopy, x, y+1))
or \

               (isWall(mapObjCopy, x, y+1) and isWall(mapObjCopy, x-1, y))
or \

               (isWall(mapObjCopy, x-1, y) and isWall(mapObjCopy, x, y-1)):

                map0bjCopy[x][y] = 'x'



            elif map0bjCopy[x][y] == ' ' and random.randint(0, 99) <
OUTSIDE_DECORATION_PCT:

                 map0bjCopy[x][y] =
random.choice(list(OUTSIDECOMAPPING.keys()))



    return map0bjCopy





def isBlocked(map0bj, gameState0bj, x, y):



    if isWall(map0bj, x, y):

        return True



    elif x < 0 or x >= len(map0bj) or y < 0 or y >= len(map0bj[x]):

        return True



    return False



def makeMove(map0bj, gameState0bj, playerMoveTo):

    playerx, playery = gameState0bj['player']



    stars = gameState0bj['stars']



    if playerMoveTo == UP:

        x0ffset = 0

        y0ffset = -1

    elif playerMoveTo == RIGHT:

        x0ffset = 1

        y0ffset = 0

    elif playerMoveTo == DOWN:

        x0ffset = 0

        y0ffset = 1

    elif playerMoveTo == LEFT:

        x0ffset = -1

        y0ffset = 0



    if isWall(map0bj, playerx, x0ffset, playery + y0ffset):

        return False

    else:

        if (playerx + x0ffset, playery + y0ffset) in stars:

            if not isBlocked(map0bj, gameState0bj, playerx + (x0ffset*2),
playery + (y0ffset*2)):

                ind = stars.index((playerx + x0ffset, playery + y0ffset))

                stars[ind] = (stars[ind][0] + x0ffset, stars[ind][1] +
y0ffset)

            else:

                return False



        gameState0bj['player'] = (playerx + x0ffset, playery + y0ffset)

        return True





def startScreen():



    titleRect = IMAGESDICT['title'].get_rect()

    topCoord = 50

    titleRect.top = topCoord

    titleRect.centerx = HALF_WINWIDTH

    topCoord += titleRect.height



    instructionText = ['Push the stars over the marks.',

                       'Arrow keys move the player, WASD controls the
camera, and P changes the characer.',

                       'Backspaced resets the level, Escape quits the
game.',

                       'N for next level, B to go back a level.']



    DISPLAYSURF.fill(BGCOLOR)



    DISPLAYSURF.blit(IMAGESDICT['title'], titleRect)



    for i in range(len(instructionText)):

        instSurf = BASICFONT.render(instructionText[i], 1, TEXTCOLOR)

        instRect = instSurf.get_rect()

        topCoord += 10

        instRect.top = topCoord

        instRect.centerx = HALF_WINWIDTH

        topCoord += instRect.height

        DISPLAYSURF.blit(instSurf, instRect)



    while True:

        for event in pygame.event.get():

            if event.type == QUIT:

                terminate()

            elif event.type == KEYDOWN:

                if event.key ==K_ESCAPE:

                    terminate()

                return



        pygame.display.update()

        FPSCLOCK.tick()





def readLevelsFile(filename):

    assert os.path.exists(filename), 'Cannot find the level file: %s' %
(filename)

    mapFile = open(filename, 'r')

    content = mapFile.readlines() + ['\r\n']

    mapFile.close()



    levels = []

    levelNum = 0

    mapTextLines = []

    map0bj = []

    for lineNum in range (len(content)):

        line = content[lineNum].rstrip('\r\n')



        if ';' in line:

            line = line[:line.find(';')]

        if line != '':

            mapTextLines.append(line)

        elif line == '' and len(mapTextLines) > 0:



            maxWidth = -1

            for i in range(len(mapTextLines)):

                if len(mapTextLines[i]) > maxWidth:

                    maxWidth = len(mapTextLines[i])



            for i in range(len(mapTextLines)):

                mapTextLines[i] += ' ' * (maxWidth - len(mapTextLines[i]))



            for x in range(len(mapTextLines[0])):

                map0bj.append([])

            for y in range(len(mapTextLines)):

                for x in range(maxWidth):

                    map0bj[x].append(mapTextLines[y][x])



            startx = None

            starty = None

            goals = []

            stars = []

            for x in range(maxWidth):

                for y in range (len(map0bj[x])):

                    if map0bj[x][y] in ('@', '+'):

                        startx = x

                        starty = y

                    if map0bj [x][y] in ('.', '+', '*'):

                        goals.append((x, y))

                assert startx != None  and starty!= None, 'Level %s (around
line %s) in %s is missing a "@" or "+" to mark the start point.' %
(levelNum+1, lineNum, filename)

                assert len(goals) > 0, 'Level %s (around line %s) in %s
must have at least one goal.' % (levelNum+1, lineNum, filename)

                assert len(stars) >= len(goals), 'Level %s (around line %s)
in %s is impossible to solve. It has %s goals but only %s stars.' %
(levelNum+1, lineNum, filename, len(goals), len(stars))



                gameState0bj = {'player': (startx, starty),

                                'stepCounter': 0,

                                'stars': stars}

                level0bj = {'width': maxWidth,

                            'height': len(map0bj),

                            'map0bj': map0bj,

                            'goals': goals,

                            'startState': gameState0bj}



                levels.append(level0bj)



                mapTextLines = []

                map0bj = []

                gameState0bj = {}

                levelNum += 1

    return levels





def floodFill(map0bj, x, y, oldCharacter, newCharacter):

    if map0bj[x][y] == oldCharacter:

        map0bj[x][y] = newCharacter



    if x < len(map0bj) - 1 and map0bj[x+1][y] == oldCharacter:

        floodFill(map0bj, x+1, y, oldCharacter, newCharacter)

    if x > 0 and map0bj[x-1][y] == oldCharacter:

        floodFill(mapObj, x-1, y, oldCharacter, newCharacter)

    if y < len(mapObj[x]) - 1 and mapObj[x][y+1] == oldCharacter:

        floodFill(mapObj, x, y+1, oldCharacter, newCharacter)

    if y > 0 and mapObj[x][y-1] == oldCharacter:

        floodFill(mapObj, x, y-1, oldCharacter, newCharacter)





def drawMap(map0bj, gamestate0bj, goals):

    mapSurfWidth = len(map0bj) * TILEWIDTH

    mapSurfHeight = len(len(map0bj[0]) - 1) * (TILEHEIGHT -
TILEFLOORHEIGHT) + TILEHEIGHT

    mapSurf = pygame.Surface((mapSurfWidth, mapSurfHeight))

    mapSurf.fill(BGCOLOR)



    for x in range(len(map0bj)):

        for y in range(len(map0bj)):

            spaceRect = pygame.Rect((x * TILEWIDTH, y * (TILEHEIGHT -
TILEFLOORHEIGHT), TILEWIDTH, TILEHEIGHT))

            if map0bj[x][y] in TILEMAPPING:

                baseTile = TILEMAPPING[map0bj[x][y]]

            elif map0bj[x][y] in OUTSIDECOMAPPING:

                baseTile = TILEMAPPING[' ']



            mapSurf.blit(baseTile, spaceRect)



            if map0bj[x][y] in OUTSIDECOMAPPING:

                mapSurf.blit(OUTSIDEDECOMAPPING[map0bj[x][y]], spaceRect)

            elif (x, y) in gameState0bj['stars']:

                if (x, y) in goals:

                    mapSurf.blit(IMAGESDICT['covered goal'], spaceRect)

                mapSurf.blit(IMAGESDICT['star'], spaceRect)

            elif (x, y) in goals:

                mapSurf.blit(IMAGESDICT['uncovered goal'], spaceRect)



            if (x, y) == gameState0bj['player']:

                mapSurf.blit(PLAYERIMAGES[currentImage], spaceRect)



    return mapSurf





def isLevelFinished(level0bj, gameState0bj):

    for goal in level0bj['goals']:

        if goal not in gameState0bj['stars']:

            return False

    return True





def terminate():

    pygame.quit()

    sys.exit()





if __name__ == '__main__':

    main()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130413/e8c4b2be/attachment-0001.html>

From n.nayeri at hotmail.com  Tue Apr  9 03:31:43 2013
From: n.nayeri at hotmail.com (Negin Nayeri)
Date: Tue, 9 Apr 2013 03:31:43 +0200
Subject: [Tutor] Create Library
Message-ID: <DUB121-W66BBA0260D75479254B0587C60@phx.gbl>

Hi!Im supposed to do a Library in Python and I don't even know how to begin! Please just help me. Like what kind of attributes do you think I should have, how do I store information? The file with the books and authors I must fix, do think I should write in txt format or like in Excel. Please help me.


Write a program used to handling simpler library routines. The program should be able to search for books in terms of both author and title. You should also be able to borrow and return books, put new books in the registry and remove the old books, and print a list on the screen of all books. The books will be sorted with respect to the author.The books are stored in a text file that you can write yourself. Your file does not contain more than ten books, but your program should be valid also for a large number of books.The program will remember which books are utl?nade?ven if the user turns off and restarts the application.It can look some thing like this:Welcome to Adriana's Library:T search for titelF search by authorL Borrow BookR Return BookN Register new bookB remove book from registerA see a list of all booksQ quitWhat do you want to do? TWich title do you looking for? ...(write a list of all the books found)and so on. 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130409/69e81b03/attachment.html>

From rocketmanblamb at gmail.com  Tue Apr  9 23:59:00 2013
From: rocketmanblamb at gmail.com (Brian Lamb)
Date: Tue, 9 Apr 2013 17:59:00 -0400
Subject: [Tutor] building a website with python
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF474182BD269@SCACMX008.exchad.jpmchase.net>
References: <7740DF86-8DD9-4364-ABEA-FDF4D1D9E031@gmail.com>
	<5B80DD153D7D744689F57F4FB69AF474182BD269@SCACMX008.exchad.jpmchase.net>
Message-ID: <0B40E011-D620-4205-A3CF-14A32DD98E23@gmail.com>

Without overly proselytizing any particular host you might want to check out Webfaction for hosting.  They have an excellent reputation for Python hosting and reasonable rates.   There are of course others that some may prefer, you can certainly google for other web hosting comparisons.

Also there are other frameworks that may be worth your time to investigate, as with everything it really depends what you are trying to accomplish.

Best of Luck,
Brian
On Apr 9, 2013, at 5:54 PM, Prasad, Ramit wrote:

> Benjamin Fishbein wrote:
>> 
>> Hello. I learned Python this past year (with help from many of you) and wrote many programs for my
>> small business. Now I want to build a website. I acquired the domain name through godaddy.com
>> (bookchicken.com) but have not found hosting yet.
>> I learned html, css, and javascript via codeacademy.org, but have never built a website.
>> I would like to build it with Python, and was wondering if you could give me some pointers about what
>> I need to learn first: Django is the thing to use? And do I need specific hosting to use python or are
>> all hosts basically the same.
>> Thanks,
>> Ben
> 
> http://wiki.python.org/moin/WebFrameworks
> 
> Lots of Python frameworks to choose from, though Django is the most famous/popular. There are
> lighter frameworks too, depending on what you need.
> 
> Your hosting solution to support Python, and I do not believe all hosts support Python. You 
> should double check with whatever host you choose.
> 
> 
> ~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 at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor


From s.shall at virginmedia.com  Mon Apr  8 16:49:50 2013
From: s.shall at virginmedia.com (Sydney Shall)
Date: Mon, 08 Apr 2013 15:49:50 +0100
Subject: [Tutor] How to extract a float from an instancemethod call
In-Reply-To: <5162BD85.7070207@davea.name>
References: <5162BAB1.8010700@virginmedia.com> <5162BD85.7070207@davea.name>
Message-ID: <5162D90E.8050603@virginmedia.com>



On 08/04/2013 13:52, Dave Angel wrote:
> On 04/08/2013 08:40 AM, Sydney Shall wrote:
>> Hi,
>> I am  learning Python.
>>
>> I use MAC OSX 10.6.8
>> Python 2.7.3
>>
>> I have been given a project to write a program involving random walks.
>> I have drafted a program which has passed all the static tests, but on
>> testing my program i get the following error message:
>>
>>
>> Traceback (most recent call last):
>>    File "/Users/Sydney/Documents/6.00x Files/Problem
>> Sets/ProblemSet7/ps7 copy.py", line 303, in <module>
>>      testRobotMovement(StandardRobot, RectangularRoom)
>>    File "ps7_verify_movement.py", line 12, in testRobotMovement
>>    File "/Users/Sydney/Documents/6.00x Files/Problem
>> Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean
>>      while self.room.isPositionInRoom(self.position) == False:
>>    File "/Users/Sydney/Documents/6.00x Files/Problem
>> Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom
>>      return self.room[(x,y)] in self.room
>> KeyError: (<bound method Position.getX of <__main__.Position object at
>> 0x4699490>>, <bound method Position.getY of <__main__.Position object at
>> 0x4699490>>)
>>  >>>
>>
>> The program text referred to is the following, I give the whole module,
>> which is part of a larger program.
>>   def isPositionInRoom(self, pos):
>>          """
>>          Return True if pos is inside the room.
>>
>>          pos: a Position object.
>>          returns: True if pos is in the room, False otherwise.
>>          """
>>          x = pos.getX
>>          y = pos.getY
>
> You never show the code for Position.getX and Position.getY, but I'd 
> expect they're methods that take no arguments.  in that case, you need 
> parens in order to call them.
>
>            x = pos.getX()
>            y = pos.getY()
>
>>          return self.room[(x,y)] in self.room
>>
>
> a simple print of x and y could have revealed this as well.
>
>
Dear Dave,
Thanks for  pointing out my mistake. I thought it would be some small 
error on my part.
I had a print statement, but I could not correctly interpret the output.
It solves that problem.



-- 
Sydney Shall

From breamoreboy at yahoo.co.uk  Sun Apr 14 19:41:00 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sun, 14 Apr 2013 18:41:00 +0100
Subject: [Tutor] Issue With a Python Game
In-Reply-To: <CAC1EF+HYS9evt61WyP1+-9cxHz_u2zgS0Nhv3qZvpNGNg_885Q@mail.gmail.com>
References: <CAC1EF+HYS9evt61WyP1+-9cxHz_u2zgS0Nhv3qZvpNGNg_885Q@mail.gmail.com>
Message-ID: <kkeplg$38d$1@ger.gmane.org>

On 13/04/2013 14:13, John Bochicchio wrote:
> I have a question about a game I am making. I finished the overall code,
> but keep getting errors when I try to play. This is my most common error:
> C:\Users\John\Documents\Python Games\Noah>python nickeladventuredemo.py
> Traceback (most recent call last):
>    File "nickeladventuredemo.py", line 451, in <module>
>      main()
>    File "nickeladventuredemo.py", line 78, in main
>      levels = readLevelsFile('levels.txt')
>    File "nickeladventuredemo.py", line 371, in readLevelsFile
>      assert startx != None  and starty!= None, 'Level %s (around line
> %s) in %s i
> s missing a "@" or "+" to mark the start point.' % (levelNum+1, lineNum,
> filenam
> e)
> AssertionError: Level 1 (around line 10) in levels.txt is missing a "@"
> or "+" t
> o mark the start point.
>
> The Code:
> import random, sys, copy, os, pygame
>

I've stripped the remaining 450 lines of code as it's got the dread 
double spaced google disease, please see my signature.  You're also far 
more likely to get responses if your question follows the guidelines 
given here http://www.sscce.org/, particularly if someone already has 
pygame installed, which I don't.

However I did note one area where you can simplfy your code.  You've 
many lines using this type of construct.

for i in range(len(ships)):
     doSomething(ships[i])

There's rarely a need for this in Python.  Use this instead.

for ship in ships:
     doSomething(ship)

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From eryksun at gmail.com  Sun Apr 14 19:50:44 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 14 Apr 2013 13:50:44 -0400
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <CAJ5mJ2u81rNpV7Ayq6+A8NnMUVnQCcHJnpEETdz2kxn_+hVAtQ@mail.gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
	<CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
	<kkcacv$a75$1@ger.gmane.org> <5169B26B.1050707@gmail.com>
	<516A0D01.6000903@pearwood.info>
	<CAJ5mJ2u81rNpV7Ayq6+A8NnMUVnQCcHJnpEETdz2kxn_+hVAtQ@mail.gmail.com>
Message-ID: <CACL+1atC8c396mBw_vy_ii0EhE6Ozf1RBfduB7dQfk4cHDbKAA@mail.gmail.com>

On Sun, Apr 14, 2013 at 12:46 PM, Saad Javed <sbjaved at gmail.com> wrote:
>
> As for the underscores, what happened is that I didn't voluntarily add the
> underscores to begin with. If you read the emails again, after Mark's answer
> about not looping, I asked that the dictionary created as a result of his
> code wasn't ordered.

You replied with a multipart MIME message that included both plain
text and HTML versions.

HTML:

    if item.startswith((
      &#39;Mon&#39;,
      &#39;Tue&#39;,
      &#39;<u></u>Wed&#39;,
      &#39;Thu&#39;,
      &#39;Fri&#39;,
      &#39;Sat&#39;,
      &#39;Sun&#39;))<u></u>

Text:

    item.startswith(
        ('Mon','Tue','**Wed','Thu','Fri','Sat','Sun'))**

I don't know how the <u></u> underline tags got in there. They aren't
in the quote in Mark's message. Either way, for the plain text part,
your email program substituted "**". Others substituted "__".

There'd be no problem if you didn't use rich text in the first place.
Email programs always manage to mangle HTML. Besides, it really has no
place whatsoever on this forum. I always reply in plain text here.

From sbjaved at gmail.com  Sun Apr 14 22:27:11 2013
From: sbjaved at gmail.com (Saad Bin Javed)
Date: Mon, 15 Apr 2013 01:27:11 +0500
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <CACL+1atC8c396mBw_vy_ii0EhE6Ozf1RBfduB7dQfk4cHDbKAA@mail.gmail.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
	<CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
	<kkcacv$a75$1@ger.gmane.org> <5169B26B.1050707@gmail.com>
	<516A0D01.6000903@pearwood.info>
	<CAJ5mJ2u81rNpV7Ayq6+A8NnMUVnQCcHJnpEETdz2kxn_+hVAtQ@mail.gmail.com>
	<CACL+1atC8c396mBw_vy_ii0EhE6Ozf1RBfduB7dQfk4cHDbKAA@mail.gmail.com>
Message-ID: <516B111F.9050303@gmail.com>

On 04/14/2013 10:50 PM, eryksun wrote:

> I don't know how the <u></u> underline tags got in there. They aren't
> in the quote in Mark's message. Either way, for the plain text part,
> your email program substituted "**". Others substituted "__".
>
> There'd be no problem if you didn't use rich text in the first place.
> Email programs always manage to mangle HTML. Besides, it really has no
> place whatsoever on this forum. I always reply in plain text here.

I've set changed settings in thunderbird to send plain text emails to 
python.org domain. Hopefully it won't be an issue again!


From wprins at gmail.com  Sun Apr 14 23:16:05 2013
From: wprins at gmail.com (Walter Prins)
Date: Sun, 14 Apr 2013 22:16:05 +0100
Subject: [Tutor] Issue With a Python Game
In-Reply-To: <CAC1EF+Et032xRjzXEeWHxZ0xA0kx+iLv66xN-3F1KiTi9nVzcg@mail.gmail.com>
References: <CAC1EF+Et032xRjzXEeWHxZ0xA0kx+iLv66xN-3F1KiTi9nVzcg@mail.gmail.com>
Message-ID: <CANLXbfDUnZbUsdzMtq=TLKK1OY6HFuYsFZdc0r+k8V6avoOP9Q@mail.gmail.com>

Hi John,

On 10 April 2013 15:21, John Bochicchio <luckytsukune at gmail.com> wrote:

> I have a question about a game I am making. I finished the overall code,
> but keep getting errors when I try to play. This is my most common error:
> C:\Users\John\Documents\Python Games\Noah>python nickeladventuredemo.py
> Traceback (most recent call last):
>   File "nickeladventuredemo.py", line 451, in <module>
>     main()
>   File "nickeladventuredemo.py", line 78, in main
>     levels = readLevelsFile('levels.txt')
>   File "nickeladventuredemo.py", line 371, in readLevelsFile
>     assert startx != None  and starty!= None, 'Level %s (around line %s)
> in %s i
> s missing a "@" or "+" to mark the start point.' % (levelNum+1, lineNum,
> filenam
> e)
> AssertionError: Level 1 (around line 10) in levels.txt is missing a "@" or
> "+" t
> o mark the start point.
>
> The error has something to do with the levels. I will attach the code and
> levels, as they are fairly long.
>

Firstly please next time include a segment of the failing code in the email
-- not everyone is prepared to or can be bothered to download and wade
through a large source file just to get to the bottom of an program error.

Secondly, re your your first assertion statement: it assumes that the
problem is due to a problem in the levels.txt file, which is not the case
here.  You'd do better IMHO to maybe not be so creative/presumptuous with
 the error message, and rather have it report exactly what the actual
assertion conditions (and maybe variable values at the time) is that failed
(in this case values of startx, starty.)   You might also consider rather
using Exceptions here.

All that said, the problem is you have the code throwing the exception at
the wrong level of indent.  You need to de-indent all the assert statements
as well as the code that follows up to but excluding the return statement
so that it's at the same level of the first "for" loop.  (Differently put,
the reason the assertion is likely failing is because you're doing your
asserts before the loops have finished processing/reading your mapObj. You
presumably want the asserts once the mapObj's been finished processing by
the loop.)

As an aside,  the next failure you'll likely run into is the third assert,
which expects len(stars) >= len(goals), which I assume will fail as you are
not reading anything into "stars" list anywhere as you do for  goals.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130414/8c488fa9/attachment.html>

From davea at davea.name  Mon Apr 15 01:56:06 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 14 Apr 2013 19:56:06 -0400
Subject: [Tutor] Create Library
In-Reply-To: <DUB121-W66BBA0260D75479254B0587C60@phx.gbl>
References: <DUB121-W66BBA0260D75479254B0587C60@phx.gbl>
Message-ID: <516B4216.3010909@davea.name>

On 04/08/2013 09:31 PM, Negin Nayeri wrote:
> Hi!Im supposed to do a Library in Python and I don't even know how to begin! Please just help me. Like what kind of attributes do you think I should have, how do I store information? The file with the books and authors I must fix, do think I should write in txt format or like in Excel. Please help me.
>
>
> Write a program used to handling simpler library routines. The program should be able to search for books in terms of both author and title. You should also be able to borrow and return books, put new books in the registry and remove the old books, and print a list on the screen of all books. The books will be sorted with respect to the author.The books are stored in a text file that you can write yourself. Your file does not contain more than ten books, but your program should be valid also for a large number of books.The program will remember which books are utl?nade?ven if the user turns off and restarts the application.It can look some thing like this:Welcome to Adriana's Library:T search for titelF search by authorL Borrow BookR Return BookN Register new bookB remove book from registerA see a list of all booksQ quitWhat do you want to do? TWich title do you looking for? ...(write a list of all the books found)and so on. 		 	   		
>
>

The formatting of that message sure got messed up.   Two very long 
lines.  You must have sent the message as html, instead of text.

Your assignment does NOT say you're supposed to create a Library.  It 
says you're supposed to create routines that might be used in a library.

It DOES tell you how to store your information;  use a text file.




-- 
DaveA

From ysoliman at uncc.edu  Mon Apr 15 02:35:51 2013
From: ysoliman at uncc.edu (Soliman, Yasmin)
Date: Mon, 15 Apr 2013 00:35:51 +0000
Subject: [Tutor] (no subject)
Message-ID: <211A029E048A2245A6E00BA02FEFF88A6BF5F7E0@BL2PRD0310MB373.namprd03.prod.outlook.com>

Hi everyone. I just need to know why this programs tells me End is not defined, what can I o to fix this issue? Thanks in advance.

hrList=[]
while True:
    heartrate= float(input('Enter heart rate as beats per min: '))
    hrList.append(heartrate)
    
    if heartrate=='End':
        print '\nThank you for using this program! Bye.'
        break     
    
    total_sum = 0;
    length = len(hrList)
    
    for i in range(0, length):
        total_sum += hrList[i]
    
    average = total_sum / length
    
    print average 

From davea at davea.name  Mon Apr 15 04:44:08 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 14 Apr 2013 22:44:08 -0400
Subject: [Tutor] (no subject)
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A6BF5F7E0@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A6BF5F7E0@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <516B6978.4010404@davea.name>

On 04/14/2013 08:35 PM, Soliman, Yasmin wrote:
> Hi everyone. I just need to know why this programs tells me End is not defined, what can I o to fix this issue? Thanks in advance.
>
> hrList=[]
> while True:
>      heartrate= float(input('Enter heart rate as beats per min: '))
>      hrList.append(heartrate)
>
>      if heartrate=='End':
>          print '\nThank you for using this program! Bye.'
>          break
>
>      total_sum = 0;
>      length = len(hrList)
>
>      for i in range(0, length):
>          total_sum += hrList[i]
>
>      average = total_sum / length
>
>      print average
>


I can't see any place there where such an error might occur.  But I can 
see where you forgot the parens in the call to print().

You might get better advice by telling us the Python version, and the 
complete error message traceback.  That'll show us exactly what was 
executing when the exception happened.

Oh wait.  Perhaps you were running Python 2.x, rather than 3.x.  In that 
case, you should have used raw_input(), not input.  Input will eval 
whatever the user types, and if he types "End" he'll get an error:

Enter heart rate as beats per min: End
Traceback (most recent call last):
   File "soliman2.py", line 6, in <module>
     heartrate= float(input('Enter heart rate as beats per min: '))
   File "<string>", line 1, in <module>
NameError: name 'End' is not defined

Once you fix that, you'll get another error.

Enter heart rate as beats per min: End
Traceback (most recent call last):
   File "soliman2.py", line 6, in <module>
     heartrate= float(raw_input('Enter heart rate as beats per min: '))
ValueError: could not convert string to float: End

That's because you try to convert the string "End" into an integer 
before you check it for the terminating value.  You want to do the 
raw_input first, then the check for End, then convert to int, then 
append and print the stuff.


Alternatively, you could just tell the user to enter "0" when he wants 
to quit.





-- 
DaveA

From zakiakhmad at gmail.com  Mon Apr 15 07:59:56 2013
From: zakiakhmad at gmail.com (Zaki Akhmad)
Date: Mon, 15 Apr 2013 12:59:56 +0700
Subject: [Tutor] Scheduling Python Execution
Message-ID: <CAE7Ck-RgQMoC7aDGj=07gEKLPeAsBq8TQ3bdO1U0Wt9Q2UpGWg@mail.gmail.com>

Hi all,

I'd like to execute python script for specific times. I prefer not to
use cron, since this times will be very varies.

Example, my requirement is, this python script will execute at:

13:00:00
14:05:00
14:35:00
15:20:00

I know this is gonna be a long script to run. Check the time.ctime()
then execute. Is designing with this approach isn't good? Since it
will be a long script running.

I've read the sched module.

And the enter module has delay argument. So is better that I calculate
the delay rather than the ctime to execute?

Regards,

-- 
Zaki Akhmad

From ybronhei at redhat.com  Mon Apr 15 09:01:37 2013
From: ybronhei at redhat.com (Yaniv Bronheim)
Date: Mon, 15 Apr 2013 03:01:37 -0400 (EDT)
Subject: [Tutor] How to extract a float from an instancemethod call
In-Reply-To: <5162D90E.8050603@virginmedia.com>
References: <5162BAB1.8010700@virginmedia.com> <5162BD85.7070207@davea.name>
	<5162D90E.8050603@virginmedia.com>
Message-ID: <1986072937.168546.1366009297778.JavaMail.root@redhat.com>

by reading the exception you see that you pass function pointer instead of a value
"KeyError: (<bound method Position.getX of <__main__.Position object at 
0x4699490>>, <bound method Position.getY of <__main__.Position object at 
0x4699490>>)"

as if you just print pos.getX and not pos.getX(), you will see the exact output - <__main__.Position object at 0x4699490>
..

Regards,
Yaniv.

----- Original Message -----
> From: "Sydney Shall" <s.shall at virginmedia.com>
> To: "Dave Angel" <davea at davea.name>
> Sent: Monday, April 8, 2013 5:49:50 PM
> Subject: Re: [Tutor] How to extract a float from an instancemethod call
> 
> 
> 
> On 08/04/2013 13:52, Dave Angel wrote:
> > On 04/08/2013 08:40 AM, Sydney Shall wrote:
> >> Hi,
> >> I am  learning Python.
> >>
> >> I use MAC OSX 10.6.8
> >> Python 2.7.3
> >>
> >> I have been given a project to write a program involving random walks.
> >> I have drafted a program which has passed all the static tests, but on
> >> testing my program i get the following error message:
> >>
> >>
> >> Traceback (most recent call last):
> >>    File "/Users/Sydney/Documents/6.00x Files/Problem
> >> Sets/ProblemSet7/ps7 copy.py", line 303, in <module>
> >>      testRobotMovement(StandardRobot, RectangularRoom)
> >>    File "ps7_verify_movement.py", line 12, in testRobotMovement
> >>    File "/Users/Sydney/Documents/6.00x Files/Problem
> >> Sets/ProblemSet7/ps7 copy.py", line 285, in updatePositionAndClean
> >>      while self.room.isPositionInRoom(self.position) == False:
> >>    File "/Users/Sydney/Documents/6.00x Files/Problem
> >> Sets/ProblemSet7/ps7 copy.py", line 163, in isPositionInRoom
> >>      return self.room[(x,y)] in self.room
> >> KeyError: (<bound method Position.getX of <__main__.Position object at
> >> 0x4699490>>, <bound method Position.getY of <__main__.Position object at
> >> 0x4699490>>)
> >>  >>>
> >>
> >> The program text referred to is the following, I give the whole module,
> >> which is part of a larger program.
> >>   def isPositionInRoom(self, pos):
> >>          """
> >>          Return True if pos is inside the room.
> >>
> >>          pos: a Position object.
> >>          returns: True if pos is in the room, False otherwise.
> >>          """
> >>          x = pos.getX
> >>          y = pos.getY
> >
> > You never show the code for Position.getX and Position.getY, but I'd
> > expect they're methods that take no arguments.  in that case, you need
> > parens in order to call them.
> >
> >            x = pos.getX()
> >            y = pos.getY()
> >
> >>          return self.room[(x,y)] in self.room
> >>
> >
> > a simple print of x and y could have revealed this as well.
> >
> >
> Dear Dave,
> Thanks for  pointing out my mistake. I thought it would be some small
> error on my part.
> I had a print statement, but I could not correctly interpret the output.
> It solves that problem.
> 
> 
> 
> --
> Sydney Shall
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
> 

From alan.gauld at btinternet.com  Mon Apr 15 10:51:37 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 15 Apr 2013 09:51:37 +0100
Subject: [Tutor] Scheduling Python Execution
In-Reply-To: <CAE7Ck-RgQMoC7aDGj=07gEKLPeAsBq8TQ3bdO1U0Wt9Q2UpGWg@mail.gmail.com>
References: <CAE7Ck-RgQMoC7aDGj=07gEKLPeAsBq8TQ3bdO1U0Wt9Q2UpGWg@mail.gmail.com>
Message-ID: <kkgf2l$8df$1@ger.gmane.org>

On 15/04/13 06:59, Zaki Akhmad wrote:

> I'd like to execute python script for specific times. I prefer not to
> use cron, since this times will be very varies.

multiple cron jobs will be less work for your computer than running a 
long term program constantly checking times and launching your 
scripts... That's called reinventing the wheel with a square one...

There are more modern (and more efficent) replacements for cron but 
given your requirements cron still looks like the best bet.

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


From jappy.db at gmail.com  Mon Apr 15 10:54:33 2013
From: jappy.db at gmail.com (Jabesa Daba)
Date: Mon, 15 Apr 2013 09:54:33 +0100
Subject: [Tutor] Help on python
Message-ID: <CAG=4q87MoVzZ=G9vtqhbiTaFzr0bqy+T2KDW5hLSuZp0WLdv4Q@mail.gmail.com>

is it possible to reorder a sentence in the form of SVO (Subject Verb
Object) into the form of SOV (Subject Object Verb) by using a python
program? if so, how?

regards,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130415/d6b45b10/attachment.html>

From breamoreboy at yahoo.co.uk  Mon Apr 15 11:23:40 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Mon, 15 Apr 2013 10:23:40 +0100
Subject: [Tutor] (no subject)
In-Reply-To: <211A029E048A2245A6E00BA02FEFF88A6BF5F7E0@BL2PRD0310MB373.namprd03.prod.outlook.com>
References: <211A029E048A2245A6E00BA02FEFF88A6BF5F7E0@BL2PRD0310MB373.namprd03.prod.outlook.com>
Message-ID: <kkggup$s7t$1@ger.gmane.org>

You've already had a sound answer from Dave Angel, I've just a few 
comments below.

On 15/04/2013 01:35, Soliman, Yasmin wrote:
> Hi everyone. I just need to know why this programs tells me End is not defined, what can I o to fix this issue? Thanks in advance.
>
> hrList=[]
> while True:
>      heartrate= float(input('Enter heart rate as beats per min: '))
>      hrList.append(heartrate)
>
>      if heartrate=='End':
>          print '\nThank you for using this program! Bye.'
>          break
>
>      total_sum = 0;

No need for the semicolon.

>      length = len(hrList)
>      for i in range(0, length):
>          total_sum += hrList[i]

For the third time in three days, you rarely need to write a loop like 
this in Python :)

for hr in hrList:
     total_sum += hr

>
>      average = total_sum / length

Part of the learning curve, but the lot could be written as.

average = sum(hrList) / len(hrList)

>
>      print average
>

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From zakiakhmad at gmail.com  Mon Apr 15 11:23:56 2013
From: zakiakhmad at gmail.com (Zaki Akhmad)
Date: Mon, 15 Apr 2013 16:23:56 +0700
Subject: [Tutor] Scheduling Python Execution
In-Reply-To: <kkgf2l$8df$1@ger.gmane.org>
References: <CAE7Ck-RgQMoC7aDGj=07gEKLPeAsBq8TQ3bdO1U0Wt9Q2UpGWg@mail.gmail.com>
	<kkgf2l$8df$1@ger.gmane.org>
Message-ID: <CAE7Ck-S8iAXNCOnaAaMEo8nvqrvQzYjpkrLR1hWB5Ow5bVf6Qw@mail.gmail.com>

On Mon, Apr 15, 2013 at 3:51 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:

> multiple cron jobs will be less work for your computer than running a long
> term program constantly checking times and launching your scripts... That's
> called reinventing the wheel with a square one...
>
> There are more modern (and more efficent) replacements for cron but given
> your requirements cron still looks like the best bet.

Actually,

I want to write a twitter bot which runs on a specific time. For an
idea, I'd like to have this twitter bot tweet every sunrise and
sunset, everyday. Since everyday the sunrise and the sunset time are
vary, what are the best way to do it?

Should I entered the sunset and the sunrise manually?

Thanks!
-- 
Zaki Akhmad

From breamoreboy at yahoo.co.uk  Mon Apr 15 11:31:45 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Mon, 15 Apr 2013 10:31:45 +0100
Subject: [Tutor] Help on python
In-Reply-To: <CAG=4q87MoVzZ=G9vtqhbiTaFzr0bqy+T2KDW5hLSuZp0WLdv4Q@mail.gmail.com>
References: <CAG=4q87MoVzZ=G9vtqhbiTaFzr0bqy+T2KDW5hLSuZp0WLdv4Q@mail.gmail.com>
Message-ID: <kkghdu$14g$1@ger.gmane.org>

On 15/04/2013 09:54, Jabesa Daba wrote:
> is it possible to reorder a sentence in the form of SVO (Subject Verb
> Object) into the form of SOV (Subject Object Verb) by using a python
> program? if so, how?
>
> regards,
>

Yes.  By writing code.

You could have answered your own question by typing something like 
"python natural language processing" into your favourite search engine.

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From Steve.Flynn at capita.co.uk  Mon Apr 15 11:35:29 2013
From: Steve.Flynn at capita.co.uk (Flynn, Stephen (L & P - IT))
Date: Mon, 15 Apr 2013 10:35:29 +0100
Subject: [Tutor] Scheduling Python Execution
In-Reply-To: <CAE7Ck-S8iAXNCOnaAaMEo8nvqrvQzYjpkrLR1hWB5Ow5bVf6Qw@mail.gmail.com>
References: <CAE7Ck-RgQMoC7aDGj=07gEKLPeAsBq8TQ3bdO1U0Wt9Q2UpGWg@mail.gmail.com><kkgf2l$8df$1@ger.gmane.org>
	<CAE7Ck-S8iAXNCOnaAaMEo8nvqrvQzYjpkrLR1hWB5Ow5bVf6Qw@mail.gmail.com>
Message-ID: <D35D4ADAE41B404A9EB381E750C1A5A503B6F449@CAPPRWMMBX14.central.ad.capita.co.uk>

> I want to write a twitter bot which runs on a specific time. For an
> idea, I'd like to have this twitter bot tweet every sunrise and
> sunset, everyday. Since everyday the sunrise and the sunset time are
> vary, what are the best way to do it?

Have the bot calculate sunrise and sunset for the following day and
re-schedule itself for those times.



This email and any attachment to it are confidential.  Unless you are the intended recipient, you may not use, copy or disclose either the message or any information contained in the message. If you are not the intended recipient, you should delete this email and notify the sender immediately.

Any views or opinions expressed in this email are those of the sender only, unless otherwise stated.  All copyright in any Capita material in this email is reserved.

All emails, incoming and outgoing, may be recorded by Capita and monitored for legitimate business purposes. 

Capita exclude all liability for any loss or damage arising or resulting from the receipt, use or transmission of this email to the fullest extent permitted by law.

From svenito at gmail.com  Mon Apr 15 12:53:05 2013
From: svenito at gmail.com (Sven)
Date: Mon, 15 Apr 2013 11:53:05 +0100
Subject: [Tutor] Scheduling Python Execution
In-Reply-To: <CAE7Ck-S8iAXNCOnaAaMEo8nvqrvQzYjpkrLR1hWB5Ow5bVf6Qw@mail.gmail.com>
References: <CAE7Ck-RgQMoC7aDGj=07gEKLPeAsBq8TQ3bdO1U0Wt9Q2UpGWg@mail.gmail.com>
	<kkgf2l$8df$1@ger.gmane.org>
	<CAE7Ck-S8iAXNCOnaAaMEo8nvqrvQzYjpkrLR1hWB5Ow5bVf6Qw@mail.gmail.com>
Message-ID: <CAEH=cXVCR36w8Y211nxeMj+DBunAzrnj2yEo0GDSDSmLv+uPsQ@mail.gmail.com>

I assume that you are getting these times from somewhere, hopefully a
website. To do as Steve says, you would just scrape (or use the API if
there is one) to get the times, and schedule a tweet at that time. If you
do use cron you can make use of https://pypi.python.org/pypi/python-crontab


On 15 April 2013 10:23, Zaki Akhmad <zakiakhmad at gmail.com> wrote:

> On Mon, Apr 15, 2013 at 3:51 PM, Alan Gauld <alan.gauld at btinternet.com>
> wrote:
>
> > multiple cron jobs will be less work for your computer than running a
> long
> > term program constantly checking times and launching your scripts...
> That's
> > called reinventing the wheel with a square one...
> >
> > There are more modern (and more efficent) replacements for cron but given
> > your requirements cron still looks like the best bet.
>
> Actually,
>
> I want to write a twitter bot which runs on a specific time. For an
> idea, I'd like to have this twitter bot tweet every sunrise and
> sunset, everyday. Since everyday the sunrise and the sunset time are
> vary, what are the best way to do it?
>
> Should I entered the sunset and the sunrise manually?
>
> Thanks!
> --
> Zaki Akhmad
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
./Sven
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130415/576b4988/attachment.html>

From alan.gauld at btinternet.com  Mon Apr 15 13:56:10 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 15 Apr 2013 12:56:10 +0100
Subject: [Tutor] Help on python
In-Reply-To: <CAG=4q87MoVzZ=G9vtqhbiTaFzr0bqy+T2KDW5hLSuZp0WLdv4Q@mail.gmail.com>
References: <CAG=4q87MoVzZ=G9vtqhbiTaFzr0bqy+T2KDW5hLSuZp0WLdv4Q@mail.gmail.com>
Message-ID: <kkgpsl$sve$1@ger.gmane.org>

On 15/04/13 09:54, Jabesa Daba wrote:
> is it possible to reorder a sentence in the form of SVO (Subject Verb
> Object) into the form of SOV (Subject Object Verb) by using a python
> program? if so, how?

Python is a general purpose programming language so yes, you can program 
it to do any computational task. How much work is involved depends on 
how well you can define the algorithm and whether somebody else has 
already implemented it for you in Python.

In your case you need to consider which language you are processing and 
what the grammatical rules are (what is a word? How do you identify a 
subject, object and verb? What are the separator rules and do you need 
to consider changes of endings etc when you change order? etc)
Just how sophisticated does it need to be?)

There are several libraries that can help ranging from general
purpose text processing and parsers to natural language tookits.
Whatever you use you will still need a fair amount of effort
to get it working. Google (or any other search engine!) is your
friend.

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


From sbjaved at gmail.com  Mon Apr 15 15:48:06 2013
From: sbjaved at gmail.com (Saad Bin Javed)
Date: Mon, 15 Apr 2013 18:48:06 +0500
Subject: [Tutor] creating dictionary from a list
In-Reply-To: <516BBD7D.2060306@virginmedia.com>
References: <51689E54.1010708@gmail.com> <5168B35D.2060207@pearwood.info>
	<CAF6DajJKEktiuqEMEishcPDM3YGNqDOYNwrxA2oa4m4i7s5v0w@mail.gmail.com>
	<51696D09.4000103@gmail.com> <kkbssn$cei$1@ger.gmane.org>
	<CAJ5mJ2szrVy4ve99EQ+0ubD_N18sB6DsdTyBasrDdzWS-DTksA@mail.gmail.com>
	<kkc83e$krr$1@ger.gmane.org>
	<CAJ5mJ2sTxA-9T9uSMfQELedtH2j8uz-EdhQkk0jnyR67YajNtw@mail.gmail.com>
	<kkcacv$a75$1@ger.gmane.org> <5169B26B.1050707@gmail.com>
	<516A0D01.6000903@pearwood.info>
	<CAJ5mJ2u81rNpV7Ayq6+A8NnMUVnQCcHJnpEETdz2kxn_+hVAtQ@mail.gmail.com>
	<CACL+1atC8c396mBw_vy_ii0EhE6Ozf1RBfduB7dQfk4cHDbKAA@mail.gmail.com>
	<516B111F.9050303@gmail.com> <516BBD7D.2060306@virginmedia.com>
Message-ID: <516C0516.8010104@gmail.com>

On 04/15/2013 01:42 PM, Sydney Shall wrote:
> Dear Saad,
> Could you please tell me how to change the Thunderbird settings to plain
> text.
> I could not find the correct menu.
> Many thanks,
> Sydney

Go to Preferences > Composition > Send Options and add python.org under 
Plain Text Domains.


From doark at mail.com  Mon Apr 15 21:00:19 2013
From: doark at mail.com (frank ernest)
Date: Mon, 15 Apr 2013 15:00:19 -0400
Subject: [Tutor] The proper use of classes
Message-ID: <20130415190020.51550@gmx.com>

Thanks guys! I've got my class up and running and am having a fine time programming in python... again.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130415/c828b9b0/attachment.html>

From dyoo at hashcollision.org  Tue Apr 16 00:56:58 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Mon, 15 Apr 2013 16:56:58 -0600
Subject: [Tutor] Help on python
In-Reply-To: <kkgpsl$sve$1@ger.gmane.org>
References: <CAG=4q87MoVzZ=G9vtqhbiTaFzr0bqy+T2KDW5hLSuZp0WLdv4Q@mail.gmail.com>
	<kkgpsl$sve$1@ger.gmane.org>
Message-ID: <CAGZAPF4R3GUqbucuGnS4Dzyx1omxg14fSTKtacy11BKKvvr-pg@mail.gmail.com>

For example, see: http://nltk.org.

From steve at pearwood.info  Tue Apr 16 03:27:30 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 16 Apr 2013 11:27:30 +1000
Subject: [Tutor] Scheduling Python Execution
In-Reply-To: <CAE7Ck-S8iAXNCOnaAaMEo8nvqrvQzYjpkrLR1hWB5Ow5bVf6Qw@mail.gmail.com>
References: <CAE7Ck-RgQMoC7aDGj=07gEKLPeAsBq8TQ3bdO1U0Wt9Q2UpGWg@mail.gmail.com>
	<kkgf2l$8df$1@ger.gmane.org>
	<CAE7Ck-S8iAXNCOnaAaMEo8nvqrvQzYjpkrLR1hWB5Ow5bVf6Qw@mail.gmail.com>
Message-ID: <516CA902.8090204@pearwood.info>

On 15/04/13 19:23, Zaki Akhmad wrote:
> On Mon, Apr 15, 2013 at 3:51 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>> multiple cron jobs will be less work for your computer than running a long
>> term program constantly checking times and launching your scripts... That's
>> called reinventing the wheel with a square one...
>>
>> There are more modern (and more efficent) replacements for cron but given
>> your requirements cron still looks like the best bet.
>
> Actually,
>
> I want to write a twitter bot which runs on a specific time.

That is exactly what cron is designed to do. Although given that the time you want will vary, my guess is that the lesser-known "at" job will be better.

Another option is the sched module, that lets you schedule tasks to run while your program is idling. It is not a replacement for cron or at, since it requires your program to be running. But for simple needs, it may do the job.

http://docs.python.org/2/library/sched.html
http://pymotw.com/2/sched/



>For an
> idea, I'd like to have this twitter bot tweet every sunrise and
> sunset, everyday. Since everyday the sunrise and the sunset time are
> vary, what are the best way to do it?

Sunrise and sunset *where*?

Because the world is a globe, sunrise and sunset vary from place to place. Even in one place, they also vary at different times of the year. If you google for "sunrise sunset algorithm", you may find a formula for calculating the time of each at a given latitude and longitude. Or not. I don't really know how complicated it is.


> Should I entered the sunset and the sunrise manually?

I don't know about "manually", but there's no standard Python command for giving you sunset and sunrise. You'll either need to find an existing program that does it, or write one yourself.




-- 
Steven

From amckenzie4 at gmail.com  Tue Apr 16 17:58:15 2013
From: amckenzie4 at gmail.com (Andy McKenzie)
Date: Tue, 16 Apr 2013 11:58:15 -0400
Subject: [Tutor] Hello, and a newbie question
Message-ID: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>

Hey folks.

I'm just starting to pick up Python, and I'd like to avoid some of the
mistakes I made in the past.  To elaborate on that, my primary
programming/scripting experience is PHP, with a little bit of Perl thrown
in.  Like so many people who write in PHP, I was entirely self-taught, and
would be the first to admit that a lot of what I've written is, well...
wrong.  It works, but it's sloppy and inefficient, because there were
standard constructions and solutions I just didn't know about.  I'd like to
avoid that with Python.

So:  my first two questions to the list.

1) Python 2.7 or 3.x?  I know I'm going to want to do some work with NLTK
(which appears to only have an alpha version out for Python 3), but I've
just gone through the hassle of dealing with an upgrade from PHP 4 to 5.3,
and I'd rather not start learning something that's already obsolete.  Any
words of advice?

2) Best practices.  I have the WROX Press Beginning Python book, which
targets Python 2.  Clearly that's of only limited value if I'm going to go
with Python 3, but it looks like it's at least going to be a good overview.
 But some of the stuff they do seems to be fairly personalized, rather than
trying to follow standards.  Should I just start out with the tutorial from
docs.python.org?  I would assume that that would start putting me in the
right habits from the beginning... is that accurate, or is there a better
way to go?

Thanks in advance,
  Andy McKenzie
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130416/91d8ae27/attachment.html>

From alan.gauld at btinternet.com  Tue Apr 16 18:22:56 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 16 Apr 2013 17:22:56 +0100
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
Message-ID: <kkjtsr$92h$1@ger.gmane.org>

On 16/04/13 16:58, Andy McKenzie wrote:

> 1) Python 2.7 or 3.x?  I know I'm going to want to do some work with
> NLTK (which appears to only have an alpha version out for Python 3), but
> I've just gone through the hassle of dealing with an upgrade from PHP 4
> to 5.3, and I'd rather not start learning something that's already
> obsolete.  Any words of advice?

Upgrading from P2 to P3 is not too onerous but there will be some 
changes to make at some po9nt.
However P2 is the one to go for if you want to do anything industrial 
just now because not all the 3rd party libraries (like NLTK) are fully 
ported to v3 yet, including some pretty significant ones.

OTOH If you are only experimenting/learning then going with P3 will 
avoid any relearning in the future.

> 2) Best practices.  I have the WROX Press Beginning Python book,

Sorry, I've never even seen that one so can't comment...

> <http://docs.python.org>?  I would assume that that would start putting
> me in the right habits from the beginning... is that accurate,

Yes, for existing programmers new to Python the official tutor is nearly 
always the best place to start. You can fill in the gaps elsewhere 
later. And the tutor is pretty short and fast paced, you can just about 
get through it all in an afternoon - certainly in a day.

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


From leamhall at gmail.com  Tue Apr 16 18:30:10 2013
From: leamhall at gmail.com (leam hall)
Date: Tue, 16 Apr 2013 12:30:10 -0400
Subject: [Tutor] Fwd:  Hello, and a newbie question
In-Reply-To: <CACv9p5qZnbey6ahi5YtDwUbS=aD=0F0eZ1Qab44pj6WzNCqW4A@mail.gmail.com>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
	<kkjtsr$92h$1@ger.gmane.org>
	<CACv9p5qZnbey6ahi5YtDwUbS=aD=0F0eZ1Qab44pj6WzNCqW4A@mail.gmail.com>
Message-ID: <CACv9p5ooXU6ZmVKWyGL8V=d9jzXmc-wZ6qiiw3mqeRikigXMiw@mail.gmail.com>

Python 2.x if you're working on existing servers like RHEL. If you're
having fun on a desktop, Python 3.

Free on-line college level class just started:
https://class.coursera.org/interactivepython-002/class/index

BTW, PHP ROCKS!  :P

Leam
  -- Also a PHP programmer


-- 
Mind on a Mission <http://leamhall.blogspot.com/>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130416/22377087/attachment.html>

From cybervigilante at gmail.com  Tue Apr 16 19:43:57 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 16 Apr 2013 10:43:57 -0700
Subject: [Tutor] How did this decimal error pop up?
Message-ID: <CALRAYNXM8=1Ys8ug9xpFw0JkvSA8Bgx9HDPe0PJTK+wELqNfMw@mail.gmail.com>

I was doing a simple training prog to figure change, and wanted to avoid
computer inaccuracy by using only two-decimal input and not using division
or mod where it would cause error. Yet, on a simple subtraction I got a
decimal error instead of a two decimal result, as per below. What gives?

cost = float(input('How much did the item cost?: '))
paid = float(input('How much did the customer give you?: '))
change = paid - cost

*#using 22.89 as cost and 248.76 as paid*

twenties = int(change / 20)
if twenties != 0:
  twentiesAmount = 20 * twenties
  change = change - twentiesAmount
  *#change is 5.8700000000000045, not 5.87 - how did I get this decimal
error when simply subtracting an integer from what  should be a
  #two-decimal amount?
*  print(twenties, ' twenties')
  print(change)

#and so forth for the rest of the change

-- 
*Jim Mooney

If you shoot a child you're a bad guy. If you splatter forty children
across a wall with a bomb, you're a heroic, manly Top Gun with gleaming Tom
Cruise teeth. The moral is you'll get laid more if you snuff a lot of
children than if you only snuff a few.*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130416/ea5ea55b/attachment.html>

From cybervigilante at gmail.com  Tue Apr 16 19:48:14 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 16 Apr 2013 10:48:14 -0700
Subject: [Tutor] oops - resending as plain text
Message-ID: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>

I accidentally sent as HTML so this is a resend in case that choked
the mailing prog ;')

I was doing a simple training prog to figure monetary change, and
wanted to avoid computer inaccuracy by using only two-decimal input
and not using division or mod where it would cause error. Yet, on a
simple subtraction I got a decimal error instead of a two decimal
result, as per below. What gives?

cost = float(input('How much did the item cost?: '))
paid = float(input('How much did the customer give you?: '))
change = paid - cost

#using 22.89 as cost and 248.76 as paid

twenties = int(change / 20)
if twenties != 0:
  twentiesAmount = 20 * twenties
  change = change - twentiesAmount
  #change is 5.8700000000000045, not 5.87 - how did I get this decimal
error when simply subtracting an integer from what  should be a
  #two-decimal amount?
  print(twenties, ' twenties')
  print(change)

#and so forth for the rest of the prog

Jim Mooney

From joel.goldstick at gmail.com  Tue Apr 16 20:16:24 2013
From: joel.goldstick at gmail.com (Joel Goldstick)
Date: Tue, 16 Apr 2013 14:16:24 -0400
Subject: [Tutor] oops - resending as plain text
In-Reply-To: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
References: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
Message-ID: <CAPM-O+zG6CfYArmC3ALC6f_UCUGAdSKcfD37S5A735S28VZ6ig@mail.gmail.com>

On Tue, Apr 16, 2013 at 1:48 PM, Jim Mooney <cybervigilante at gmail.com>wrote:

> I accidentally sent as HTML so this is a resend in case that choked
> the mailing prog ;')
>
> I was doing a simple training prog to figure monetary change, and
> wanted to avoid computer inaccuracy by using only two-decimal input
> and not using division or mod where it would cause error. Yet, on a
> simple subtraction I got a decimal error instead of a two decimal
> result, as per below. What gives?
>
> cost = float(input('How much did the item cost?: '))
> paid = float(input('How much did the customer give you?: '))
> change = paid - cost
>
> #using 22.89 as cost and 248.76 as paid
>
> twenties = int(change / 20)
> if twenties != 0:
>   twentiesAmount = 20 * twenties
>   change = change - twentiesAmount
>   #change is 5.8700000000000045, not 5.87 - how did I get this decimal
> error when simply subtracting an integer from what  should be a
>   #two-decimal amount?
>

because binary computers convert decimal numbers to binary numbers.  There
is often a rounding error.

>   print(twenties, ' twenties')
>   print(change)
>
> #and so forth for the rest of the prog
>
> Jim Mooney
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Joel Goldstick
http://joelgoldstick.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130416/c957f99e/attachment-0001.html>

From dfjennings at gmail.com  Tue Apr 16 20:29:48 2013
From: dfjennings at gmail.com (Don Jennings)
Date: Tue, 16 Apr 2013 14:29:48 -0400
Subject: [Tutor] oops - resending as plain text
In-Reply-To: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
References: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
Message-ID: <373E45EA-D702-4A95-AF37-262BCB45AE80@gmail.com>


On Apr 16, 2013, at 1:48 PM, Jim Mooney wrote:

> I accidentally sent as HTML so this is a resend in case that choked
> the mailing prog ;')
> 
> I was doing a simple training prog to figure monetary change, and
> wanted to avoid computer inaccuracy by using only two-decimal input
> and not using division or mod where it would cause error. Yet, on a
> simple subtraction I got a decimal error instead of a two decimal
> result, as per below. What gives?
> 
> cost = float(input('How much did the item cost?: '))
> paid = float(input('How much did the customer give you?: '))
> change = paid - cost
> 
> #using 22.89 as cost and 248.76 as paid
> 
> twenties = int(change / 20)
> if twenties != 0:
>  twentiesAmount = 20 * twenties
>  change = change - twentiesAmount
>  #change is 5.8700000000000045, not 5.87 - how did I get this decimal
> error when simply subtracting an integer from what  should be a

Now that Joel Goldstick has pointed out the reason, you may wonder what to do now. Answer? Use the decimal module:

http://docs.python.org/2/library/decimal.html

Although, you might prefer Doug Hellmann's introduction:

http://pymotw.com/2/decimal/

Take care,
Don


From sander.sweers at gmail.com  Tue Apr 16 20:55:17 2013
From: sander.sweers at gmail.com (Sander Sweers)
Date: Tue, 16 Apr 2013 20:55:17 +0200
Subject: [Tutor] oops - resending as plain text
In-Reply-To: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
References: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
Message-ID: <516D9E95.2050203@gmail.com>

On 04/16/2013 07:48 PM, Jim Mooney wrote:
> I accidentally sent as HTML so this is a resend in case that choked
> the mailing prog ;')
> 
> I was doing a simple training prog to figure monetary change, and
> wanted to avoid computer inaccuracy by using only two-decimal input
> and not using division or mod where it would cause error. Yet, on a
> simple subtraction I got a decimal error instead of a two decimal
> result, as per below. What gives?

Floats can not be represented accurately in binary and will have small
rounding errors. See
https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems.

> cost = float(input('How much did the item cost?: '))
> paid = float(input('How much did the customer give you?: '))
> change = paid - cost
> 
> #using 22.89 as cost and 248.76 as paid
> 
> twenties = int(change / 20)
> if twenties != 0:
>   twentiesAmount = 20 * twenties
>   change = change - twentiesAmount
>   #change is 5.8700000000000045, not 5.87 - how did I get this decimal
> error when simply subtracting an integer from what  should be a
>   #two-decimal amount?
>   print(twenties, ' twenties')
>   print(change)
> 
> #and so forth for the rest of the prog

You can use string formatting to show as much precision you want. Example:

>>> n = 5.8700000000000045
>>> print '%.2f' % n
5.87
>>> print '%.4f' % n
5.8700

Or use round(), example:

>>> round(n,2)
5.87

In your case I would just use string formatting to hide the rounding error.

Greets
~sander

From davea at davea.name  Tue Apr 16 22:18:16 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 16 Apr 2013 16:18:16 -0400
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
Message-ID: <516DB208.80006@davea.name>

On 04/16/2013 11:58 AM, Andy McKenzie wrote:
> Hey folks.
>
> I'm just starting to pick up Python, and I'd like to avoid some of the
> mistakes I made in the past.  To elaborate on that, my primary
> programming/scripting experience is PHP, with a little bit of Perl thrown
> in.  Like so many people who write in PHP, I was entirely self-taught, and
> would be the first to admit that a lot of what I've written is, well...
> wrong.  It works, but it's sloppy and inefficient, because there were
> standard constructions and solutions I just didn't know about.  I'd like to
> avoid that with Python.
>

Welcome to the mailing list.  I expect you'll find Python a much cleaner 
language than the other two, though php has some definite convenience 
for its particular niche.



> So:  my first two questions to the list.
>
> 1) Python 2.7 or 3.x?  I know I'm going to want to do some work with NLTK
> (which appears to only have an alpha version out for Python 3), but I've
> just gone through the hassle of dealing with an upgrade from PHP 4 to 5.3,
> and I'd rather not start learning something that's already obsolete.  Any
> words of advice?
>

If you have to use a library that's not available yet for 3.x, then you 
need to use 2.x  on the other hand, if you're learning now, maybe that 
library will be available by the time you actually need it.

For most people, I'd advise against trying to use a tutorial that 
targets a different version than you're running.  If you get frustrated 
quickly, you can get bogged down by the differences when you're just 
copying an exact program out of some book.

Python 3 in particular has spent some substantial effort cleaning up the 
warts, the biggest one being Unicode.  For beginning programmers using 
only ASCII, probably the main thing that'll bog you down is that print() 
is now a function, rather than a statement, so you need parentheses. 
But once you get used to seeing syntax error, you quickly get the hang 
of it.  And once you do, the function is much nicer.


> 2) Best practices.  I have the WROX Press Beginning Python book, which
> targets Python 2.  Clearly that's of only limited value if I'm going to go
> with Python 3, but it looks like it's at least going to be a good overview.
>   But some of the stuff they do seems to be fairly personalized, rather than
> trying to follow standards.  Should I just start out with the tutorial from
> docs.python.org?  I would assume that that would start putting me in the
> right habits from the beginning... is that accurate, or is there a better
> way to go?
>
> Thanks in advance,
>    Andy McKenzie

I'd start with the python.org tutorial for the version you're trying to 
learn.  Get serious about trying everything, and don't try to absorb it 
all in one sitting, even though it can be done.

And use a text editor that helps you indent, or even that colorizes your 
code.  And when you just want to try things, use the interpreter 
directly.  It's amazing what you can learn directly from it.  You can 
ask the interpreter lots of questions about an object:

    help(obj)
    dir(obj)
    print( type(obj) )
    print( repr(obj) )

And don't forget to post here when you seem to be stuck.  Sometimes a 
well placed comment beats days of struggling.  When you do get an 
exception you don't understand, paste the whole thing, as well as the 
code you were trying.

Best of luck.



-- 
DaveA

From davea at davea.name  Tue Apr 16 22:31:31 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 16 Apr 2013 16:31:31 -0400
Subject: [Tutor] oops - resending as plain text
In-Reply-To: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
References: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
Message-ID: <516DB523.20305@davea.name>

On 04/16/2013 01:48 PM, Jim Mooney wrote:
> I accidentally sent as HTML so this is a resend in case that choked
> the mailing prog ;')
>
> I was doing a simple training prog to figure monetary change, and
> wanted to avoid computer inaccuracy by using only two-decimal input
> and not using division or mod where it would cause error. Yet, on a
> simple subtraction I got a decimal error instead of a two decimal
> result, as per below. What gives?
>
> cost = float(input('How much did the item cost?: '))
> paid = float(input('How much did the customer give you?: '))
> change = paid - cost
>
> #using 22.89 as cost and 248.76 as paid
>
> twenties = int(change / 20)
> if twenties != 0:
>    twentiesAmount = 20 * twenties
>    change = change - twentiesAmount
>    #change is 5.8700000000000045, not 5.87 - how did I get this decimal
> error when simply subtracting an integer from what  should be a
>    #two-decimal amount?


The other responses have been good.  But let me point some things out. 
Binary floating point has been around as long as I've been in computers, 
which was in 1967.  I saw a detailed rant about avoiding errors in 
manipulating floats, in that year.

The fact is that rounding errors can occur in lots of surprising places. 
  For example, if you're using pencil and paper, and you divide 7 by 3, 
you get 2.333333   and at some point you'll stop writing the 3's.  if 
you then multiply by 3, you get  6.99999  not 7.  Now if you're doing it 
by hand, you just adjust it without thinking much.  But a computer is a 
very literal thing, and fudging numbers isn't necessarily a good idea.

In the code above you divided a number by 20, then multiplied by 20 
again.  That's an operation that happens to come out even in decimal, 
because 20 is a factor of 100, the base squared.  But just like 1/3 is a 
problem in a decimal system, so 1/20 is a problem in a binary one.

The chief advantage of decimal is NOT that it's more accurate, but that 
it gets the numbers wrong when YOU expect it, not by some other, more 
subtle rule.  And the second advantage is that there are fewer places 
where the numbers need to be converted, and each conversion might 
produce an error.

It happens that binary floats, as used on Intel hardware, are accurate 
for integers up to a fairly large value.  So some people will represent 
money in pennies, adjusting only when it's time to print.  Others will 
simply use integers (which have no practical size limit on python 3.x) 
for the same purpose.  That's frequently necessary when doing accounting 
or banking, since many transactions are rounded or truncated to the 
nearest penny at each step, according to some standardized rules, rather 
than keeping the numbers more "accurate."

Bottom line, you need to understand enough about what's going on to 
avoid getting burned.

And in case it wasn't obvious, it's not unique to Python.  It's 
potentially  a problem in any environment that doesn't have infinite 
precision.

-- 
DaveA

From amckenzie4 at gmail.com  Tue Apr 16 23:20:01 2013
From: amckenzie4 at gmail.com (Andy McKenzie)
Date: Tue, 16 Apr 2013 17:20:01 -0400
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <516DB208.80006@davea.name>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
	<516DB208.80006@davea.name>
Message-ID: <CAJttDkoFOKp3pJDgojOa2Ncb0DvjUe1GNzo5cBx62+U08FhW+A@mail.gmail.com>

On Tue, Apr 16, 2013 at 4:18 PM, Dave Angel <davea at davea.name> wrote:

> On 04/16/2013 11:58 AM, Andy McKenzie wrote:
>
>> Hey folks.
>>
>> I'm just starting to pick up Python, and I'd like to avoid some of the
>> mistakes I made in the past.  To elaborate on that, my primary
>> programming/scripting experience is PHP, with a little bit of Perl thrown
>> in.  Like so many people who write in PHP, I was entirely self-taught, and
>> would be the first to admit that a lot of what I've written is, well...
>> wrong.  It works, but it's sloppy and inefficient, because there were
>> standard constructions and solutions I just didn't know about.  I'd like
>> to
>> avoid that with Python.
>>
>>
> Welcome to the mailing list.  I expect you'll find Python a much cleaner
> language than the other two, though php has some definite convenience for
> its particular niche.
>
>
>
>
>  So:  my first two questions to the list.
>>
>> 1) Python 2.7 or 3.x?  I know I'm going to want to do some work with NLTK
>> (which appears to only have an alpha version out for Python 3), but I've
>> just gone through the hassle of dealing with an upgrade from PHP 4 to 5.3,
>> and I'd rather not start learning something that's already obsolete.  Any
>> words of advice?
>>
>>
> If you have to use a library that's not available yet for 3.x, then you
> need to use 2.x  on the other hand, if you're learning now, maybe that
> library will be available by the time you actually need it.
>
> For most people, I'd advise against trying to use a tutorial that targets
> a different version than you're running.  If you get frustrated quickly,
> you can get bogged down by the differences when you're just copying an
> exact program out of some book.
>
> Python 3 in particular has spent some substantial effort cleaning up the
> warts, the biggest one being Unicode.  For beginning programmers using only
> ASCII, probably the main thing that'll bog you down is that print() is now
> a function, rather than a statement, so you need parentheses. But once you
> get used to seeing syntax error, you quickly get the hang of it.  And once
> you do, the function is much nicer.
>
>
>
>  2) Best practices.  I have the WROX Press Beginning Python book, which
>> targets Python 2.  Clearly that's of only limited value if I'm going to go
>> with Python 3, but it looks like it's at least going to be a good
>> overview.
>>   But some of the stuff they do seems to be fairly personalized, rather
>> than
>> trying to follow standards.  Should I just start out with the tutorial
>> from
>> docs.python.org?  I would assume that that would start putting me in the
>> right habits from the beginning... is that accurate, or is there a better
>> way to go?
>>
>> Thanks in advance,
>>    Andy McKenzie
>>
>
> I'd start with the python.org tutorial for the version you're trying to
> learn.  Get serious about trying everything, and don't try to absorb it all
> in one sitting, even though it can be done.
>
> And use a text editor that helps you indent, or even that colorizes your
> code.  And when you just want to try things, use the interpreter directly.
>  It's amazing what you can learn directly from it.  You can ask the
> interpreter lots of questions about an object:
>
>    help(obj)
>    dir(obj)
>    print( type(obj) )
>    print( repr(obj) )
>
> And don't forget to post here when you seem to be stuck.  Sometimes a well
> placed comment beats days of struggling.  When you do get an exception you
> don't understand, paste the whole thing, as well as the code you were
> trying.
>
> Best of luck.
>
>
>
>
Thanks for the advice, folks.  Given that it looks like the biggest changes
are unicode handling (which I'm not going to need any time soon) and the
way the print function works, I decided to stick with 2.7.  I'm an IT guy,
though unemployed at the moment, and it occurred to me that "I'm familiar
with Python, but not the version your entire established codebase is in"
wasn't a great thing to have on a resume.

Since it looks like the new formatting for print -- that is, print("Print
this stuff!") -- works fine in 2.7, I'm just getting myself used to doing
that from the beginning.

I went through the first four or five sections of the tutorial this
afternoon, with a few side trips into things that got me interested, and I
figure I'll do at least one more section after dinner.  I did find it
interesting that one of the first things I wanted to know turned out to be
an extremely common question:  "What's the Python equivalent to print_r()
from PHP?"  If any of you are familiar with PHP (I know at least a couple
of you seemed to be), you'll know that pprint() (which seems to be the most
common answer) isn't actually very close.  Its output isn't nearly as
readable.

For instance:  output of running print_r on a very short dictionary from
PHP:

Array
(
    [key3] => thing3
    [key2] => thing2
    [key1] => thing1
)

And running pprint on the same dict in Python:

{'key1': 'thing1', 'key2': 'thing2', 'key3': 'thing3'}


I finally decided that a good project would be building a quick function
that recreates the print_r function, and I got that working.  New function
output, in Python:

(
    [key3] => thing3
    [key2] => thing2
    [key1] => thing1
)


So at least I've figured out enough to do SOMETHING useful, which is
reassuring.

Anyway, thanks again to all of you, and I'm sure I'll be posting soon with
problems.


-Andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130416/f4d16d09/attachment-0001.html>

From davea at davea.name  Tue Apr 16 23:31:41 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 16 Apr 2013 17:31:41 -0400
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <CAJttDkoFOKp3pJDgojOa2Ncb0DvjUe1GNzo5cBx62+U08FhW+A@mail.gmail.com>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
	<516DB208.80006@davea.name>
	<CAJttDkoFOKp3pJDgojOa2Ncb0DvjUe1GNzo5cBx62+U08FhW+A@mail.gmail.com>
Message-ID: <516DC33D.1050304@davea.name>

On 04/16/2013 05:20 PM, Andy McKenzie wrote:
>
>
     <SNIP>
>>
>>
> Thanks for the advice, folks.  Given that it looks like the biggest changes
> are unicode handling (which I'm not going to need any time soon) and the
> way the print function works, I decided to stick with 2.7.  I'm an IT guy,
> though unemployed at the moment, and it occurred to me that "I'm familiar
> with Python, but not the version your entire established codebase is in"
> wasn't a great thing to have on a resume.
>
> Since it looks like the new formatting for print -- that is, print("Print
> this stuff!") -- works fine in 2.7, I'm just getting myself used to doing
> that from the beginning.
>

The degenerate print, where you're printing exactly one thing, works the 
same.  But if you have two things to print, putting parens around them 
in Python 2.x will cause a tuple to be printed, rather than printing the 
two with a space between.

 >>> print(3,5)      -- version 2.x
(3, 5)

 >>> print(3,5)      -- version 3.x
3 5

To get 3.x functionality, you'd want to use
     from __future__ import print_function

and I do not think that works in 2.6 or older versions.  It also can be 
awkward even in 2.7 if you're mixing existing code with new print functions.



-- 
DaveA

From amckenzie4 at gmail.com  Tue Apr 16 23:47:23 2013
From: amckenzie4 at gmail.com (Andy McKenzie)
Date: Tue, 16 Apr 2013 17:47:23 -0400
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <516DC33D.1050304@davea.name>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
	<516DB208.80006@davea.name>
	<CAJttDkoFOKp3pJDgojOa2Ncb0DvjUe1GNzo5cBx62+U08FhW+A@mail.gmail.com>
	<516DC33D.1050304@davea.name>
Message-ID: <CAJttDkp9V==rR++7CDKar+4icb1Z+VeO8cBS+mrtWkemkZsTrg@mail.gmail.com>

On Tue, Apr 16, 2013 at 5:31 PM, Dave Angel <davea at davea.name> wrote:

> On 04/16/2013 05:20 PM, Andy McKenzie wrote:
>
>>
>>
>>      <SNIP>
>
>
>>>
>>>  Thanks for the advice, folks.  Given that it looks like the biggest
>> changes
>> are unicode handling (which I'm not going to need any time soon) and the
>> way the print function works, I decided to stick with 2.7.  I'm an IT guy,
>> though unemployed at the moment, and it occurred to me that "I'm familiar
>> with Python, but not the version your entire established codebase is in"
>> wasn't a great thing to have on a resume.
>>
>> Since it looks like the new formatting for print -- that is, print("Print
>> this stuff!") -- works fine in 2.7, I'm just getting myself used to doing
>> that from the beginning.
>>
>>
> The degenerate print, where you're printing exactly one thing, works the
> same.  But if you have two things to print, putting parens around them in
> Python 2.x will cause a tuple to be printed, rather than printing the two
> with a space between.
>
> >>> print(3,5)      -- version 2.x
> (3, 5)
>
> >>> print(3,5)      -- version 3.x
> 3 5
>
> To get 3.x functionality, you'd want to use
>     from __future__ import print_function
>
> and I do not think that works in 2.6 or older versions.  It also can be
> awkward even in 2.7 if you're mixing existing code with new print functions.
>
>
That's good to know, since I hadn't run into it yet.

So am I correct in understanding that I can just put the from __future__
import print_function in each new 2.7 script, and get identical
functionality to what happens in 3.x?  Or do I need to do that system-wide
somehow?

-Andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130416/62b56fae/attachment.html>

From cybervigilante at gmail.com  Tue Apr 16 23:49:31 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 16 Apr 2013 14:49:31 -0700
Subject: [Tutor] Tutor Digest, Vol 110, Issue 69
In-Reply-To: <mailman.3684.1366147204.3113.tutor@python.org>
References: <mailman.3684.1366147204.3113.tutor@python.org>
Message-ID: <CALRAYNUrK1a1rLz4B17=v+KZUc=rzTn5JXvzN0L8778rNDv=JQ@mail.gmail.com>

> Now that Joel Goldstick has pointed out the reason, you may wonder what to do now. Answer? Use the decimal module:
>
> http://docs.python.org/2/library/decimal.html
>
> Although, you might prefer Doug Hellmann's introduction:
>
> http://pymotw.com/2/decimal/

Thanks. I was about to ask that but you beat me to it. I'll try
Hellmann. The manual is just a tad wordy and it's hard to find what
you want.

Jim
>

From cybervigilante at gmail.com  Tue Apr 16 23:46:44 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 16 Apr 2013 14:46:44 -0700
Subject: [Tutor] oops - resending as plain text
In-Reply-To: <516D9E95.2050203@gmail.com>
References: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
	<516D9E95.2050203@gmail.com>
Message-ID: <CALRAYNXtY385knusB_zE9a08qq6XTgUfPEhsUXJ79wABN+_ukA@mail.gmail.com>

Further question. If I round the input right at the beginning,
round(paid,2) does that mean  I still have the original error from
using .76 even before math, or does the rounding kill it? I would
guess not if it's binary, although Python must have a way to handle
money amounts. I'm only on Chapter 2 ;')

I assume Python has some automatic way to filter input, so that if
someone entered three decimals instead of two for a money amount, they
could get a wrist slap. Can you direct me to that functionality?
Thanks.

Jim

On 16 April 2013 11:55, Sander Sweers <sander.sweers at gmail.com> wrote:
> On 04/16/2013 07:48 PM, Jim Mooney wrote:
>> I accidentally sent as HTML so this is a resend in case that choked
>> the mailing prog ;')
>>
>> I was doing a simple training prog to figure monetary change, and
>> wanted to avoid computer inaccuracy by using only two-decimal input
>> and not using division or mod where it would cause error. Yet, on a
>> simple subtraction I got a decimal error instead of a two decimal
>> result, as per below. What gives?
>
> Floats can not be represented accurately in binary and will have small
> rounding errors. See
> https://en.wikipedia.org/wiki/Floating_point#Accuracy_problems.
>
>> cost = float(input('How much did the item cost?: '))
>> paid = float(input('How much did the customer give you?: '))
>> change = paid - cost
>>
>> #using 22.89 as cost and 248.76 as paid
>>
>> twenties = int(change / 20)
>> if twenties != 0:
>>   twentiesAmount = 20 * twenties
>>   change = change - twentiesAmount
>>   #change is 5.8700000000000045, not 5.87 - how did I get this decimal
>> error when simply subtracting an integer from what  should be a
>>   #two-decimal amount?
>>   print(twenties, ' twenties')
>>   print(change)
>>
>> #and so forth for the rest of the prog
>
> You can use string formatting to show as much precision you want. Example:
>
>>>> n = 5.8700000000000045
>>>> print '%.2f' % n
> 5.87
>>>> print '%.4f' % n
> 5.8700
>
> Or use round(), example:
>
>>>> round(n,2)
> 5.87
>
> In your case I would just use string formatting to hide the rounding error.
>
> Greets
> ~sander



-- 
Jim Mooney

If you shoot a child you're a bad guy. If you splatter forty children
across a wall with a bomb, you're a heroic, manly Top Gun with
gleaming Tom Cruise teeth. The moral is you'll get laid more if you
snuff a lot of children than if you only snuff a few.

From davea at davea.name  Wed Apr 17 00:09:47 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 16 Apr 2013 18:09:47 -0400
Subject: [Tutor] oops - resending as plain text
In-Reply-To: <CALRAYNXtY385knusB_zE9a08qq6XTgUfPEhsUXJ79wABN+_ukA@mail.gmail.com>
References: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
	<516D9E95.2050203@gmail.com>
	<CALRAYNXtY385knusB_zE9a08qq6XTgUfPEhsUXJ79wABN+_ukA@mail.gmail.com>
Message-ID: <516DCC2B.7070607@davea.name>

On 04/16/2013 05:46 PM, Jim Mooney wrote:
> Further question. If I round the input right at the beginning,
> round(paid,2) does that mean  I still have the original error from
> using .76 even before math, or does the rounding kill it? I would
> guess not if it's binary,

You guess right.  round() function is only theoretical, when applied to 
floats.  It can be useful when combined with formatting, as suggested 
elsewhere in the thread.  But even if .76 prints out "correctly," you 
have no assurance that adding two such apparently-exact figures will 
give one that will also print out easily.

> although Python must have a way to handle
> money amounts. I'm only on Chapter 2 ;')
>
> I assume Python has some automatic way to filter input, so that if
> someone entered three decimals instead of two for a money amount, they
> could get a wrist slap. Can you direct me to that functionality?
> Thanks.
>

There's no "money type" in Python, and if you want your user to get 
slapped, you have to write your own.  Normally, you take input in the 
form of text, validate it, then convert to int, float, Decimal, or 
whatever.  If the conversion itself will catch the errors, then you can 
just use try/catch to make such errors more polite to your users. 
That's the case if they enter  "charlie" when you're asking for a salary 
value.  But if they were to put  7.500 when the value is supposed to be 
in dollars and cents, then by the time it's turned into a float or 
decimal, the extra zero is long gone.

-- 
DaveA

From davea at davea.name  Wed Apr 17 00:17:21 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 16 Apr 2013 18:17:21 -0400
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <CAJttDkp9V==rR++7CDKar+4icb1Z+VeO8cBS+mrtWkemkZsTrg@mail.gmail.com>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
	<516DB208.80006@davea.name>
	<CAJttDkoFOKp3pJDgojOa2Ncb0DvjUe1GNzo5cBx62+U08FhW+A@mail.gmail.com>
	<516DC33D.1050304@davea.name>
	<CAJttDkp9V==rR++7CDKar+4icb1Z+VeO8cBS+mrtWkemkZsTrg@mail.gmail.com>
Message-ID: <516DCDF1.6040306@davea.name>

On 04/16/2013 05:47 PM, Andy McKenzie wrote:
> On Tue, Apr 16, 2013 at 5:31 PM, Dave Angel <davea at davea.name> wrote:
>
>>     <SNIP>
>>
>> To get 3.x functionality, you'd want to use
>>      from __future__ import print_function
>>
>> and I do not think that works in 2.6 or older versions.  It also can be
>> awkward even in 2.7 if you're mixing existing code with new print functions.
>>
>>
> That's good to know, since I hadn't run into it yet.
>
> So am I correct in understanding that I can just put the from __future__
> import print_function in each new 2.7 script, and get identical
> functionality to what happens in 3.x?  Or do I need to do that system-wide
> somehow?
>

Someone else may know if "identical" has some exceptions.  But as for 
where to put it, you'd need it for any module (including your own 
script) which is going to use the newer print() function.

And the nice thing is that the from-future directive is ignored in 3.x, 
so you don't have to remove it when you do progress.

-- 
DaveA

From hugo.yoshi at gmail.com  Wed Apr 17 00:10:57 2013
From: hugo.yoshi at gmail.com (Hugo Arts)
Date: Wed, 17 Apr 2013 00:10:57 +0200
Subject: [Tutor] How did this decimal error pop up?
In-Reply-To: <CALRAYNXM8=1Ys8ug9xpFw0JkvSA8Bgx9HDPe0PJTK+wELqNfMw@mail.gmail.com>
References: <CALRAYNXM8=1Ys8ug9xpFw0JkvSA8Bgx9HDPe0PJTK+wELqNfMw@mail.gmail.com>
Message-ID: <CAJmBOfmNmJshyb55LAtPwcQT0EODFdi4DZ2UrXXQvb26Z00GNA@mail.gmail.com>

On Tue, Apr 16, 2013 at 7:43 PM, Jim Mooney <cybervigilante at gmail.com>wrote:

> I was doing a simple training prog to figure change, and wanted to avoid
> computer inaccuracy by using only two-decimal input and not using division
> or mod where it would cause error. Yet, on a simple subtraction I got a
> decimal error instead of a two decimal result, as per below. What gives?
>
>
Your assumption that using only two-decimal input and no division/modulo
would avoid computer inaccuracy is wrong. In fact, for some values floating
point numbers don't even have 1 decimal accuracy (all examples done in
python 2.7.3):

 >>> 0.1 + 0.2
0.30000000000000004

This is a limitation of the way floating point numbers are represented in
hardware (some python versions may actually print 0.3 here, but the number
stored in memory is *not* 0.3. It can't be). floating point accuracy isn't
as simple as "accurate to 5 decimal places, always." Some numbers simply
*can not* be represented as a floating point value. A simple example of
this is the number 0.1, it has no exact floating point representation. Note
that python appears to have no problem storing the value 0.1:

>>> a = 0.1
>>> a
0.1

But this is just because python actually rounds numbers when it is
displaying them. We can show that there are still errors by adding the
errors up to make them visible:

>>> i = 0
>>> for _ in range(1000):
i += 0.1

 >>> i
99.9999999999986

That should, by all the laws of math, be 100. But it isn't. Because the
computer can't store 0.1 in a float, so it stores the closest possible
number it can instead. The value stored in a above is not actually 0.1,
it's closer to:

0.1000000000000000055511151231257827021181583404541015625

The precise value kind of depends on what hardware you have, but it can
*never* be 0.1 exactly. The format that floating point numbers are stored
in simply cannot represent the value 0.1. The reason for this is kind of
complicated, it has to do with how the number is stored in hardware. A good
analogy for base 10 is the number 1/3. To write that number down in a
decimal notation you'd need an infinite amount of space: 0.3333333..... and
so on. In floating point, 0.1, along with a ton of other numbers, are the
same way: you'd need an infinite amount of space to store them.

To store decimals with perfect accuracy, you have 2 options. The most basic
is what is generally called "fixed point" arithmetic. You decide beforehand
on the amount of accuracy you would like to have, say 2 decimals. Then you
simply multiply all numbers by 10^decimals_of_accuracy (in this case, 100)
and store them in a regular int. So 10.43 would become 1043. Then when
you're displaying a number, just put the decimal point back in. This is
pretty simple, gives you perfect (though fixed) accuracy, but it's also
kind of tedious.

The other option, and probably the simplest to use, is python's built in
decimal module, which provides a special class that implements perfectly
accurate decimal calculations. Why don't we use it for all applications,
you might ask? Well, it is extremely slow when compared to floats, and
usually float accuracy is good enough for people that they don't care about
the inaccuracies. Only packages that absolutely need accuracy use decimal,
like accounting software.

The documentation for the decimal module is here:
http://docs.python.org/2/library/decimal.html
everything a computer scientist should know about floating point is here:
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

HTH,
Hugo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130417/2ec71e9a/attachment.html>

From eryksun at gmail.com  Wed Apr 17 00:45:41 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 16 Apr 2013 18:45:41 -0400
Subject: [Tutor] oops - resending as plain text
In-Reply-To: <516DCC2B.7070607@davea.name>
References: <CALRAYNUbUs-N3_W880W9VGzumpN7w7N8YjANKiF1gBi_CZASOQ@mail.gmail.com>
	<516D9E95.2050203@gmail.com>
	<CALRAYNXtY385knusB_zE9a08qq6XTgUfPEhsUXJ79wABN+_ukA@mail.gmail.com>
	<516DCC2B.7070607@davea.name>
Message-ID: <CACL+1auc8OjMMqBgJmckaJTyaLaWsUHd=U4W5ZCeeFenfaW3xg@mail.gmail.com>

On Tue, Apr 16, 2013 at 6:09 PM, Dave Angel <davea at davea.name> wrote:
> If the conversion itself will catch the errors, then you can just use
> try/catch to make such errors more polite to your users. That's the case if
> they enter  "charlie" when you're asking for a salary value.  But if they
> were to put  7.500 when the value is supposed to be in dollars and cents,
> then by the time it's turned into a float or decimal, the extra zero is long
> gone.

With Decimal it's not really 'long gone'. It affects the number of
significant digits retained in arithmetic operations:

    >>> from decimal import Decimal
    >>> context = decimal.getcontext()

    >>> Decimal('7.500') + Decimal('0.50')
    Decimal('8.000')

You could look specifically at the _exp attribute, or quantize with a
trap for inexact rounding:

    >>> Decimal('7.500')._exp
    -3

    def round_money(value):
        with decimal.localcontext() as ctx:
            ctx.traps[decimal.Inexact] = 1
            return Decimal(value).quantize(Decimal('1.00'))

    >>> try: round_money('7.500')
    ... except decimal.Inexact: print 'ack!'
    ...
    Decimal('7.50')

    >>> try: round_money('7.501')
    ... except decimal.Inexact: print 'ack!'
    ...
    ack!

    >>> try: round_money('charlie')
    ... except decimal.InvalidOperation as e: print 'ack!'
    ...
    ack!

Please don't print a useless error message like 'ack'; it was just a
silly example. Handle the error within the logical context of your
application.

From davea at davea.name  Wed Apr 17 01:02:45 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 16 Apr 2013 19:02:45 -0400
Subject: [Tutor] How did this decimal error pop up?
In-Reply-To: <CAJmBOfmNmJshyb55LAtPwcQT0EODFdi4DZ2UrXXQvb26Z00GNA@mail.gmail.com>
References: <CALRAYNXM8=1Ys8ug9xpFw0JkvSA8Bgx9HDPe0PJTK+wELqNfMw@mail.gmail.com>
	<CAJmBOfmNmJshyb55LAtPwcQT0EODFdi4DZ2UrXXQvb26Z00GNA@mail.gmail.com>
Message-ID: <516DD895.3060806@davea.name>

On 04/16/2013 06:10 PM, Hugo Arts wrote:
>
>    <SNIP>
> The other option, and probably the simplest to use, is python's built in
> decimal module, which provides a special class that implements perfectly
> accurate decimal calculations. Why don't we use it for all applications,
> you might ask? Well, it is extremely slow when compared to floats, and

I've been told (here) that starting with about Python 3.3, the decimal 
package is nearly as fast as float, for typical use.  The underlying 
processor logic is much slower, but it gets swamped by Python's overhead 
manipulating objects and searching dicts.

By nearly as fast, I'm thinking like 30%, rather than the previous 
1000%.  Or some such.

-- 
DaveA

From eryksun at gmail.com  Wed Apr 17 01:06:48 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 16 Apr 2013 19:06:48 -0400
Subject: [Tutor] How did this decimal error pop up?
In-Reply-To: <CAJmBOfmNmJshyb55LAtPwcQT0EODFdi4DZ2UrXXQvb26Z00GNA@mail.gmail.com>
References: <CALRAYNXM8=1Ys8ug9xpFw0JkvSA8Bgx9HDPe0PJTK+wELqNfMw@mail.gmail.com>
	<CAJmBOfmNmJshyb55LAtPwcQT0EODFdi4DZ2UrXXQvb26Z00GNA@mail.gmail.com>
Message-ID: <CACL+1auBWawGpjZwX_0H7MMajyjPi4_q6bS47apq3R72mASXeQ@mail.gmail.com>

On Tue, Apr 16, 2013 at 6:10 PM, Hugo Arts <hugo.yoshi at gmail.com> wrote:
>>>> i = 0
>>>> for _ in range(1000):
> i += 0.1
>
>>>> i
> 99.9999999999986
>
> That should, by all the laws of math, be 100. But it isn't. Because the
> computer can't store 0.1 in a float, so it stores the closest possible
> number it can instead. The value stored in a above is not actually 0.1, it's
> closer to:
>
> 0.1000000000000000055511151231257827021181583404541015625

Now you have to explain how the summation ends up as less than 100. ;)
 That really gets to the heart of error introduced by intermediate
rounding with fixed-precision arithmetic. This is a more important
point than the fact that 0.1 doesn't have an exact representation in
binary floating point. Python's floats are limited to hardware
precision, which is 53 bits or floor(53*log10(2)) == 15 decimal
digits. There's no option to extend the precision arbitrarily as is
possible with the Decimal type.

BTW, did you know Decimal got a C implementation in 3.3? It's a lot
faster than the pure Python implementation in previous versions, but
still not as fast as hardware floats.

From alan.gauld at btinternet.com  Wed Apr 17 01:39:14 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 17 Apr 2013 00:39:14 +0100
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <CAJttDkoFOKp3pJDgojOa2Ncb0DvjUe1GNzo5cBx62+U08FhW+A@mail.gmail.com>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
	<516DB208.80006@davea.name>
	<CAJttDkoFOKp3pJDgojOa2Ncb0DvjUe1GNzo5cBx62+U08FhW+A@mail.gmail.com>
Message-ID: <kkkneu$2ft$1@ger.gmane.org>

On 16/04/13 22:20, Andy McKenzie wrote:

> For instance:  output of running print_r on a very short dictionary from
> PHP:
>
> Array
> (
>      [key3] => thing3
>      [key2] => thing2
>      [key1] => thing1
> )
>
> And running pprint on the same dict in Python:
>
> {'key1': 'thing1', 'key2': 'thing2', 'key3': 'thing3'}
>
>
> I finally decided that a good project would be building a quick function
> that recreates the print_r function, and I got that working.  New
> function output, in Python:
>
> (
>      [key3] => thing3
>      [key2] => thing2
>      [key1] => thing1
> )


You should probably use {} instead of () as the delimiter to indicate 
that the thing is a dictionary and not a tuple. but otherwise that's a 
good starter project.


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


From eryksun at gmail.com  Wed Apr 17 01:39:03 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 16 Apr 2013 19:39:03 -0400
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <516DCDF1.6040306@davea.name>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
	<516DB208.80006@davea.name>
	<CAJttDkoFOKp3pJDgojOa2Ncb0DvjUe1GNzo5cBx62+U08FhW+A@mail.gmail.com>
	<516DC33D.1050304@davea.name>
	<CAJttDkp9V==rR++7CDKar+4icb1Z+VeO8cBS+mrtWkemkZsTrg@mail.gmail.com>
	<516DCDF1.6040306@davea.name>
Message-ID: <CACL+1asL5ayVy3xk7AOsM89e7bFOTArg1tAMRc9+d_Xmpx74mg@mail.gmail.com>

On Tue, Apr 16, 2013 at 6:17 PM, Dave Angel <davea at davea.name> wrote:
> Someone else may know if "identical" has some exceptions.  But as for where
> to put it, you'd need it for any module (including your own script) which is
> going to use the newer print() function.

I think any differences will result from the I/O system redesign in
3.x. In 2.x sys.stdout is still the old "file" type, which is
basically a wrapper around CRT FILE streams, while in 3.x it's a
TextIOWrapper wrapping a BufferedWriter wrapping a FileIO object.

Off the top of my head I don't have a clear example where it matters.
I vaguely recall having an issue with the default buffer flushing not
being the same. I think I was simulating scrolling text by printing a
carriage return ('\r') to overwrite a line. IRRC, in the end I opted
to directly use sys.stdout.write() and sys.stdout.flush().

Since __future__ imports are compiler directive, you have to include
them at the top of every module. "print_function" works in 2.6+. If
you just want the function under a different name, you can grab it
from the __builtin__ module:

    >>> import __builtin__
    >>> printf = getattr(__builtin__, 'print')
    >>> printf('spam')
    spam

From amckenzie4 at gmail.com  Wed Apr 17 01:46:06 2013
From: amckenzie4 at gmail.com (Andy McKenzie)
Date: Tue, 16 Apr 2013 19:46:06 -0400
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <kkkneu$2ft$1@ger.gmane.org>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
	<516DB208.80006@davea.name>
	<CAJttDkoFOKp3pJDgojOa2Ncb0DvjUe1GNzo5cBx62+U08FhW+A@mail.gmail.com>
	<kkkneu$2ft$1@ger.gmane.org>
Message-ID: <CAJttDkpHp_4o3uUG2vuCec5eCCs17AmX2qb4GQ2Qdcf3CrAHxA@mail.gmail.com>

On Tue, Apr 16, 2013 at 7:39 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> On 16/04/13 22:20, Andy McKenzie wrote:
>
>  For instance:  output of running print_r on a very short dictionary from
>> PHP:
>>
>> Array
>> (
>>      [key3] => thing3
>>      [key2] => thing2
>>      [key1] => thing1
>> )
>>
>> And running pprint on the same dict in Python:
>>
>> {'key1': 'thing1', 'key2': 'thing2', 'key3': 'thing3'}
>>
>>
>> I finally decided that a good project would be building a quick function
>> that recreates the print_r function, and I got that working.  New
>> function output, in Python:
>>
>> (
>>      [key3] => thing3
>>      [key2] => thing2
>>      [key1] => thing1
>> )
>>
>
>
> You should probably use {} instead of () as the delimiter to indicate that
> the thing is a dictionary and not a tuple. but otherwise that's a good
> starter project.
>
>
Good idea.  I went with () because I was just trying to duplicate the
output in PHP.  Now that I've got that, I can start thinking about
improvements.  Varying the punctuation to match the type would probably be
a good idea.

Thanks,
  Andy
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130416/fe0b3d2d/attachment.html>

From steve at pearwood.info  Wed Apr 17 02:11:03 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 17 Apr 2013 10:11:03 +1000
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
References: <CAJttDkqNu6fkso_uGPUWBuP2NJts5_4KJW-KsuXazC7Tw8jnxw@mail.gmail.com>
Message-ID: <516DE897.8070404@pearwood.info>

On 17/04/13 01:58, Andy McKenzie wrote:

> 1) Python 2.7 or 3.x?  I know I'm going to want to do some work with NLTK
> (which appears to only have an alpha version out for Python 3), but I've
> just gone through the hassle of dealing with an upgrade from PHP 4 to 5.3,
> and I'd rather not start learning something that's already obsolete.  Any
> words of advice?

Python 3.3 is awesome and much cleaner and better than 2.7, and 2.7 is
pretty damn good! So if you have a choice, pick 3.3. It's the future of
Python, 2.7 is the past.

But, 2.7 is still good, and if you need NLTK *right now* you might not have
a choice. (Unless you like being a guinea pig working with an alpha version.)

Also, the *incompatibilities* between 2.7 and 3.3 are fairly small. The
biggest difference from a beginner's perspective is that print is no longer
a statement, it is a function, so instead of writing this:

print "Hello world!"

you have to write this:

print("Hello world!")

That doesn't seem too onerous, does it? If you can cope with a few differences
of that complexity, why not learn both?


> 2) Best practices.  I have the WROX Press Beginning Python book, which
> targets Python 2.  Clearly that's of only limited value if I'm going to go
> with Python 3, but it looks like it's at least going to be a good overview.
>   But some of the stuff they do seems to be fairly personalized, rather than
> trying to follow standards.  Should I just start out with the tutorial from
> docs.python.org?  I would assume that that would start putting me in the
> right habits from the beginning... is that accurate, or is there a better
> way to go?

If there's a Python 3 version of "Learning Python", from O'Reilly Books (sorry
I forget the authors), give it a go. The first edition, at least, is an awesome
book although you will want a more recent version since the first edition
deals with Python 1.5, which truly is ancient history!

I haven't done the official Python tutorial, but from what I've seen of it,
it's pretty good.



-- 
Steven

From eryksun at gmail.com  Wed Apr 17 02:15:07 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 16 Apr 2013 20:15:07 -0400
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <1366156656384.bcbb86a8@Nodemailer>
References: <CACL+1asL5ayVy3xk7AOsM89e7bFOTArg1tAMRc9+d_Xmpx74mg@mail.gmail.com>
	<1366156656384.bcbb86a8@Nodemailer>
Message-ID: <CACL+1asWjAQ4sgV5R9hF_TAJVeGitqWsG3Sw_unS7mjCAjRzfA@mail.gmail.com>

On Tue, Apr 16, 2013 at 7:57 PM, Virgilio Rodriguez Jr
<virgiliorodriguezjr at gmail.com> wrote:
> Can someone please do me the favor and remove me from this god forsaken
> email list I am sorry I signed up all it has done is taken over my phone and
> rings all night long with emails I am not interested in any more because it
> is just too many darn emails. I keep trying to log in and nothing it will
> not let me unsubscribe and it is BS already.

You can get a password reminder here:
http://mail.python.org/mailman/options/tutor

If you're sure that you have the correct password and still can't
unsubscribe, then email the administrator, tutor-owner at python.org.
Alan Gauld is active in this thread, BTW, in case you happen to have
read the admin page where it says "Tutor list run by wescpy at
gmail.com, alan.gauld at btinternet.com".

From eryksun at gmail.com  Wed Apr 17 02:34:24 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 16 Apr 2013 20:34:24 -0400
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <CACL+1asWjAQ4sgV5R9hF_TAJVeGitqWsG3Sw_unS7mjCAjRzfA@mail.gmail.com>
References: <CACL+1asL5ayVy3xk7AOsM89e7bFOTArg1tAMRc9+d_Xmpx74mg@mail.gmail.com>
	<1366156656384.bcbb86a8@Nodemailer>
	<CACL+1asWjAQ4sgV5R9hF_TAJVeGitqWsG3Sw_unS7mjCAjRzfA@mail.gmail.com>
Message-ID: <CACL+1avcGu4vR2xtmc5ETdsZkRJkwx-Cs4TMvKkB9opDfpAozQ@mail.gmail.com>

On Tue, Apr 16, 2013 at 8:15 PM, eryksun <eryksun at gmail.com> wrote:
>> Can someone please do me the favor and remove me from this god forsaken
>> email list I am sorry I signed up all it has done is taken over my phone and
>> rings all night long with emails I am not interested in any more because it
>> is just too many darn emails. I keep trying to log in and nothing it will
>> not let me unsubscribe and it is BS already.
>
> You can get a password reminder here:
> http://mail.python.org/mailman/options/tutor
>
> If you're sure that you have the correct password and still can't
> unsubscribe, then email the administrator, tutor-owner at python.org.
> Alan Gauld is active in this thread, BTW, in case you happen to have
> read the admin page where it says "Tutor list run by wescpy at
> gmail.com, alan.gauld at btinternet.com".

I just went through the steps. You don't even need your password.
Enter your email address in the bottom field of the list info page:

http://mail.python.org/mailman/listinfo/tutor

Click the button that says "Unsubscribe or edit options". Then simply
click the "Unsubscribe" button in the middle of the options page.
You'll get a confirmation email with instructions to complete the
process.

From sander.sweers at gmail.com  Wed Apr 17 02:44:32 2013
From: sander.sweers at gmail.com (Sander Sweers)
Date: Wed, 17 Apr 2013 02:44:32 +0200
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <CACL+1avcGu4vR2xtmc5ETdsZkRJkwx-Cs4TMvKkB9opDfpAozQ@mail.gmail.com>
References: <CACL+1asL5ayVy3xk7AOsM89e7bFOTArg1tAMRc9+d_Xmpx74mg@mail.gmail.com>
	<1366156656384.bcbb86a8@Nodemailer>
	<CACL+1asWjAQ4sgV5R9hF_TAJVeGitqWsG3Sw_unS7mjCAjRzfA@mail.gmail.com>
	<CACL+1avcGu4vR2xtmc5ETdsZkRJkwx-Cs4TMvKkB9opDfpAozQ@mail.gmail.com>
Message-ID: <516DF070.4080301@gmail.com>

On 04/17/2013 02:34 AM, eryksun wrote:
> I just went through the steps. You don't even need your password.
> Enter your email address in the bottom field of the list info page:
> 
> http://mail.python.org/mailman/listinfo/tutor
> 
> Click the button that says "Unsubscribe or edit options". Then simply
> click the "Unsubscribe" button in the middle of the options page.
> You'll get a confirmation email with instructions to complete the
> process.

Or send an e-mail to tutor-request at python.org with unsubscribe in the
subject.

~sander

From cybervigilante at gmail.com  Wed Apr 17 03:02:26 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 16 Apr 2013 18:02:26 -0700
Subject: [Tutor] regex to promote Py 2 to Py 3?
Message-ID: <CALRAYNWOGJJmzqW5Y2wQWBtgzqJeJFMsdNrk-wU3afVZeZ5E3w@mail.gmail.com>

I already tried an example I copied from something online, in Py 2,
that had a ton of print statements. So I did some fast search and
replace to make them Py 3 with (), since I'm using Py 3. (Except Wing
101 won't do Replace All for some reason I haven't figured out, so
it's a bit tedious)

So for online progs, examples, ebooks, etc, that still have Py 2
examples I can copy, has anyone come up with a nice regex package to
do most of the conversions and produce a mostly Py3 from a Py2? That
might make some things a bit easier. I use Clipmate, which has a regex
option so I could just copy a Py2 script, run the regex, and paste
back a Py3. I could probably work one out but since I don't know Py
yet, that could be problematic ;')

Jim

From michael.weylandt at gmail.com  Wed Apr 17 03:35:48 2013
From: michael.weylandt at gmail.com (Michael Weylandt)
Date: Tue, 16 Apr 2013 21:35:48 -0400
Subject: [Tutor] regex to promote Py 2 to Py 3?
In-Reply-To: <CALRAYNWOGJJmzqW5Y2wQWBtgzqJeJFMsdNrk-wU3afVZeZ5E3w@mail.gmail.com>
References: <CALRAYNWOGJJmzqW5Y2wQWBtgzqJeJFMsdNrk-wU3afVZeZ5E3w@mail.gmail.com>
Message-ID: <DE79ABBC-6DA8-405A-B1FA-B41006991864@gmail.com>



On Apr 16, 2013, at 21:02, Jim Mooney <cybervigilante at gmail.com> wrote:

> I already tried an example I copied from something online, in Py 2,
> that had a ton of print statements. So I did some fast search and
> replace to make them Py 3 with (), since I'm using Py 3. (Except Wing
> 101 won't do Replace All for some reason I haven't figured out, so
> it's a bit tedious)
> 
> So for online progs, examples, ebooks, etc, that still have Py 2
> examples I can copy, has anyone come up with a nice regex package to
> do most of the conversions and produce a mostly Py3 from a Py2? That
> might make some things a bit easier. I use Clipmate, which has a regex
> option so I could just copy a Py2 script, run the regex, and paste
> back a Py3. I could probably work one out but since I don't know Py
> yet, that could be problematic ;')

Much ink has been spilled on just such a translation, but you may as well start with the 2to3 script and see if that suffices for your needs:

http://docs.python.org/2/library/2to3.html


Michael

> 
> Jim
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130416/6f0c1241/attachment.html>

From eryksun at gmail.com  Wed Apr 17 04:24:08 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 16 Apr 2013 22:24:08 -0400
Subject: [Tutor] regex to promote Py 2 to Py 3?
In-Reply-To: <CALRAYNWOGJJmzqW5Y2wQWBtgzqJeJFMsdNrk-wU3afVZeZ5E3w@mail.gmail.com>
References: <CALRAYNWOGJJmzqW5Y2wQWBtgzqJeJFMsdNrk-wU3afVZeZ5E3w@mail.gmail.com>
Message-ID: <CACL+1avys_3nh+EfhHNPSapQXaYux5nJpm6SMDtXc_HSXJREPQ@mail.gmail.com>

On Tue, Apr 16, 2013 at 9:02 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> So for online progs, examples, ebooks, etc, that still have Py 2
> examples I can copy, has anyone come up with a nice regex package to
> do most of the conversions and produce a mostly Py3 from a Py2? That
> might make some things a bit easier.

Generally the 2to3 script does an OK job. If you're using Windows it's
[Python_Dir]\Tools\Scripts\2to3.py.

http://docs.python.org/3/library/2to3

lib2to3 doesn't have a stable API, but you can use it in the REPL if
you want to experiment:

    >>> from lib2to3.refactor import RefactoringTool
    >>> rt = RefactoringTool(['lib2to3.fixes.fix_print'])

    >>> code2 = r'''
    ... for s in strings:
    ...     print >>myfile, s,
    ... '''

    >>> code3 = str(rt.refactor_string(code2, '<string>'))
    >>> print(code3)

    for s in strings:
        print(s, end=' ', file=myfile)

If you want all the fixes applied, you can use

    >>> from lib2to3.refactor import (
    ...   RefactoringTool, get_fixers_from_package)

    >>> rt = RefactoringTool(get_fixers_from_package('lib2to3.fixes'))

    >>> code2 = r'''
    ... class Test(object):
    ...     __metaclass__ = MetaTest
    ... '''
    >>> code3 = str(r.refactor_string(code2, '<string>'))
    >>> print(code3)

    class Test(object, metaclass=MetaTest):
        pass

From jslozier at gmail.com  Wed Apr 17 03:49:03 2013
From: jslozier at gmail.com (Jay Lozier)
Date: Tue, 16 Apr 2013 21:49:03 -0400
Subject: [Tutor] How did this decimal error pop up?
In-Reply-To: <CALRAYNXM8=1Ys8ug9xpFw0JkvSA8Bgx9HDPe0PJTK+wELqNfMw@mail.gmail.com>
References: <CALRAYNXM8=1Ys8ug9xpFw0JkvSA8Bgx9HDPe0PJTK+wELqNfMw@mail.gmail.com>
Message-ID: <516DFF8F.5020106@gmail.com>

On 04/16/2013 01:43 PM, Jim Mooney wrote:
> I was doing a simple training prog to figure change, and wanted to 
> avoid computer inaccuracy by using only two-decimal input and not 
> using division or mod where it would cause error. Yet, on a simple 
> subtraction I got a decimal error instead of a two decimal result, as 
> per below. What gives?
>
> cost = float(input('How much did the item cost?: '))
> paid = float(input('How much did the customer give you?: '))
> change = paid - cost
>
> *#using 22.89 as cost and 248.76 as paid*
>
> twenties = int(change / 20)
> if twenties != 0:
>   twentiesAmount = 20 * twenties
>   change = change - twentiesAmount
> *#change is 5.8700000000000045, not 5.87 - how did I get this decimal 
> error when simply subtracting an integer from what should be a
>   #two-decimal amount?
> *  print(twenties, ' twenties')
>   print(change)
>
> #and so forth for the rest of the change
>
> -- 
> *Jim Mooney
> * 
This is a common problem with decimal numbers that is discussed in 
various numerical methods texts and is independent of the programming 
language. The two numerical texts I have from the 1980's discuss this 
problem using FORTRAN and Pascal ( I am fairly certain they are out of 
print). It caused by binary representation of decimal numbers at times 
will introduce errors in decimal numbers. Many decimal numbers can not 
be exactly represented by a binary number with some binary 
representations being a little higher and some a little lower than the 
actual number. There are recommend algorithms and data encoding 
techniques to use to minimize these problems.

Integers always have an exact binary representation so if it one can 
change the problem to one that uses integers instead of floats then the 
rounding problem disappears. Many financial calculations can be 
converted from dollars to cents to avoid decimals. Unfortunately, many 
science and engineering calculations will need to address the decimal to 
binary to decimal representation errors.

It can be a nasty problem if one does not address it properly an even 
larger error could occur. Often it is suitable error because one does 
not spot that an intermediate calculation is incorrectly implemented.

-- 
Jay Lozier
jslozier at gmail.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130416/568e896d/attachment.html>

From cybervigilante at gmail.com  Wed Apr 17 07:11:33 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Tue, 16 Apr 2013 22:11:33 -0700
Subject: [Tutor] regex to promote Py 2 to Py 3?
In-Reply-To: <CACL+1avys_3nh+EfhHNPSapQXaYux5nJpm6SMDtXc_HSXJREPQ@mail.gmail.com>
References: <CALRAYNWOGJJmzqW5Y2wQWBtgzqJeJFMsdNrk-wU3afVZeZ5E3w@mail.gmail.com>
	<CACL+1avys_3nh+EfhHNPSapQXaYux5nJpm6SMDtXc_HSXJREPQ@mail.gmail.com>
Message-ID: <CALRAYNXRD92j_5ss8TTvS+R-YyEQ7AO=EazGrhE8-CT_eqz7Sw@mail.gmail.com>

> Generally the 2to3 script does an OK job. If you're using Windows it's
> [Python_Dir]\Tools\Scripts\2to3.py.
>
> http://docs.python.org/3/library/2to3
================================

Thanks. I didn't know where to find it and thought I had to install it.

I opened a command window in my Python33/progs dir, started Python,
and ran it on a tiny test program called loops.py but I get "invalid
syntax" Any idea why?:

>>> 2to3 loops.py
  File "<stdin>", line 1
    2to3 loops.py
       ^
SyntaxError: invalid syntax

The loops.py program simply had the old-style print as a single test
statement. ie:

print 'Machiavelli'

Jim

From eryksun at gmail.com  Wed Apr 17 09:21:24 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 17 Apr 2013 03:21:24 -0400
Subject: [Tutor] regex to promote Py 2 to Py 3?
In-Reply-To: <CALRAYNXRD92j_5ss8TTvS+R-YyEQ7AO=EazGrhE8-CT_eqz7Sw@mail.gmail.com>
References: <CALRAYNWOGJJmzqW5Y2wQWBtgzqJeJFMsdNrk-wU3afVZeZ5E3w@mail.gmail.com>
	<CACL+1avys_3nh+EfhHNPSapQXaYux5nJpm6SMDtXc_HSXJREPQ@mail.gmail.com>
	<CALRAYNXRD92j_5ss8TTvS+R-YyEQ7AO=EazGrhE8-CT_eqz7Sw@mail.gmail.com>
Message-ID: <CACL+1asOVS7yzdmZS9a6uogKN3wPbRCqRW14g_O+m=_yyt9Ocw@mail.gmail.com>

On Wed, Apr 17, 2013 at 1:11 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
>>>> 2to3 loops.py
>   File "<stdin>", line 1
>     2to3 loops.py
>        ^
> SyntaxError: invalid syntax

The script 2to3.py is run from the system's terminal/console shell
(e.g. cmd or PowerShell on Windows), not the python shell.

If the current directory has the file "loops.py" and Python is
installed in C:\Python33, then try running the following in cmd:

    C:\Python33\Tools\Scripts\2to3.py -w loops.py

If that fails, try running 3.3 explicitly:

    C:\Python33\python.exe C:\Python33\Tools\Scripts\2to3.py -w loops.py

The -w option tells 2to3 to write the ported version back to loops.py.
The original will be backed up to loops.py.bak.

----

Running Scripts

Python 3.3 is distributed on Windows with a "py" launcher that's
associated with .py files. This should be set up by the installer as
follows:

    C:\>assoc .py
    .py=Python.File

    C:\>ftype Python.File
    Python.File="C:\Windows\py.exe" "%1" %*

The launcher parses a script's shebang line, which is a special
comment on the first line. A shebang begins with an exclamation point
(i.e. a "bang"), followed by the command used to run the script. The
launcher accepts a literal command (e.g. #!C:\Python33\python.exe), a
preset virtual command, or an alias you've added to the configuration
ini.

For example, this shebang runs a script in the default Python version:

    #!/usr/bin/env python

"/usr/bin/env" is a Unix-ism included for portability. You can simply
use "#!python3" if you want the script to run in 3.x on Windows.

2.x is the default if it's installed. You can configure the launcher
to instead use 3.x as the default. Just edit the configuration ini:

    >notepad %localappdata%\py.ini

to include the following:

[defaults]
python=3

For convenience, you can add your script directories to the
environment PATH. You can also append ;.PY to the environment PATHEXT
to be able to run "script.py" as just "script", without the .py
extension.

From wprins at gmail.com  Wed Apr 17 10:40:38 2013
From: wprins at gmail.com (Walter Prins)
Date: Wed, 17 Apr 2013 09:40:38 +0100
Subject: [Tutor] regex to promote Py 2 to Py 3?
In-Reply-To: <CALRAYNXRD92j_5ss8TTvS+R-YyEQ7AO=EazGrhE8-CT_eqz7Sw@mail.gmail.com>
References: <CALRAYNWOGJJmzqW5Y2wQWBtgzqJeJFMsdNrk-wU3afVZeZ5E3w@mail.gmail.com>
	<CACL+1avys_3nh+EfhHNPSapQXaYux5nJpm6SMDtXc_HSXJREPQ@mail.gmail.com>
	<CALRAYNXRD92j_5ss8TTvS+R-YyEQ7AO=EazGrhE8-CT_eqz7Sw@mail.gmail.com>
Message-ID: <CANLXbfAhh=4wEgOeO2+p=A1vJZLnyggjA8L0E1oz0E3fSe35tg@mail.gmail.com>

Hi,


On 17 April 2013 06:11, Jim Mooney <cybervigilante at gmail.com> wrote:

> > Generally the 2to3 script does an OK job. If you're using Windows it's
> > [Python_Dir]\Tools\Scripts\2to3.py.
> >
> > http://docs.python.org/3/library/2to3
> ================================
>
> Thanks. I didn't know where to find it and thought I had to install it.
>
> I opened a command window in my Python33/progs dir, started Python,
> and ran it on a tiny test program called loops.py but I get "invalid
> syntax" Any idea why?:
>
> >>> 2to3 loops.py
>   File "<stdin>", line 1
>     2to3 loops.py
>        ^
> SyntaxError: invalid syntax


As additional background to eryksun's response, please read this:
http://www.voidspace.org.uk/python/articles/command_line.shtml

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130417/5bb7343a/attachment.html>

From cybervigilante at gmail.com  Wed Apr 17 18:09:59 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Wed, 17 Apr 2013 09:09:59 -0700
Subject: [Tutor] Tutor Digest, Vol 110, Issue 74
In-Reply-To: <mailman.27.1366192802.25562.tutor@python.org>
References: <mailman.27.1366192802.25562.tutor@python.org>
Message-ID: <CALRAYNWqceKdFvxcQ26hwWqbR4RgG4_8W_7=N5LhObv9S6twSg@mail.gmail.com>

> The script 2to3.py is run from the system's terminal/console shell
> (e.g. cmd or PowerShell on Windows), not the python shell.

Yay, it worked! A decade of Windows and I'm back to the DOS Command
Line ;')  Well, it worked the second time.I thought I could do without
the -w but nothing happened. Now I'll go edit Path so I'm not typing
in all those directories.  2to3 doesn't seem to do anything without
the -w, which I find a tad puzzling.

Jim

From timomlists at gmail.com  Wed Apr 17 18:46:05 2013
From: timomlists at gmail.com (Timo)
Date: Wed, 17 Apr 2013 18:46:05 +0200
Subject: [Tutor] Tutor Digest, Vol 110, Issue 74
In-Reply-To: <CALRAYNWqceKdFvxcQ26hwWqbR4RgG4_8W_7=N5LhObv9S6twSg@mail.gmail.com>
References: <mailman.27.1366192802.25562.tutor@python.org>
	<CALRAYNWqceKdFvxcQ26hwWqbR4RgG4_8W_7=N5LhObv9S6twSg@mail.gmail.com>
Message-ID: <516ED1CD.9060705@gmail.com>

Op 17-04-13 18:09, Jim Mooney schreef:
>> The script 2to3.py is run from the system's terminal/console shell
>> (e.g. cmd or PowerShell on Windows), not the python shell.
> Yay, it worked! A decade of Windows and I'm back to the DOS Command
> Line ;')
If you want to program, the command line is your friend. You'll see it 
alot more.

> Well, it worked the second time.I thought I could do without
> the -w but nothing happened. Now I'll go edit Path so I'm not typing
> in all those directories.  2to3 doesn't seem to do anything without
> the -w, which I find a tad puzzling.
 From the 2to3 --help:

   -w, --write           Write back modified files

So it's normal nothing happens to your files without the -w argument. It 
just prints the changes to stdout.

Timo

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


From bicofino at gmail.com  Wed Apr 17 21:27:50 2013
From: bicofino at gmail.com (Danilo Chilene)
Date: Wed, 17 Apr 2013 16:27:50 -0300
Subject: [Tutor] Sys.argv read parameters
Message-ID: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>

Dear Python Tutor,

I have the code below(file.py):

import sys

a = 'This is A'
b = 'This is B'
c = 'This is C'

for i in sys.argv[1]:
    if sys.argv[1] == 'a':
        print a
    if sys.argv[1] == 'b':
        print b
    if sys.argv[1] == 'c':
        print c

I run python file.py a and returns the var a, so far so good.

The problem is that i have a bunch of vars(like a to z), how I can handle
this in a pythonic way?

Best Regards,

Danilo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130417/32e1b79f/attachment.html>

From dyoo at hashcollision.org  Wed Apr 17 22:03:49 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 17 Apr 2013 14:03:49 -0600
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
Message-ID: <CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>

What's the part that's "changing"?  What's the part that stays the same?

I would recommend thinking of this in terms of a function.

Can you write a function that consumes a letter l and returns the
string "This is ..." where "..." is the uppercased l?

As an example of a simple function on strings:

##########################
## double: string -> string
def double(x):
    return x + x

## For example, a blast from the past:
print "The Noid says: " + double("pizza")
##########################


There are functions in Python standard library that know how to do
things to strings.  See:

    http://docs.python.org/2/library/stdtypes.html#string-methods

From davea at davea.name  Wed Apr 17 22:18:24 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 17 Apr 2013 16:18:24 -0400
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
Message-ID: <516F0390.6010903@davea.name>

On 04/17/2013 03:27 PM, Danilo Chilene wrote:
> Dear Python Tutor,
>
> I have the code below(file.py):
>
> import sys
>
> a = 'This is A'
> b = 'This is B'
> c = 'This is C'
>
> for i in sys.argv[1]:
>      if sys.argv[1] == 'a':
>          print a
>      if sys.argv[1] == 'b':
>          print b
>      if sys.argv[1] == 'c':
>          print c

Since this is a loop, I'll assume that argv[1] was supposed to permit 
multiple characters.  If so, your loop is buggy.  And if not, then you 
don't want a loop.

>
> I run python file.py a and returns the var a, so far so good.

What do you want to happen if you say
       python file.py  ac


>
> The problem is that i have a bunch of vars(like a to z), how I can handle
> this in a pythonic way?
>

Use a dictionary (dict).  Instead of separate 'variables' use one dict. 
  (With version 2.7)

import sys

mystrings = { "a" : "This is A",
               "b" : "This is B",
               "c" : "This is C",
               "d" : "This is some special case D",
             }

for parm in sys.argv[1]:
     if parm in mystrings:
         print mystrings[parm]
     else:
         print "Invalid parm"

If this isn't what you wanted, then you'll have to make it clearer.

1) tell us what version of python
2) supply us with a non-buggy program,
3) be much more specific about what change you want.  You don't want 
more vars, you presumably want a way to avoid having more vars.  Danny 
assumed you wanted those exact strings, for a, b, and c, while i assumed 
that those were just simple examples.


-- 
DaveA

From marc.tompkins at gmail.com  Wed Apr 17 22:24:52 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Wed, 17 Apr 2013 13:24:52 -0700
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
Message-ID: <CAKK8jXYZiZQ3nco3XRn9+x+fngT8AHcmJLSAAanaO-tgFU9-Qg@mail.gmail.com>

On Wed, Apr 17, 2013 at 1:03 PM, Danny Yoo <dyoo at hashcollision.org> wrote:


> ##########################
> ## double: string -> string
> def double(x):
>     return x + x
>
>

> ## For example, a blast from the past:
> print "The Noid says: " + double("pizza")
> ##########################
>

I'm sorry, but this is a bug.  The Noid tried to make Domino's pizzas get
cold before they arrived; Little Caesar said "Pizza, pizza!"


> ## For example, a blast from the past:
> print "Caesar says: " + double("pizza")
> ##########################
>

=D
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130417/3e876283/attachment.html>

From bicofino at gmail.com  Wed Apr 17 22:28:00 2013
From: bicofino at gmail.com (Danilo Chilene)
Date: Wed, 17 Apr 2013 17:28:00 -0300
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <516F0390.6010903@davea.name>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<516F0390.6010903@davea.name>
Message-ID: <CA+_2i1SK1sPqvMvFRcgVeL6o6s3JEfpsezHUA5FOLQifXO3hTw@mail.gmail.com>

Hello Dave,

1) I'm using Python 2.7
2) The program wasn't suppose to really work, was just a example.
3) You assumed correct.

That's was what I looking for, worked like charm.

Thanks!


On Wed, Apr 17, 2013 at 5:18 PM, Dave Angel <davea at davea.name> wrote:

> On 04/17/2013 03:27 PM, Danilo Chilene wrote:
>
>> Dear Python Tutor,
>>
>> I have the code below(file.py):
>>
>> import sys
>>
>> a = 'This is A'
>> b = 'This is B'
>> c = 'This is C'
>>
>> for i in sys.argv[1]:
>>      if sys.argv[1] == 'a':
>>          print a
>>      if sys.argv[1] == 'b':
>>          print b
>>      if sys.argv[1] == 'c':
>>          print c
>>
>
> Since this is a loop, I'll assume that argv[1] was supposed to permit
> multiple characters.  If so, your loop is buggy.  And if not, then you
> don't want a loop.
>
>
>
>> I run python file.py a and returns the var a, so far so good.
>>
>
> What do you want to happen if you say
>       python file.py  ac
>
>
>
>
>> The problem is that i have a bunch of vars(like a to z), how I can handle
>> this in a pythonic way?
>>
>>
> Use a dictionary (dict).  Instead of separate 'variables' use one dict.
>  (With version 2.7)
>
> import sys
>
> mystrings = { "a" : "This is A",
>               "b" : "This is B",
>               "c" : "This is C",
>               "d" : "This is some special case D",
>             }
>
> for parm in sys.argv[1]:
>     if parm in mystrings:
>         print mystrings[parm]
>     else:
>         print "Invalid parm"
>
> If this isn't what you wanted, then you'll have to make it clearer.
>
> 1) tell us what version of python
> 2) supply us with a non-buggy program,
> 3) be much more specific about what change you want.  You don't want more
> vars, you presumably want a way to avoid having more vars.  Danny assumed
> you wanted those exact strings, for a, b, and c, while i assumed that those
> were just simple examples.
>
>
> --
> DaveA
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130417/33c832f6/attachment-0001.html>

From dyoo at hashcollision.org  Wed Apr 17 22:49:07 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 17 Apr 2013 14:49:07 -0600
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <CA+_2i1SK1sPqvMvFRcgVeL6o6s3JEfpsezHUA5FOLQifXO3hTw@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<516F0390.6010903@davea.name>
	<CA+_2i1SK1sPqvMvFRcgVeL6o6s3JEfpsezHUA5FOLQifXO3hTw@mail.gmail.com>
Message-ID: <CAGZAPF4d4iP4_xwAPOUUWpnf9rau1rsZ6WDnBjvVE-p-3HMzrQ@mail.gmail.com>

Wait.  If the solution that we're stopping at to use a hashtable here,
that's not quite right. A good solution to this should be _much_
shorter, on the order of a one-liner.  Hashtables are great, but
they're not the answer to everything.


If we're doing something like:

    a -> "This is A"
    b -> "This is B"
    ...
    z -> "This is Z"

a good solution to this isn't to make a hashtable with 26 entries, and
do a lookup: the approach is more something like this:


###############################
def getMessage(letter):
    return "This is " + letter.upper()
###############################

For example:

#################
>>> getMessage('a')
'This is A'
>>> getMessage('b')
'This is B'
>>> getMessage('z')
'This is Z'
#################


The size of your program should be proportional to how "differently"
it has to act on input.  In this case, the program is pretty much the
same on all inputs, modulo the very last chunk of the message.  That's
why thinking about this in terms of functions is crucial: if you
don't, the code ends up being larger than it deserves.

From davea at davea.name  Wed Apr 17 23:02:36 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 17 Apr 2013 17:02:36 -0400
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <CAGZAPF4d4iP4_xwAPOUUWpnf9rau1rsZ6WDnBjvVE-p-3HMzrQ@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<516F0390.6010903@davea.name>
	<CA+_2i1SK1sPqvMvFRcgVeL6o6s3JEfpsezHUA5FOLQifXO3hTw@mail.gmail.com>
	<CAGZAPF4d4iP4_xwAPOUUWpnf9rau1rsZ6WDnBjvVE-p-3HMzrQ@mail.gmail.com>
Message-ID: <516F0DEC.9020205@davea.name>

On 04/17/2013 04:49 PM, Danny Yoo wrote:
> Wait.  If the solution that we're stopping at to use a hashtable here,
> that's not quite right.

Nothing wrong with a dict, if a proper specification of the problem were 
available.  Notice that in my solution, the messages were not all 
trivially related to each other.

I made some guesses, and you made some different ones.  The OP is happy. 
  Let it rest.



-- 
DaveA

From dyoo at hashcollision.org  Wed Apr 17 23:15:10 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 17 Apr 2013 15:15:10 -0600
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <516F0DEC.9020205@davea.name>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<516F0390.6010903@davea.name>
	<CA+_2i1SK1sPqvMvFRcgVeL6o6s3JEfpsezHUA5FOLQifXO3hTw@mail.gmail.com>
	<CAGZAPF4d4iP4_xwAPOUUWpnf9rau1rsZ6WDnBjvVE-p-3HMzrQ@mail.gmail.com>
	<516F0DEC.9020205@davea.name>
Message-ID: <CAGZAPF7U9uvxAU2dpDU8Ld7+TaK_d9dt85jtf0YBxY1Gg-wwLw@mail.gmail.com>

Yup!  Sorry about my tone for its stridency.  But I just got concerned
that the original poster seemed content about turning the chain of if
statements into a table definition.  To my mind, they're very closely
related, data and control.  I'm trying to push the OP to realizing
that if they are doing this, they are still enumerating all the
decisions.  Maybe it's not in the form of a chain of if statements,
but it's still reflected in the structure of the table.

(It's the same reason I get concerned when I see students not
recognize the similarities between if statements and polymorphism:
it's all about transmogrifying control flow and data structures.)

Let me say that if there's non-uniformity among the choices, then the
table lookup approach (a dispatch table) is probably the right tool.
If there's uniformity, then a computational approach should be
considered.

From cbc at unc.edu  Wed Apr 17 23:18:55 2013
From: cbc at unc.edu (Chris Calloway)
Date: Wed, 17 Apr 2013 17:18:55 -0400
Subject: [Tutor] PyCamp Registration Open for Columbus, Toronto, and Oshkosh
Message-ID: <516F11BF.7060404@unc.edu>

Registration is open for three upcoming PyCamps produced by the Triangle 
Python Users Group:

- A five-day PyOhio PyCamp hosted by the Ohio State University Open 
Source Club, July 22-26, 2013 the week prior to the PyOhio regional 
Python conference weekend. PyCamp is a training program and sponsor of 
PyOhio:

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

- A five-day Toronto PyCamp hosted by the University of Toronto 
Department of Physics, August 12-16, 2013 the week after the PyCon 
Canada national Python conference weekend. PyCamp is a Diversity Sponsor 
of PyCon CA:

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

- A three-day Wisconsin Mini-PyCamp hosted at the University of 
Wisconsin Oshkosh, June 2-4, 2013 as part of the Plone Symposium Midwest 
training days:

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

PyCamp is the original, ultra-low-cost Python Boot Camp created by a 
user group for user groups. For beginners, PyCamp makes you productive 
so you can get your work done quickly. PyCamp emphasizes the features 
which make Python a simpler and more efficient language. Following along 
with example Python PushUps speeds your learning process. Become a 
self-sufficient Python developer at PyCamp. PyCamps are conducted in 
state of the art high technology classrooms on university campuses.

Registration will open soon also for two additional Triangle Python User 
Group boot camp events. An additional announcement will follow when 
registration opens for these events, but mark your calendars now:

- A five-day Seattle PyCamp hosted by the University of Washington 
Department of Computer Science and Engineering and UW Marketing, 
September 9-13, 2013. PyCamp is a sponsor of the Seattle Plone Users Group.

- A five-day special Python Web Programming boot camp hosted by the 
University of North Carolina Department of Marine Sciences, August 5-9, 
2013.

-- 
Sincerely,

Chris Calloway http://nccoos.org/Members/cbc
office: 3313 Venable Hall   phone: (919) 599-3530
mail: Campus Box #3300, UNC-CH, Chapel Hill, NC 27599

From davea at davea.name  Wed Apr 17 23:24:59 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 17 Apr 2013 17:24:59 -0400
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <CAGZAPF7U9uvxAU2dpDU8Ld7+TaK_d9dt85jtf0YBxY1Gg-wwLw@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<516F0390.6010903@davea.name>
	<CA+_2i1SK1sPqvMvFRcgVeL6o6s3JEfpsezHUA5FOLQifXO3hTw@mail.gmail.com>
	<CAGZAPF4d4iP4_xwAPOUUWpnf9rau1rsZ6WDnBjvVE-p-3HMzrQ@mail.gmail.com>
	<516F0DEC.9020205@davea.name>
	<CAGZAPF7U9uvxAU2dpDU8Ld7+TaK_d9dt85jtf0YBxY1Gg-wwLw@mail.gmail.com>
Message-ID: <516F132B.4090203@davea.name>

On 04/17/2013 05:15 PM, Danny Yoo wrote:
> Yup!  Sorry about my tone for its stridency.  But I just got concerned
> that the original poster seemed content about turning the chain of if
> statements into a table definition.  To my mind, they're very closely
> related, data and control.  I'm trying to push the OP to realizing
> that if they are doing this, they are still enumerating all the
> decisions.  Maybe it's not in the form of a chain of if statements,
> but it's still reflected in the structure of the table.
>
> (It's the same reason I get concerned when I see students not
> recognize the similarities between if statements and polymorphism:
> it's all about transmogrifying control flow and data structures.)
>
> Let me say that if there's non-uniformity among the choices, then the
> table lookup approach (a dispatch table) is probably the right tool.
> If there's uniformity, then a computational approach should be
> considered.
>
>

But look at the original question.  It was about having many variables. 
  And a dict is the way to take many variables out of the namespace and 
replacing them with one.  And it was unlikely to my mind that the final 
intent was to produce such a simplistic message for each letter.

-- 
DaveA

From dyoo at hashcollision.org  Wed Apr 17 23:45:16 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 17 Apr 2013 15:45:16 -0600
Subject: [Tutor] Fwd:  Sys.argv read parameters
In-Reply-To: <CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
	<CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
Message-ID: <CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>

Forwarding message to Python-tutor mailing list.  I did not realize
that your reply didn't show up for the rest of Python tutor.  Please
use Reply to All in the future.



---------- Forwarded message ----------
From: Danilo Chilene <bicofino at gmail.com>
Date: Wed, Apr 17, 2013 at 2:17 PM
Subject: Re: [Tutor] Sys.argv read parameters
To: Danny Yoo <dyoo at hashcollision.org>


Hello Danny,

The part that is changing is just the sys.argv[1]
The vars will have always the same content.

What I don't want is to have like 255 'ifs' if I have 255 vars.


On Wed, Apr 17, 2013 at 5:03 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
>
> What's the part that's "changing"?  What's the part that stays the same?
>
> I would recommend thinking of this in terms of a function.
>
> Can you write a function that consumes a letter l and returns the
> string "This is ..." where "..." is the uppercased l?
>
> As an example of a simple function on strings:
>
> ##########################
> ## double: string -> string
> def double(x):
>     return x + x
>
> ## For example, a blast from the past:
> print "The Noid says: " + double("pizza")
> ##########################
>
>
> There are functions in Python standard library that know how to do
> things to strings.  See:
>
>     http://docs.python.org/2/library/stdtypes.html#string-methods

From breamoreboy at yahoo.co.uk  Thu Apr 18 00:27:29 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Wed, 17 Apr 2013 23:27:29 +0100
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
Message-ID: <kkn7kg$c5t$1@ger.gmane.org>

On 17/04/2013 20:27, Danilo Chilene wrote:
> Dear Python Tutor,
>
> I have the code below(file.py):
>
> import sys
>
> a = 'This is A'
> b = 'This is B'
> c = 'This is C'
>
> for i in sys.argv[1]:
>      if sys.argv[1] == 'a':
>          print a
>      if sys.argv[1] == 'b':
>          print b
>      if sys.argv[1] == 'c':
>          print c
>
> I run python file.py a and returns the var a, so far so good.
>
> The problem is that i have a bunch of vars(like a to z), how I can
> handle this in a pythonic way?
>
> Best Regards,
>
> Danilo
>

Further to earlier answers you might like to look at these modules for 
parsing items from sys.argv.

http://docs.python.org/3/library/argparse.html#module-argparse
http://docs.python.org/3/library/getopt.html#module-getopt

http://docs.python.org/3/library/optparse.html#module-optparse is 
available in Python 2.x but is deprecated as of Python 3.2.

There is also an awesome third party module here 
https://github.com/docopt/docopt

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From davea at davea.name  Thu Apr 18 01:21:30 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 17 Apr 2013 19:21:30 -0400
Subject: [Tutor] Fwd:  Sys.argv read parameters
In-Reply-To: <CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
	<CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
	<CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>
Message-ID: <516F2E7A.2020503@davea.name>


> ---------- Forwarded message ----------
> From: Danilo Chilene <bicofino at gmail.com>
> Date: Wed, Apr 17, 2013 at 2:17 PM
> Subject: Re: [Tutor] Sys.argv read parameters
> To: Danny Yoo <dyoo at hashcollision.org>
>
>
> Hello Danny,
>
> The part that is changing is just the sys.argv[1]
> The vars will have always the same content.
>
> What I don't want is to have like 255 'ifs' if I have 255 vars.
>

Please don't top post. Put your response AFTER the part you're quoting.

>
> On Wed, Apr 17, 2013 at 5:03 PM, Danny Yoo <dyoo at hashcollision.org> wrote:
>>
>> What's the part that's "changing"?  What's the part that stays the same?
>>

Are all the strings going to be identical except for the one letter?  If 
so, then read the better responses here, like those from Danny Yoo

So far, you haven't provided any useful input as to what you're really 
looking for.




-- 
DaveA

From alan.gauld at btinternet.com  Thu Apr 18 02:12:08 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 18 Apr 2013 01:12:08 +0100
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
Message-ID: <kkndok$3je$1@ger.gmane.org>

On 17/04/13 20:27, Danilo Chilene wrote:

> import sys
>
> a = 'This is A'
> b = 'This is B'
> c = 'This is C'
>
> for i in sys.argv[1]:
>      if sys.argv[1] == 'a':
>          print a
>      if sys.argv[1] == 'b':
>          print b
>      if sys.argv[1] == 'c':
>          print c
>
> I run python file.py a and returns the var a, so far so good.
>
> The problem is that i have a bunch of vars(like a to z), how I can
> handle this in a pythonic way?

Use a dictionary.

myVars = {
'a':'This is A',
'b':'This is B',
'c':'This is C',
# as many more as needed
}

print myVars.get(sys.argv[1], 'No variable found')

Is that what you mean?

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


From chuck.mayers at gmail.com  Thu Apr 18 02:16:38 2013
From: chuck.mayers at gmail.com (Chuck Mayers)
Date: Wed, 17 Apr 2013 19:16:38 -0500
Subject: [Tutor] new to threading, Queues
Message-ID: <CAJh6O2qq_MCsn5zrTEEV3brwCsQn0t_FOrDgsXuyhDw89X3W9A@mail.gmail.com>

Hi!  I was having a bit of nostalgia today, and thought I'd try to write a
simple, old school BBS.  I found the 'paramiko' library, and I've got
something I can SSH into that would have impressed my 1990's self.

I found some example code of the "threading" library, and I've managed to
use it to take multiple incoming connections at once.

I've never done any multithreaded programming, and everything I've ever
read is essentially "don't do it! It's really hard to get right!"

Everything I've read today says to use the Queue library
I can't seem to wrap my head around it, though. I've not seen any example
code that looks like what I'm trying to do.

Some examples of things I'd like to do:
Have one thread open a file (that all threads will want to read/write to)
and update it
Have one thread broadcast to all other threads a "chat message"


The only way I can think of, with the Queue library, would be the following
(I know this has to be the "wrong way" to do this):

1. create an object MultiTask which will have methods to handle thread
sensitive things like "update a file", etc
2. create one instance of it (we'll call it mtask) and add it to the queue
3. each thread, when it needs to, does queue.get() to get that instance
4. the thread then calls whatever it needs to, say mtask.update_users_file()
5. then, call queue.put(mtask) to put it back on the queue

so, there is only ever 1 object in the queue. I assume when another thread
tries to get() it, they block until the other threads are done with it.

Will this work? Is there a better way to do this?

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130417/290b4282/attachment.html>

From davea at davea.name  Thu Apr 18 03:07:55 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 17 Apr 2013 21:07:55 -0400
Subject: [Tutor] Sys.argv read parameters
In-Reply-To: <kkndok$3je$1@ger.gmane.org>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<kkndok$3je$1@ger.gmane.org>
Message-ID: <516F476B.3020406@davea.name>

On 04/17/2013 08:12 PM, Alan Gauld wrote:
> On 17/04/13 20:27, Danilo Chilene wrote:
>
>> import sys
>>
>> a = 'This is A'
>> b = 'This is B'
>> c = 'This is C'
>>
>> for i in sys.argv[1]:
>>      if sys.argv[1] == 'a':
>>          print a
>>      if sys.argv[1] == 'b':
>>          print b
>>      if sys.argv[1] == 'c':
>>          print c
>>
>> I run python file.py a and returns the var a, so far so good.
>>
>> The problem is that i have a bunch of vars(like a to z), how I can
>> handle this in a pythonic way?
>
> Use a dictionary.
>
> myVars = {
> 'a':'This is A',
> 'b':'This is B',
> 'c':'This is C',
> # as many more as needed
> }
>
> print myVars.get(sys.argv[1], 'No variable found')
>
> Is that what you mean?
>

What's the point?  The OP is not clarifying the "spec."  I posited a 
dict and supplied code several messages ago (about 4.5 hours), and he 
said "worked like a charm."  But since then he has given cryptic 
responses to others, and still not answered a few of the questions I 
asked then.


-- 
DaveA

From wolfrage8765 at gmail.com  Thu Apr 18 11:28:42 2013
From: wolfrage8765 at gmail.com (Jordan)
Date: Thu, 18 Apr 2013 11:28:42 +0200
Subject: [Tutor] new to threading, Queues
In-Reply-To: <CAJh6O2qq_MCsn5zrTEEV3brwCsQn0t_FOrDgsXuyhDw89X3W9A@mail.gmail.com>
References: <CAJh6O2qq_MCsn5zrTEEV3brwCsQn0t_FOrDgsXuyhDw89X3W9A@mail.gmail.com>
Message-ID: <516FBCCA.1040608@gmail.com>


On 04/18/2013 02:16 AM, Chuck Mayers wrote:
> Hi!  I was having a bit of nostalgia today, and thought I'd try to 
> write a simple, old school BBS.  I found the 'paramiko' library, and 
> I've got something I can SSH into that would have impressed my 1990's 
> self.
>
> I found some example code of the "threading" library, and I've managed 
> to use it to take multiple incoming connections at once.
>
> I've never done any multithreaded programming, and everything I've 
> ever read is essentially "don't do it! It's really hard to get right!"
True it canbe difficult, but how are you supposed to learn if you don't 
try it, and sometimes you need to do two things at once or at least nearly.
>
> Everything I've read today says to use the Queue library
> I can't seem to wrap my head around it, though. I've not seen any 
> example code that looks like what I'm trying to do.
>
> Some examples of things I'd like to do:
> Have one thread open a file (that all threads will want to read/write 
> to) and update it
> Have one thread broadcast to all other threads a "chat message"
>
>
> The only way I can think of, with the Queue library, would be the 
> following (I know this has to be the "wrong way" to do this):
>
> 1. create an object MultiTask which will have methods to handle thread 
> sensitive things like "update a file", etc
> 2. create one instance of it (we'll call it mtask) and add it to the queue
> 3. each thread, when it needs to, does queue.get() to get that instance
> 4. the thread then calls whatever it needs to, say 
> mtask.update_users_file()
> 5. then, call queue.put(mtask) to put it back on the queue
>
Yeah, I am not sure that will work but maybe.  What I did was to model 
the Mediator Pattern kind of, it then controls the queue and assigns the 
workload to multiple threads creating new threads as needed.  Not that 
my way is the best just how I did it.
http://sourcemaking.com/design_patterns/mediator
My Mediator does not follow the design pattern very well, it is called 
dispatcher, and it uses workers to get the Jobs done, jobs are actually 
defined too. Additionally the code is not as good as it could be, 
because I have not used in for many months, but the tests should work.  
It was made with Python3 in mind. It is attached.

> so, there is only ever 1 object in the queue. I assume when another 
> thread tries to get() it, they block until the other threads are done 
> with it.
>
> Will this work? Is there a better way to do this?
>
> Thanks!
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

-------------- next part --------------
A non-text attachment was scrubbed...
Name: Workers.py
Type: text/x-python
Size: 6523 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20130418/44051213/attachment-0001.py>

From wayne at waynewerner.com  Thu Apr 18 14:42:15 2013
From: wayne at waynewerner.com (Wayne Werner)
Date: Thu, 18 Apr 2013 07:42:15 -0500 (CDT)
Subject: [Tutor] design question (Django?)
In-Reply-To: <B4EF0C7D-44E9-42C3-8EAC-3256C5F974A3@gmail.com>
References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkb3a8$b2a$1@ger.gmane.org>
	<1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkbi22$99c$1@ger.gmane.org>
	<1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<B4EF0C7D-44E9-42C3-8EAC-3256C5F974A3@gmail.com>
Message-ID: <alpine.DEB.2.02.1304180739170.3322@gilgamesh>

On Sun, 14 Apr 2013, Don Jennings wrote:

>
> On Apr 14, 2013, at 7:06 AM, Albert-Jan Roskam wrote:
>
>>
>>
>> > Subject: Re: [Tutor] design question (Django?)
>>>
>>> On 13/04/13 09:48, Albert-Jan Roskam wrote:
>>>
>>>> I think I have to make a diagram of this. This stuff is quite hard
>>>
>> Would it also be a good idea to simultaneously make a paper-and-pencil drawing of the UI?
>
> Absolutely! Test it with three users. See Jakob Nielsen's brief take on the matter:
>

A recommendation - check out Balsamiq Mockups for UI design. If you plan 
to make this project open source they'll provide you a free license (with 
a bit of documentation, e.g. link to project on Bitbucket/Github/etc with 
a OSI approved license).

They also have a free web demo that's pretty powerful and just nags every 
5 (or 15?) minutes. http://www.balsamiq.com/

I've not found a better tool for doing quick and rough UI mockps!

HTH,
Wayne

From bicofino at gmail.com  Thu Apr 18 15:21:18 2013
From: bicofino at gmail.com (Danilo Chilene)
Date: Thu, 18 Apr 2013 10:21:18 -0300
Subject: [Tutor] Fwd: Sys.argv read parameters
In-Reply-To: <516F2E7A.2020503@davea.name>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
	<CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
	<CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>
	<516F2E7A.2020503@davea.name>
Message-ID: <CA+_2i1SY=xb43bX+GXjbD3mm6bp-ayeQD4QWe7wweFdMbHem3w@mail.gmail.com>

On Wed, Apr 17, 2013 at 8:21 PM, Dave Angel <davea at davea.name> wrote:

>
>  ---------- Forwarded message ----------
>> From: Danilo Chilene <bicofino at gmail.com>
>> Date: Wed, Apr 17, 2013 at 2:17 PM
>> Subject: Re: [Tutor] Sys.argv read parameters
>> To: Danny Yoo <dyoo at hashcollision.org>
>>
>>
>> Hello Danny,
>>
>> The part that is changing is just the sys.argv[1]
>> The vars will have always the same content.
>>
>> What I don't want is to have like 255 'ifs' if I have 255 vars.
>>
>>
> Please don't top post. Put your response AFTER the part you're quoting.
>
>
>
>> On Wed, Apr 17, 2013 at 5:03 PM, Danny Yoo <dyoo at hashcollision.org>
>> wrote:
>>
>>>
>>> What's the part that's "changing"?  What's the part that stays the same?
>>>
>>>
> Are all the strings going to be identical except for the one letter?  If
> so, then read the better responses here, like those from Danny Yoo
>
>
The strings will always be the same except for the letter.


> So far, you haven't provided any useful input as to what you're really
> looking for.
>
>
>
>
> --
> DaveA
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130418/b3082eec/attachment.html>

From davea at davea.name  Thu Apr 18 15:31:56 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 18 Apr 2013 09:31:56 -0400
Subject: [Tutor] Fwd: Sys.argv read parameters
In-Reply-To: <CA+_2i1SY=xb43bX+GXjbD3mm6bp-ayeQD4QWe7wweFdMbHem3w@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
	<CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
	<CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>
	<516F2E7A.2020503@davea.name>
	<CA+_2i1SY=xb43bX+GXjbD3mm6bp-ayeQD4QWe7wweFdMbHem3w@mail.gmail.com>
Message-ID: <516FF5CC.3060904@davea.name>

On 04/18/2013 09:21 AM, Danilo Chilene wrote:
> On Wed, Apr 17, 2013 at 8:21 PM, Dave Angel <davea at davea.name> wrote:
>
>>
>>   ---------- Forwarded message ----------
>>> From: Danilo Chilene <bicofino at gmail.com>
>>> Date: Wed, Apr 17, 2013 at 2:17 PM
>>> Subject: Re: [Tutor] Sys.argv read parameters
>>> To: Danny Yoo <dyoo at hashcollision.org>
>>>
>>>
>>> Hello Danny,
>>>
>>> The part that is changing is just the sys.argv[1]
>>> The vars will have always the same content.
>>>
>>> What I don't want is to have like 255 'ifs' if I have 255 vars.
>>>
>>>
>> Please don't top post. Put your response AFTER the part you're quoting.
>>
>>
>>
>>> On Wed, Apr 17, 2013 at 5:03 PM, Danny Yoo <dyoo at hashcollision.org>
>>> wrote:
>>>
>>>>
>>>> What's the part that's "changing"?  What's the part that stays the same?
>>>>
>>>>
>> Are all the strings going to be identical except for the one letter?  If
>> so, then read the better responses here, like those from Danny Yoo
>>
>>
> The strings will always be the same except for the letter.
>

Then in that case, why do you use any if-test?  Just substitute the 
letter, as Danny pointed out.

You never said whether you accept more than one letter from the command 
line.  I've been assuming you do, since you used a loop.

for letter in sys.argv[1].upper():
     print "This is uppercase of one of the input letters, %s" % letter





-- 
DaveA

From wprins at gmail.com  Thu Apr 18 16:16:34 2013
From: wprins at gmail.com (Walter Prins)
Date: Thu, 18 Apr 2013 15:16:34 +0100
Subject: [Tutor] design question (Django?)
In-Reply-To: <alpine.DEB.2.02.1304180739170.3322@gilgamesh>
References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkb3a8$b2a$1@ger.gmane.org>
	<1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkbi22$99c$1@ger.gmane.org>
	<1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<B4EF0C7D-44E9-42C3-8EAC-3256C5F974A3@gmail.com>
	<alpine.DEB.2.02.1304180739170.3322@gilgamesh>
Message-ID: <CANLXbfAkf6c0Trqg0Ybdes09YZhQuJ_5HPmJnW2Mwhxe9p3peg@mail.gmail.com>

Hi,


On Sun, 14 Apr 2013, Don Jennings wrote:
>
>
>> On Apr 14, 2013, at 7:06 AM, Albert-Jan Roskam wrote:
>>
>>
>>>
>>> > Subject: Re: [Tutor] design question (Django?)
>>>
>>>>
>>>> On 13/04/13 09:48, Albert-Jan Roskam wrote:
>>>>
>>>>  I think I have to make a diagram of this. This stuff is quite hard
>>>>>
>>>>
>>>>  Would it also be a good idea to simultaneously make a paper-and-pencil
>>> drawing of the UI?
>>>
>>
>> Absolutely! Test it with three users. See Jakob Nielsen's brief take on
>> the matter:
>>
>>
You might check out Pencil, which I quite like.

http://pencil.evolus.vn/

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130418/e3214b5d/attachment.html>

From cybervigilante at gmail.com  Thu Apr 18 18:45:51 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Thu, 18 Apr 2013 09:45:51 -0700
Subject: [Tutor] path directory backslash ending
Message-ID: <CALRAYNVKoX3MN9wTspWdCVN+1dvPmSgPjKeDfNQBZWvPo85SEw@mail.gmail.com>

Minor question. I was adding the Py Script directory to the Win 7
Path, and noticed that Python33 ends with a backslash but many
directories do not. Is there a difference? Should I use backslash or
not preferentially, or doesn't it matter at all? It does seem odd that
there's no convention for this.

-- 
Jim Mooney

Today is the day that would have been tomorrow if yesterday was today

From davea at davea.name  Thu Apr 18 18:59:41 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 18 Apr 2013 12:59:41 -0400
Subject: [Tutor] path directory backslash ending
In-Reply-To: <CALRAYNVKoX3MN9wTspWdCVN+1dvPmSgPjKeDfNQBZWvPo85SEw@mail.gmail.com>
References: <CALRAYNVKoX3MN9wTspWdCVN+1dvPmSgPjKeDfNQBZWvPo85SEw@mail.gmail.com>
Message-ID: <5170267D.9030600@davea.name>

On 04/18/2013 12:45 PM, Jim Mooney wrote:
> Minor question. I was adding the Py Script directory to the Win 7
> Path, and noticed that Python33 ends with a backslash but many
> directories do not. Is there a difference? Should I use backslash or
> not preferentially, or doesn't it matter at all? It does seem odd that
> there's no convention for this.
>

There's no Python convention.  There may be a Windows convention, but I 
doubt it.  As far as I could tell when I was stuck in Windows, the only 
time a trailing backslash was significant was when there was nothing in 
front of it but a colon and/or a drive letter.

In Linux, applications are free to make their own use of the trailing 
backslash, and I know that rsync does something different with it 
present than without.  But in the PATH, it doesn't matter.

-- 
DaveA

From bicofino at gmail.com  Thu Apr 18 19:14:08 2013
From: bicofino at gmail.com (Danilo Chilene)
Date: Thu, 18 Apr 2013 14:14:08 -0300
Subject: [Tutor] Fwd: Sys.argv read parameters
In-Reply-To: <516FF5CC.3060904@davea.name>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
	<CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
	<CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>
	<516F2E7A.2020503@davea.name>
	<CA+_2i1SY=xb43bX+GXjbD3mm6bp-ayeQD4QWe7wweFdMbHem3w@mail.gmail.com>
	<516FF5CC.3060904@davea.name>
Message-ID: <CA+_2i1TfDMLr5wRQ=nwAMEJY87rKJFQTK=zQ12qM3egosVzOxg@mail.gmail.com>

On Thu, Apr 18, 2013 at 10:31 AM, Dave Angel <davea at davea.name> wrote:

> On 04/18/2013 09:21 AM, Danilo Chilene wrote:
>
>> On Wed, Apr 17, 2013 at 8:21 PM, Dave Angel <davea at davea.name> wrote:
>>
>>
>>>   ---------- Forwarded message ----------
>>>
>>>> From: Danilo Chilene <bicofino at gmail.com>
>>>> Date: Wed, Apr 17, 2013 at 2:17 PM
>>>> Subject: Re: [Tutor] Sys.argv read parameters
>>>> To: Danny Yoo <dyoo at hashcollision.org>
>>>>
>>>>
>>>> Hello Danny,
>>>>
>>>> The part that is changing is just the sys.argv[1]
>>>> The vars will have always the same content.
>>>>
>>>> What I don't want is to have like 255 'ifs' if I have 255 vars.
>>>>
>>>>
>>>>  Please don't top post. Put your response AFTER the part you're quoting.
>>>
>>>
>>>
>>>  On Wed, Apr 17, 2013 at 5:03 PM, Danny Yoo <dyoo at hashcollision.org>
>>>> wrote:
>>>>
>>>>
>>>>> What's the part that's "changing"?  What's the part that stays the
>>>>> same?
>>>>>
>>>>>
>>>>>  Are all the strings going to be identical except for the one letter?
>>>  If
>>> so, then read the better responses here, like those from Danny Yoo
>>>
>>>
>>>  The strings will always be the same except for the letter.
>>
>>
> Then in that case, why do you use any if-test?  Just substitute the
> letter, as Danny pointed out.
>
> You never said whether you accept more than one letter from the command
> line.  I've been assuming you do, since you used a loop.
>
> for letter in sys.argv[1].upper():
>     print "This is uppercase of one of the input letters, %s" % letter


Below is the final code:

import requests, json, sys

r = requests.get('http://napmongo01.cvc.com.br:28017/_status')
j = r.json()

arg = sys.argv[1]

commands = {
                'uptime' : "j['serverStatus']['uptime']"
                'globalLock_lockTime' :
"j['serverStatus']['globalLock']['lockTime']"
                'globalLock_currentQueue_total' =
"j['serverStatus']['globalLock']['currentQueue']['total']"
                'globalLock_currentQueue_readers' =
"j['serverStatus']['globalLock']['currentQueue']['readers']"
                'globalLock_currentQueue_writers' =
"j['serverStatus']['globalLock']['currentQueue']['writers']"
                'mem_bits' = "j['serverStatus']['mem']['bits']"
                'mem_resident' = "j['serverStatus']['mem']['resident']"
                'mem_virtual' = "j['serverStatus']['mem']['virtual']"
                'connections_current' =
"j['serverStatus']['connections']['current']"
                'connections_available' =
"j['serverStatus']['connections']['available']"
                'extra_info_heap_usage' =
round(("j['serverStatus']['extra_info']['heap_usage_bytes'])/(1024*124), 2)"
                'extra_info_page_faults' =
"j['serverStatus']['extra_info']['page_faults']"
                'indexCounters_btree_accesses' =
"j['serverStatus']['indexCounters']['btree']['accesses']"
                'indexCounters_btree_hits' =
"j['serverStatus']['indexCounters']['btree']['hits']"
                'indexCounters_btree_misses' =
"j['serverStatus']['indexCounters']['btree']['misses']"
                'indexCounters_btree_resets' =
"j['serverStatus']['indexCounters']['btree']['resets']"
                'indexCounters_btree_missRatio' =
"j['serverStatus']['indexCounters']['btree']['missRatio']"
                'backgroundFlushing_flushes' =
"j['serverStatus']['backgroundFlushing']['flushes']"
                'backgroundFlushing_total_ms' =
"j['serverStatus']['backgroundFlushing']['total_ms']"
                'backgroundFlushing_average_ms' =
"j['serverStatus']['backgroundFlushing']['average_ms']"
                'backgroundFlushing_last_ms' =
"j['serverStatus']['backgroundFlushing']['last_ms']"
                'cursors_totalOpen' =
"j['serverStatus']['cursors']['totalOpen']"
                'cursors_clientCursors_size' =
"j['serverStatus']['cursors']['clientCursors_size']"
                'cursors_timedOut' =
"j['serverStatus']['cursors']['timedOut']"
                'opcounters_insert' =
"j['serverStatus']['opcounters']['insert']"
                'opcounters_query' =
"j['serverStatus']['opcounters']['query']"
                'opcounters_update' =
"j['serverStatus']['opcounters']['update']"
                'opcounters_delete' =
"j['serverStatus']['opcounters']['delete']"
                'opcounters_getmore' =
"j['serverStatus']['opcounters']['getmore']"
                'opcounters_command' =
['server_status']['opcounters']['command']""
                'asserts_regular' =
"j['serverStatus']['asserts']['regular']"
                'asserts_warning' =
"j['serverStatus']['asserts']['warning']"
                'asserts_msg' = "j['serverStatus']['asserts']['msg']"
                'asserts_user' = "j['serverStatus']['asserts']['user']"
                'asserts_rollovers' =
"j['serverStatus']['asserts']['rollovers']"
                'network_inbound_traffic_mb' =
("j['serverStatus']['network']['bytesIn'])/(1024*1024)"
                'network_outbound_traffic_mb' =
("j['serverStatus']['network']['bytesOut'])/(1024*1024)"
                'network_requests' =
"j['serverStatus']['network']['numRequests']"
                'write_backs_queued' =
"j['serverStatus']['writeBacksQueued']"
                'logging_commits' = "j['serverStatus']['dur']['commits']"
                'logging_journal_writes_mb' =
"j['serverStatus']['dur']['journaledMB']"
                'logging_datafile_writes_mb' =
"j['serverStatus']['dur']['writeToDataFilesMB']"
                'logging_commits_in_writelock' =
"j['serverStatus']['dur']['commitsInWriteLock']"
                'logging_early_commits' =
"j['serverStatus']['dur']['earlyCommits']"
                'logging_log_buffer_prep_time_ms' =
"j['serverStatus']['dur']['timeMs']['prepLogBuffer']"
                'logging_journal_write_time_ms' =
"j['serverStatus']['dur']['timeMs']['writeToJournal']"
                'logging_datafile_write_time_ms' =
"j['serverStatus']['dur']['timeMs']['writeToDataFiles']"
}

for command in commands:
    if arg in commands:
        print commands[command]
    else:
        print 'Invalid command'


Below the output:
(danilochilene at notebico - ~/lixo @14:06:56)
2: python mongo-test.py uptime
j['serverStatus']['uptime']

(danilochilene at notebico - ~/lixo @14:07:00)
2: python -i mongo-test.py uptime
j['serverStatus']['uptime']
>>> j['serverStatus']['uptime']
27806
>>>

My only issue now is commands[command] (as the example above) have the same
output as j['serverStatus']['uptime'].

Thanks for the help so far!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130418/09365b10/attachment-0001.html>

From davea at davea.name  Thu Apr 18 19:34:09 2013
From: davea at davea.name (Dave Angel)
Date: Thu, 18 Apr 2013 13:34:09 -0400
Subject: [Tutor] Fwd: Sys.argv read parameters
In-Reply-To: <CA+_2i1TfDMLr5wRQ=nwAMEJY87rKJFQTK=zQ12qM3egosVzOxg@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
	<CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
	<CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>
	<516F2E7A.2020503@davea.name>
	<CA+_2i1SY=xb43bX+GXjbD3mm6bp-ayeQD4QWe7wweFdMbHem3w@mail.gmail.com>
	<516FF5CC.3060904@davea.name>
	<CA+_2i1TfDMLr5wRQ=nwAMEJY87rKJFQTK=zQ12qM3egosVzOxg@mail.gmail.com>
Message-ID: <51702E91.60807@davea.name>

On 04/18/2013 01:14 PM, Danilo Chilene wrote:
>
>    <SNIP>

The following code has little to do with anything that happened before. 
  So you should start a new thread for this new project.

>
> Below is the final code:
>
> import requests, json, sys
>
> r = requests.get('http://napmongo01.cvc.com.br:28017/_status')
> j = r.json()
>
> arg = sys.argv[1]
>
> commands = {
>                  'uptime' : "j['serverStatus']['uptime']"
>                  'globalLock_lockTime' :
> "j['serverStatus']['globalLock']['lockTime']"

A literal string that happens to have j in it has nothing at all to do 
with the j that you got from json.

>                  'globalLock_currentQueue_total' =
> "j['serverStatus']['globalLock']['currentQueue']['total']"
>                  'globalLock_currentQueue_readers' =
> "j['serverStatus']['globalLock']['currentQueue']['readers']"
>                  'globalLock_currentQueue_writers' =
> "j['serverStatus']['globalLock']['currentQueue']['writers']"
>                  'mem_bits' = "j['serverStatus']['mem']['bits']"
>                  'mem_resident' = "j['serverStatus']['mem']['resident']"
>                  'mem_virtual' = "j['serverStatus']['mem']['virtual']"
>                  'connections_current' =
> "j['serverStatus']['connections']['current']"
>                  'connections_available' =
> "j['serverStatus']['connections']['available']"
>                  'extra_info_heap_usage' =
> round(("j['serverStatus']['extra_info']['heap_usage_bytes'])/(1024*124), 2)"
>                  'extra_info_page_faults' =
> "j['serverStatus']['extra_info']['page_faults']"
>                  'indexCounters_btree_accesses' =
> "j['serverStatus']['indexCounters']['btree']['accesses']"
>                  'indexCounters_btree_hits' =
> "j['serverStatus']['indexCounters']['btree']['hits']"
>                  'indexCounters_btree_misses' =
> "j['serverStatus']['indexCounters']['btree']['misses']"
>                  'indexCounters_btree_resets' =
> "j['serverStatus']['indexCounters']['btree']['resets']"
>                  'indexCounters_btree_missRatio' =
> "j['serverStatus']['indexCounters']['btree']['missRatio']"
>                  'backgroundFlushing_flushes' =
> "j['serverStatus']['backgroundFlushing']['flushes']"
>                  'backgroundFlushing_total_ms' =
> "j['serverStatus']['backgroundFlushing']['total_ms']"
>                  'backgroundFlushing_average_ms' =
> "j['serverStatus']['backgroundFlushing']['average_ms']"
>                  'backgroundFlushing_last_ms' =
> "j['serverStatus']['backgroundFlushing']['last_ms']"
>                  'cursors_totalOpen' =
> "j['serverStatus']['cursors']['totalOpen']"
>                  'cursors_clientCursors_size' =
> "j['serverStatus']['cursors']['clientCursors_size']"
>                  'cursors_timedOut' =
> "j['serverStatus']['cursors']['timedOut']"
>                  'opcounters_insert' =
> "j['serverStatus']['opcounters']['insert']"
>                  'opcounters_query' =
> "j['serverStatus']['opcounters']['query']"
>                  'opcounters_update' =
> "j['serverStatus']['opcounters']['update']"
>                  'opcounters_delete' =
> "j['serverStatus']['opcounters']['delete']"
>                  'opcounters_getmore' =
> "j['serverStatus']['opcounters']['getmore']"
>                  'opcounters_command' =
> ['server_status']['opcounters']['command']""
>                  'asserts_regular' =
> "j['serverStatus']['asserts']['regular']"
>                  'asserts_warning' =
> "j['serverStatus']['asserts']['warning']"
>                  'asserts_msg' = "j['serverStatus']['asserts']['msg']"
>                  'asserts_user' = "j['serverStatus']['asserts']['user']"
>                  'asserts_rollovers' =
> "j['serverStatus']['asserts']['rollovers']"
>                  'network_inbound_traffic_mb' =
> ("j['serverStatus']['network']['bytesIn'])/(1024*1024)"
>                  'network_outbound_traffic_mb' =
> ("j['serverStatus']['network']['bytesOut'])/(1024*1024)"
>                  'network_requests' =
> "j['serverStatus']['network']['numRequests']"
>                  'write_backs_queued' =
> "j['serverStatus']['writeBacksQueued']"
>                  'logging_commits' = "j['serverStatus']['dur']['commits']"
>                  'logging_journal_writes_mb' =
> "j['serverStatus']['dur']['journaledMB']"
>                  'logging_datafile_writes_mb' =
> "j['serverStatus']['dur']['writeToDataFilesMB']"
>                  'logging_commits_in_writelock' =
> "j['serverStatus']['dur']['commitsInWriteLock']"
>                  'logging_early_commits' =
> "j['serverStatus']['dur']['earlyCommits']"
>                  'logging_log_buffer_prep_time_ms' =
> "j['serverStatus']['dur']['timeMs']['prepLogBuffer']"
>                  'logging_journal_write_time_ms' =
> "j['serverStatus']['dur']['timeMs']['writeToJournal']"
>                  'logging_datafile_write_time_ms' =
> "j['serverStatus']['dur']['timeMs']['writeToDataFiles']"
> }
>
> for command in commands:
>      if arg in commands:
>          print commands[command]
>      else:
>          print 'Invalid command'

The above loop makes no sense at all for several reasons.  I'd be amazed 
if it happens to produce the output you show below.  Please use 
copy/paste to show us the code you're actually running.

>
>
> Below the output:
> (danilochilene at notebico - ~/lixo @14:06:56)
> 2: python mongo-test.py uptime
> j['serverStatus']['uptime']
>
> (danilochilene at notebico - ~/lixo @14:07:00)
> 2: python -i mongo-test.py uptime
> j['serverStatus']['uptime']
>>>> j['serverStatus']['uptime']
> 27806
>>>>
>
> My only issue now is commands[command] (as the example above) have the same
> output as j['serverStatus']['uptime'].
>

commands[command] is produced from a literal string.  If you want it to 
be an int 27806, you could type that literal instead.

commands = {
                   'uptime' : 27806

Or perhaps you could do

commands = {
                  'uptime' : j['serverStatus']['uptime']

if the values in j are already set up before you initialize the dict 
commands.

> Thanks for the help so far!
>


-- 
DaveA

From alan.gauld at btinternet.com  Thu Apr 18 19:52:01 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Thu, 18 Apr 2013 18:52:01 +0100
Subject: [Tutor] Fwd: Sys.argv read parameters
In-Reply-To: <CA+_2i1TfDMLr5wRQ=nwAMEJY87rKJFQTK=zQ12qM3egosVzOxg@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
	<CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
	<CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>
	<516F2E7A.2020503@davea.name>
	<CA+_2i1SY=xb43bX+GXjbD3mm6bp-ayeQD4QWe7wweFdMbHem3w@mail.gmail.com>
	<516FF5CC.3060904@davea.name>
	<CA+_2i1TfDMLr5wRQ=nwAMEJY87rKJFQTK=zQ12qM3egosVzOxg@mail.gmail.com>
Message-ID: <kkpbrt$4lk$1@ger.gmane.org>

On 18/04/13 18:14, Danilo Chilene wrote:

> for command in commands:
>      if arg in commands:
>          print commands[command]
>      else:
>          print 'Invalid command'

I don't understand what you are doing here? Its almost a random 
selection mechanism? You print the command for every item in commands if 
arg is in commands and Invalid Command for every command if its not?
Whatever its trying to do its massively inefficient.

I thought you'd have wanted something like

  for command in commands:
       if arg == command:
           print commands[command]
       else:
           print 'Invalid command'

Which is roughly equivalent to:

print commands.get(arg, 'Invalid command')

but much less efficient!


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


From bicofino at gmail.com  Thu Apr 18 20:23:18 2013
From: bicofino at gmail.com (Danilo Chilene)
Date: Thu, 18 Apr 2013 15:23:18 -0300
Subject: [Tutor] Fwd: Sys.argv read parameters
In-Reply-To: <kkpbrt$4lk$1@ger.gmane.org>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
	<CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
	<CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>
	<516F2E7A.2020503@davea.name>
	<CA+_2i1SY=xb43bX+GXjbD3mm6bp-ayeQD4QWe7wweFdMbHem3w@mail.gmail.com>
	<516FF5CC.3060904@davea.name>
	<CA+_2i1TfDMLr5wRQ=nwAMEJY87rKJFQTK=zQ12qM3egosVzOxg@mail.gmail.com>
	<kkpbrt$4lk$1@ger.gmane.org>
Message-ID: <CA+_2i1TyA=--RCTyW7Mgt4VdJLGUfCcZ1w-QqV09spWvoJMLeA@mail.gmail.com>

On Thu, Apr 18, 2013 at 2:52 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> On 18/04/13 18:14, Danilo Chilene wrote:
>
>  for command in commands:
>>      if arg in commands:
>>          print commands[command]
>>      else:
>>          print 'Invalid command'
>>
>
> I don't understand what you are doing here? Its almost a random selection
> mechanism? You print the command for every item in commands if arg is in
> commands and Invalid Command for every command if its not?
> Whatever its trying to do its massively inefficient.
>
> I thought you'd have wanted something like
>
>  for command in commands:
>       if arg == command:
>
>           print commands[command]
>       else:
>           print 'Invalid command'
>
> Which is roughly equivalent to:
>
> print commands.get(arg, 'Invalid command')
>
> but much less efficient!

Hi Alan,

Yes, I was doing it the wrong way.


>
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130418/43b1082d/attachment.html>

From dyoo at hashcollision.org  Thu Apr 18 21:10:02 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Thu, 18 Apr 2013 13:10:02 -0600
Subject: [Tutor] Fwd: Sys.argv read parameters
In-Reply-To: <CA+_2i1TfDMLr5wRQ=nwAMEJY87rKJFQTK=zQ12qM3egosVzOxg@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
	<CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
	<CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>
	<516F2E7A.2020503@davea.name>
	<CA+_2i1SY=xb43bX+GXjbD3mm6bp-ayeQD4QWe7wweFdMbHem3w@mail.gmail.com>
	<516FF5CC.3060904@davea.name>
	<CA+_2i1TfDMLr5wRQ=nwAMEJY87rKJFQTK=zQ12qM3egosVzOxg@mail.gmail.com>
Message-ID: <CAGZAPF7_5xMa5CxcfD7QV1987at1nEPPq+nrwB+g81JUtV-vCQ@mail.gmail.com>

Ok, good.  This is _much_ more realistic code, and demonstrates why
seeing context is important.


My suggestion to do it computationally is totally invalid here.  :P
There's a lot of variation here, due to the access paths through the
JSON that you're walking.  You're essentially defining a very
lightweight domain-specific language, technically.  The semantics of
the commands appear to be: walk the JSON of a certain path.  A
dispatch table here is _very_ appropriate.

The values in your dispatch table, however, should not be literal code
that you want to evaluate: rather, they should just hold an inert
path.  The act of using the dispatch table should take a path and then
apply it to the JSON in question.

(I am trying _very_ hard not to say the word "eval" here, because it's
just dangerous in this context.)

Here's what the interpretation part of your language might looks like:

#####################################################################
def p(*elts):
    """Construct a representation of a path.
    (We'll cheat a little by using a list of strings.)"""
    return elts

commands = {
    'uptime' : p('serverStatus', 'uptime'),
    'globalLock_lockTime' : p('serverStatus', 'globalLock', 'lockTime')
    ## Fill me in with more elements.
}

def lookup(data, cmdName):
    path = commands[cmdName]
    for p in path:
        data = data[p]
    return data

## For example, let's mock up some sample data and see how this works.

sampleData = {'serverStatus' : {'uptime': 3,
                                'cpu load' : 1.11,
                                'globalLock' : { 'lockName' : 'sample
lock name',
                                                 'lockTime' : 42 }}}
print lookup(sampleData, 'uptime')
print lookup(sampleData, 'globalLock_lockTime')
#####################################################################


You should be able to see how to extend this to your realistic
example: just add more entries in your command.  Note that I'm using a
function p() to construct the path: that's just for my own
convenience: you might be able to just strip it out and inline the
paths directly into the table.

(But having p there enables maintenance: we might need to extend the
system to do more than path lookup later on, in which case redefining
p makes it easy to change the representation of paths by modifying a
single place.)

From dyoo at hashcollision.org  Thu Apr 18 21:16:25 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Thu, 18 Apr 2013 13:16:25 -0600
Subject: [Tutor] Fwd: Sys.argv read parameters
In-Reply-To: <CAGZAPF7_5xMa5CxcfD7QV1987at1nEPPq+nrwB+g81JUtV-vCQ@mail.gmail.com>
References: <CA+_2i1RzWSZUrRKdupCC+1=nFEyosr_wDa0Zad=hTKgXHh6M0A@mail.gmail.com>
	<CAGZAPF6_3d+eYtw-u+LRBbOgLXc+R2TPP8GPWaKNsTsx0uojPg@mail.gmail.com>
	<CA+_2i1RdpuC5fKpzrCmkQrrneSYOxwpTNBW2--9G+1XZWBwOFw@mail.gmail.com>
	<CAGZAPF7CnDSQDB6FwvJYZSrrnj2pmiknX+9pzPZqcu6+gHtuxw@mail.gmail.com>
	<516F2E7A.2020503@davea.name>
	<CA+_2i1SY=xb43bX+GXjbD3mm6bp-ayeQD4QWe7wweFdMbHem3w@mail.gmail.com>
	<516FF5CC.3060904@davea.name>
	<CA+_2i1TfDMLr5wRQ=nwAMEJY87rKJFQTK=zQ12qM3egosVzOxg@mail.gmail.com>
	<CAGZAPF7_5xMa5CxcfD7QV1987at1nEPPq+nrwB+g81JUtV-vCQ@mail.gmail.com>
Message-ID: <CAGZAPF5M+4kveuBahB-yaXfoqFjmRAgJWfYYXoQ8RRWYnQabmQ@mail.gmail.com>

Followup: compare the previous interpreter code with this revision:

    https://gist.github.com/dyoo/5415464

and you'll see how it becomes easier now to add new command types into
the system.

From eryksun at gmail.com  Thu Apr 18 21:22:19 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 18 Apr 2013 15:22:19 -0400
Subject: [Tutor] path directory backslash ending
In-Reply-To: <CALRAYNVKoX3MN9wTspWdCVN+1dvPmSgPjKeDfNQBZWvPo85SEw@mail.gmail.com>
References: <CALRAYNVKoX3MN9wTspWdCVN+1dvPmSgPjKeDfNQBZWvPo85SEw@mail.gmail.com>
Message-ID: <CACL+1auv3RpDmJKmWoqAiyRA4nStN6EJvCokqm=rLBRrA1TWSA@mail.gmail.com>

On Thu, Apr 18, 2013 at 12:45 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> Minor question. I was adding the Py Script directory to the Win 7
> Path, and noticed that Python33 ends with a backslash but many
> directories do not. Is there a difference? Should I use backslash or
> not preferentially, or doesn't it matter at all? It does seem odd that
> there's no convention for this.

The trailing backslash shouldn't directly matter in the PATH variable,
not as far how the system splits the string on ';' and searches the
directories. It may be an issue with escaping if "%PATH%" is passed as
a quoted argument. We can test this to be sure. Create test.py:

    import sys
    print(sys.argv[1:])

Now try an example. First without quotes:

    C:\>test.py C:\Program Files;C:\Python33\
    ['C:\\Program', 'Files;C:\\Python33\\']

Obviously the C runtime (not the shell, as would be the case on a
POSIX system)  needs a little help parsing the argument string. We'll
add some quotes around it:

    C:\>test.py "C:\Program Files;C:\Python33\"
    ['C:\\Program Files;C:\\Python33"']

Ack! The trailing backslash was treated as an escape character, so we
end up with a trailing double quote. It works fine if you remove the
trailing backslash:

    C:\>test.py "C:\Program Files;C:\Python33"
    ['C:\\Program Files;C:\\Python33']

OK, so IMHO don't use a trailing backslash.

It's also a convention to not use a trailing backslash in directories
set as environment variables. For example:

    C:\>echo %ProgramFiles%
    C:\Program Files

This makes it look more natural as part of another path:

    C:\>dir /b "%ProgramFiles%\Microsoft SDKs\Windows\v7.0A"
    bin
    Include
    Lib

Note that the shell replaces %ProgramFiles% literally with C:\Program
Files, so quotes are required.

From cybervigilante at gmail.com  Fri Apr 19 02:51:01 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Thu, 18 Apr 2013 17:51:01 -0700
Subject: [Tutor] path directory backslash ending
In-Reply-To: <CACL+1auv3RpDmJKmWoqAiyRA4nStN6EJvCokqm=rLBRrA1TWSA@mail.gmail.com>
References: <CALRAYNVKoX3MN9wTspWdCVN+1dvPmSgPjKeDfNQBZWvPo85SEw@mail.gmail.com>
	<CACL+1auv3RpDmJKmWoqAiyRA4nStN6EJvCokqm=rLBRrA1TWSA@mail.gmail.com>
Message-ID: <CALRAYNWPLxqw=vbGSPqHcNmB_Dk2B3p84A15XUqs_kUnYdpVjg@mail.gmail.com>

Well, under the principle of least  harm, it appears that since the
trailing backslash causes no harm if omitted, but sometimes does if
allowed, I removed them all.

But that's in win 7. Is it okay to always omit them in Linux? Python33
is itself installed with a trailing backslash, so I figured this was a
Linux habit.

An entirely different question as long as I'm here. I have a local
wamp server with mysql and phpadmin for php so I can test web pages
locally. What's the equivalent for Python?

Jim

From sayanchatterjee at gmail.com  Fri Apr 19 13:44:17 2013
From: sayanchatterjee at gmail.com (Sayan Chatterjee)
Date: Fri, 19 Apr 2013 17:14:17 +0530
Subject: [Tutor] Python Script: Downloading Youtube videos by search result
Message-ID: <CAAT-4OROOdx04Vk2uq-iggCD-SOge+1dBuHcG0Tuy4ovMWtEyw@mail.gmail.com>

Dear All,

I want to download some music from youtube.There are already marvellous
python scripts like youtube-dl which downloads videos and playlists from
numerous sites,but what I want to do is to download videos from youtube
with a search string. The user will give a search string, and the script
will download first 20(say) videos from the youtube.The script will use
youtube-dl on the backend and avconv tool for video to MP3 conversion etc.

How should I proceed to make such a script. I am a newbie in Python but I
am sure with your guidance I can pick it up quite fast. :)

Cheers,
Sayan
-- 


--------------------------------------------------------------------------
*Sayan  Chatterjee*
Dept. of Physics and Meteorology
IIT Kharagpur
Lal Bahadur Shastry Hall of Residence
Room AB 205
Mob: +91 9874513565
blog: www.blissprofound.blogspot.com

Volunteer , Padakshep
www.padakshep.org
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130419/37ee598f/attachment.html>

From eryksun at gmail.com  Fri Apr 19 15:53:48 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 19 Apr 2013 09:53:48 -0400
Subject: [Tutor] path directory backslash ending
In-Reply-To: <CALRAYNWPLxqw=vbGSPqHcNmB_Dk2B3p84A15XUqs_kUnYdpVjg@mail.gmail.com>
References: <CALRAYNVKoX3MN9wTspWdCVN+1dvPmSgPjKeDfNQBZWvPo85SEw@mail.gmail.com>
	<CACL+1auv3RpDmJKmWoqAiyRA4nStN6EJvCokqm=rLBRrA1TWSA@mail.gmail.com>
	<CALRAYNWPLxqw=vbGSPqHcNmB_Dk2B3p84A15XUqs_kUnYdpVjg@mail.gmail.com>
Message-ID: <CACL+1atfTpZ7utQy-1DgEqmZzp56cTTRwhxk9nMcQc4W3GkgUA@mail.gmail.com>

On Thu, Apr 18, 2013 at 8:51 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> But that's in win 7. Is it okay to always omit them in Linux? Python33
> is itself installed with a trailing backslash, so I figured this was a
> Linux habit.

POSIX/Linux uses a forward slash instead of a backslash (py: os.sep),
and the delimiter in PATH is a colon instead of a semicolon (py:
os.pathsep). There's no convention I know of to use trailing slashes.

You might also consider using the PEP 405 "venv" module:

http://www.python.org/dev/peps/pep-0405

When you "activate" the environment it prepends the "Scripts" (or
"bin") directory to PATH. The option "--symlinks" requires an elevated
security token on Windows, but just to create the virtual environment.
If you'd rather copy over the required DLLs, there's a "--upgrade"
option for when you upgrade to Python 3.4, etc.

> An entirely different question as long as I'm here. I have a local
> wamp server with mysql and phpadmin for php so I can test web pages
> locally. What's the equivalent for Python?

Here's a sampling of links. Hopefully a web developer will provide a
more detailed answer.

mod_wsgi
http://code.google.com/p/modwsgi
http://code.google.com/p/modwsgi/wiki/InstallationOnWindows

The wiki has several integration guides for popular frameworks.

mod_wsgi Windows binaries:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#mod_wsgi

Python Web Server Gateway Interface v1.0.1
http://www.python.org/dev/peps/pep-3333

From fahraynk at gmail.com  Fri Apr 19 16:49:38 2013
From: fahraynk at gmail.com (Frank Schiro)
Date: Fri, 19 Apr 2013 10:49:38 -0400
Subject: [Tutor] hard time importing a module
Message-ID: <CA+QG++EDiGTaEoQLWiKnfHOb0vdmwZP4ZcYGmoAT3OJd5qzzQQ@mail.gmail.com>

hi I have a question about modules ...

Im trying to use a 3rd party module called pywinatuo. It said I had to
install 2 other modules. 1 was called sendkeys.py, the other was ctypes.
Ctypes was included in the python library I had, but sendkeys was not.

After I found SendKeys, I put it in a directory I found in sys.path, and
then type import SendKeys. I got an error because sendkeys was trying to
import from another file called _sendkeys. After searching I found
_sendkeys, but it is .c

I know that you can somehow extend python with c from reading this article
: http://docs.python.org/2/extending/extending.html

But... how do I get the interpreter to recognize the _sendkeys.c file when
sendkeys.py trys to import it ? I get errors right away since c uses * to
comment so python doesnt recognize it and errors on all of the comments
from _sendkeys.c

Basically how do I correctly import this module that doesnt have a setup.py
?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130419/9ab3e673/attachment.html>

From oscar.j.benjamin at gmail.com  Fri Apr 19 17:12:36 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Fri, 19 Apr 2013 16:12:36 +0100
Subject: [Tutor] hard time importing a module
In-Reply-To: <CA+QG++EDiGTaEoQLWiKnfHOb0vdmwZP4ZcYGmoAT3OJd5qzzQQ@mail.gmail.com>
References: <CA+QG++EDiGTaEoQLWiKnfHOb0vdmwZP4ZcYGmoAT3OJd5qzzQQ@mail.gmail.com>
Message-ID: <CAHVvXxRbnYTyQ=C_1y9WetEDqjhd7=yOcVNKHTc5XdQitEc-Ow@mail.gmail.com>

On 19 April 2013 15:49, Frank Schiro <fahraynk at gmail.com> wrote:
> hi I have a question about modules ...
>
> Im trying to use a 3rd party module called pywinatuo. It said I had to
> install 2 other modules. 1 was called sendkeys.py, the other was ctypes.
> Ctypes was included in the python library I had, but sendkeys was not.
>
> After I found SendKeys, I put it in a directory I found in sys.path, and
> then type import SendKeys. I got an error because sendkeys was trying to
> import from another file called _sendkeys. After searching I found
> _sendkeys, but it is .c

Did these files also come with a file called setup.py?

Normally, a Python module is not installed by manually copying the
files to the appropriate places but by running 'python setup.py
install' in the terminal. This will compile any C code and copy files
to the appropriate places. Note that you will need to have separately
installed a C compiler to be able to compile C code.


>
> I know that you can somehow extend python with c from reading this article :
> http://docs.python.org/2/extending/extending.html

Try reading this one instead:
http://docs.python.org/2/install/index.html

>
> But... how do I get the interpreter to recognize the _sendkeys.c file when
> sendkeys.py trys to import it ? I get errors right away since c uses * to
> comment so python doesnt recognize it and errors on all of the comments from
> _sendkeys.c

Yeah, that won't work. C code needs to be compiled by a C compiler, not Python.

>
> Basically how do I correctly import this module that doesnt have a setup.py
> ?

Oh okay, no setup.py. Where did you get this from? What does it have?
Is there a Makefile or something?


Oscar

From eryksun at gmail.com  Fri Apr 19 17:39:57 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 19 Apr 2013 11:39:57 -0400
Subject: [Tutor] hard time importing a module
In-Reply-To: <CAHVvXxRbnYTyQ=C_1y9WetEDqjhd7=yOcVNKHTc5XdQitEc-Ow@mail.gmail.com>
References: <CA+QG++EDiGTaEoQLWiKnfHOb0vdmwZP4ZcYGmoAT3OJd5qzzQQ@mail.gmail.com>
	<CAHVvXxRbnYTyQ=C_1y9WetEDqjhd7=yOcVNKHTc5XdQitEc-Ow@mail.gmail.com>
Message-ID: <CACL+1avTpe628B0CLAxzbn-1BJwSsXEO0QQCw4AjUUZO3ABBQA@mail.gmail.com>

On Fri, Apr 19, 2013 at 11:12 AM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> Did these files also come with a file called setup.py?
>
> Normally, a Python module is not installed by manually copying the
> files to the appropriate places but by running 'python setup.py
> install' in the terminal. This will compile any C code and copy files
> to the appropriate places. Note that you will need to have separately
> installed a C compiler to be able to compile C code.

I think this is the SendKeys module in question:

http://web.archive.org/web/20121002234104/http://www.rutherfurd.net/python/sendkeys

You can get the zipped source from archive.org above, along with
binaries for 2.1-2.6. The source  has a setup.py, but as Oscar said
already you'll need a C compiler. You can use Visual Studio 2008 to
compile it for 2.6/2.7. There are direct links for VS 2008 Express
edition (free as in beer) in this SO answer:

http://stackoverflow.com/a/14979612/205580

Or use MinGW-w64 if you prefer since the source isn't C++:

http://mingw-w64.sourceforge.net/

There's also a binary installer for 2.7 here, courtesy of Christoph Gohlke:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys

From mail at timgolden.me.uk  Fri Apr 19 17:52:39 2013
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 19 Apr 2013 16:52:39 +0100
Subject: [Tutor] hard time importing a module
In-Reply-To: <CACL+1avTpe628B0CLAxzbn-1BJwSsXEO0QQCw4AjUUZO3ABBQA@mail.gmail.com>
References: <CA+QG++EDiGTaEoQLWiKnfHOb0vdmwZP4ZcYGmoAT3OJd5qzzQQ@mail.gmail.com>
	<CAHVvXxRbnYTyQ=C_1y9WetEDqjhd7=yOcVNKHTc5XdQitEc-Ow@mail.gmail.com>
	<CACL+1avTpe628B0CLAxzbn-1BJwSsXEO0QQCw4AjUUZO3ABBQA@mail.gmail.com>
Message-ID: <51716847.9070305@timgolden.me.uk>

On 19/04/2013 16:39, eryksun wrote:
> On Fri, Apr 19, 2013 at 11:12 AM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>> Did these files also come with a file called setup.py?
>>
>> Normally, a Python module is not installed by manually copying the
>> files to the appropriate places but by running 'python setup.py
>> install' in the terminal. This will compile any C code and copy files
>> to the appropriate places. Note that you will need to have separately
>> installed a C compiler to be able to compile C code.
> 
> I think this is the SendKeys module in question:
> 
> http://web.archive.org/web/20121002234104/http://www.rutherfurd.net/python/sendkeys
> 
> You can get the zipped source from archive.org above, along with
> binaries for 2.1-2.6. The source  has a setup.py, but as Oscar said
> already you'll need a C compiler. You can use Visual Studio 2008 to
> compile it for 2.6/2.7. There are direct links for VS 2008 Express
> edition (free as in beer) in this SO answer:

As usual, the excellent  Christoph Gohlke has provided binaries for a
range of targets:

  http://www.lfd.uci.edu/~gohlke/pythonlibs/

TJG

From breamoreboy at yahoo.co.uk  Fri Apr 19 18:00:55 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Fri, 19 Apr 2013 17:00:55 +0100
Subject: [Tutor] hard time importing a module
In-Reply-To: <CACL+1avTpe628B0CLAxzbn-1BJwSsXEO0QQCw4AjUUZO3ABBQA@mail.gmail.com>
References: <CA+QG++EDiGTaEoQLWiKnfHOb0vdmwZP4ZcYGmoAT3OJd5qzzQQ@mail.gmail.com>
	<CAHVvXxRbnYTyQ=C_1y9WetEDqjhd7=yOcVNKHTc5XdQitEc-Ow@mail.gmail.com>
	<CACL+1avTpe628B0CLAxzbn-1BJwSsXEO0QQCw4AjUUZO3ABBQA@mail.gmail.com>
Message-ID: <kkrpno$qpm$1@ger.gmane.org>

On 19/04/2013 16:39, eryksun wrote:
> On Fri, Apr 19, 2013 at 11:12 AM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>> Did these files also come with a file called setup.py?
>>
>> Normally, a Python module is not installed by manually copying the
>> files to the appropriate places but by running 'python setup.py
>> install' in the terminal. This will compile any C code and copy files
>> to the appropriate places. Note that you will need to have separately
>> installed a C compiler to be able to compile C code.
>
> I think this is the SendKeys module in question:
>
> http://web.archive.org/web/20121002234104/http://www.rutherfurd.net/python/sendkeys
>
> You can get the zipped source from archive.org above, along with
> binaries for 2.1-2.6. The source  has a setup.py, but as Oscar said
> already you'll need a C compiler. You can use Visual Studio 2008 to
> compile it for 2.6/2.7. There are direct links for VS 2008 Express
> edition (free as in beer) in this SO answer:
>
> http://stackoverflow.com/a/14979612/205580
>
> Or use MinGW-w64 if you prefer since the source isn't C++:
>
> http://mingw-w64.sourceforge.net/
>
> There's also a binary installer for 2.7 here, courtesy of Christoph Gohlke:
>
> http://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

At least two variants on sendkeys are here on stackoverflow if none of 
the above work out http://tinyurl.com/cuwdhjk

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From eryksun at gmail.com  Fri Apr 19 18:12:09 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 19 Apr 2013 12:12:09 -0400
Subject: [Tutor] hard time importing a module
In-Reply-To: <51716847.9070305@timgolden.me.uk>
References: <CA+QG++EDiGTaEoQLWiKnfHOb0vdmwZP4ZcYGmoAT3OJd5qzzQQ@mail.gmail.com>
	<CAHVvXxRbnYTyQ=C_1y9WetEDqjhd7=yOcVNKHTc5XdQitEc-Ow@mail.gmail.com>
	<CACL+1avTpe628B0CLAxzbn-1BJwSsXEO0QQCw4AjUUZO3ABBQA@mail.gmail.com>
	<51716847.9070305@timgolden.me.uk>
Message-ID: <CACL+1atVOt0MfZ745iqAe9a6X08KpHUpP_d9mjU-WmK6Z6_UjQ@mail.gmail.com>

On Fri, Apr 19, 2013 at 11:52 AM, Tim Golden <mail at timgolden.me.uk> wrote:
> As usual, the excellent  Christoph Gohlke has provided binaries for a
> range of targets:
>
>   http://www.lfd.uci.edu/~gohlke/pythonlibs/

Maybe you missed the link at the end of my link fest:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys

From mail at timgolden.me.uk  Fri Apr 19 18:13:47 2013
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 19 Apr 2013 17:13:47 +0100
Subject: [Tutor] hard time importing a module
In-Reply-To: <CACL+1atVOt0MfZ745iqAe9a6X08KpHUpP_d9mjU-WmK6Z6_UjQ@mail.gmail.com>
References: <CA+QG++EDiGTaEoQLWiKnfHOb0vdmwZP4ZcYGmoAT3OJd5qzzQQ@mail.gmail.com>
	<CAHVvXxRbnYTyQ=C_1y9WetEDqjhd7=yOcVNKHTc5XdQitEc-Ow@mail.gmail.com>
	<CACL+1avTpe628B0CLAxzbn-1BJwSsXEO0QQCw4AjUUZO3ABBQA@mail.gmail.com>
	<51716847.9070305@timgolden.me.uk>
	<CACL+1atVOt0MfZ745iqAe9a6X08KpHUpP_d9mjU-WmK6Z6_UjQ@mail.gmail.com>
Message-ID: <51716D3B.8070203@timgolden.me.uk>

On 19/04/2013 17:12, eryksun wrote:
> On Fri, Apr 19, 2013 at 11:52 AM, Tim Golden <mail at timgolden.me.uk> wrote:
>> As usual, the excellent  Christoph Gohlke has provided binaries for a
>> range of targets:
>>
>>   http://www.lfd.uci.edu/~gohlke/pythonlibs/
> 
> Maybe you missed the link at the end of my link fest:
> 
> http://www.lfd.uci.edu/~gohlke/pythonlibs/#sendkeys
> 

Whoops. Quite right. Still, better twice than not at all ;)

TJG

From ramit.prasad at jpmorgan.com  Fri Apr 19 18:11:09 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Fri, 19 Apr 2013 16:11:09 +0000
Subject: [Tutor] Hello, and a newbie question
In-Reply-To: <CACL+1asWjAQ4sgV5R9hF_TAJVeGitqWsG3Sw_unS7mjCAjRzfA@mail.gmail.com>
References: <CACL+1asL5ayVy3xk7AOsM89e7bFOTArg1tAMRc9+d_Xmpx74mg@mail.gmail.com>
	<1366156656384.bcbb86a8@Nodemailer>
	<CACL+1asWjAQ4sgV5R9hF_TAJVeGitqWsG3Sw_unS7mjCAjRzfA@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF47418335202@SCACMX008.exchad.jpmchase.net>

eryksun wrote:
> On Tue, Apr 16, 2013 at 7:57 PM, Virgilio Rodriguez Jr
> <virgiliorodriguezjr at gmail.com> wrote:
> > Can someone please do me the favor and remove me from this god forsaken
> > email list I am sorry I signed up all it has done is taken over my phone and
> > rings all night long with emails I am not interested in any more because it
> > is just too many darn emails. I keep trying to log in and nothing it will
> > not let me unsubscribe and it is BS already.
> 
> You can get a password reminder here:
> http://mail.python.org/mailman/options/tutor
> 
> If you're sure that you have the correct password and still can't
> unsubscribe, then email the administrator, tutor-owner at python.org.
> Alan Gauld is active in this thread, BTW, in case you happen to have
> read the admin page where it says "Tutor list run by wescpy at
> gmail.com, alan.gauld at btinternet.com".

Or switch to digest mode which will email once a day with all the 
messages in it. Be glad you are not subscribed to the main Python 
mailing list as it is far more active than the tutor list. ;)


~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.  

From chetansaip at gmail.com  Fri Apr 19 22:56:50 2013
From: chetansaip at gmail.com (Chetan Sai)
Date: Fri, 19 Apr 2013 13:56:50 -0700
Subject: [Tutor] How to find reverse pair words in a list of Words that has
 to be accessed through a URL
Message-ID: <CABr0M0zSp4CymDNy8Yp7e2q8nmapgj17U1v9g=p1W1VMaPuHUg@mail.gmail.com>

*Here is my question:*
*
*
*"Two words are a ?reverse pair? if each is the reverse of the other. Write
a program that finds all the reverse pairs in the word list. The word list
can be downloaded athttp://www.puzzlers.org/pub/wordlists/pocket.txt"*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130419/e6a5c384/attachment.html>

From dfjennings at gmail.com  Fri Apr 19 23:05:12 2013
From: dfjennings at gmail.com (Don Jennings)
Date: Fri, 19 Apr 2013 17:05:12 -0400
Subject: [Tutor] How to find reverse pair words in a list of Words that
	has to be accessed through a URL
In-Reply-To: <CABr0M0zSp4CymDNy8Yp7e2q8nmapgj17U1v9g=p1W1VMaPuHUg@mail.gmail.com>
References: <CABr0M0zSp4CymDNy8Yp7e2q8nmapgj17U1v9g=p1W1VMaPuHUg@mail.gmail.com>
Message-ID: <6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com>


On Apr 19, 2013, at 4:56 PM, Chetan Sai wrote:

> Here is my question:
> 
> "Two words are a ?reverse pair? if each is the reverse of the other. Write a program that finds all the reverse pairs in the word list. The word list can be downloaded athttp://www.puzzlers.org/pub/wordlists/pocket.txt"

Really, that's not a question, but we are happy to answer questions :>) Oh, there's your question in the subject line. What have you tried thus far? Have you given any thought to what steps you might have to take to solve this task?

Take care,
Don


From chetansaip at gmail.com  Fri Apr 19 23:19:10 2013
From: chetansaip at gmail.com (Chetan Sai)
Date: Fri, 19 Apr 2013 14:19:10 -0700
Subject: [Tutor] How to find reverse pair words in a list of Words that
 has to be accessed through a URL
In-Reply-To: <6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com>
References: <CABr0M0zSp4CymDNy8Yp7e2q8nmapgj17U1v9g=p1W1VMaPuHUg@mail.gmail.com>
	<6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com>
Message-ID: <CABr0M0z73q6pgbB2kQ5usinw4=HPhcBKDjYanqPJtcHYO-xh-g@mail.gmail.com>

Hi Don

I'm a beginner in Python Programming.

I'm using python 3. I wrote a program that checks whether given two words
are reverse pair or not and outputs TRUE/FALSE.

*def reverse_pair(a,b):*
*    return list(a)==list(reversed(list(b)))*
*
*
*
*
But how to write a program that finds all the reverse pairs in the given
word list, eg: how to find the reverse pair words in a list of 20 words.
And that to how to access those list of words form a URL.

Because with the above code we can only find out whether the given 2 words
are reverse pair or not, that's it.

I'm thinking of using the below code which is written for Python 2.7.


 Code:

def reverse_pair(word_list, word):
    """Checks whether a reversed word appears in word_list.

    word_list: list of strings
    word: string
    """
    rev_word = word[::-1]
    return in_bisect(word_list, rev_word)


if __name__ == '__main__':
    word_list = make_word_list()

    for word in word_list:
        if reverse_pair(word_list, word): print word, word[::-1]



On Fri, Apr 19, 2013 at 2:05 PM, Don Jennings <dfjennings at gmail.com> wrote:

>
> On Apr 19, 2013, at 4:56 PM, Chetan Sai wrote:
>
> > Here is my question:
> >
> > "Two words are a ?reverse pair? if each is the reverse of the other.
> Write a program that finds all the reverse pairs in the word list. The word
> list can be downloaded athttp://www.puzzlers.org/pub/wordlists/pocket.txt"
>
> Really, that's not a question, but we are happy to answer questions :>)
> Oh, there's your question in the subject line. What have you tried thus
> far? Have you given any thought to what steps you might have to take to
> solve this task?
>
> Take care,
> Don
>
>


-- 
Thanks & Regards

Sai Chetan Pothula
408-203-3323


On Fri, Apr 19, 2013 at 2:05 PM, Don Jennings <dfjennings at gmail.com> wrote:

>
> On Apr 19, 2013, at 4:56 PM, Chetan Sai wrote:
>
> > Here is my question:
> >
> > "Two words are a ?reverse pair? if each is the reverse of the other.
> Write a program that finds all the reverse pairs in the word list. The word
> list can be downloaded athttp://www.puzzlers.org/pub/wordlists/pocket.txt"
>
> Really, that's not a question, but we are happy to answer questions :>)
> Oh, there's your question in the subject line. What have you tried thus
> far? Have you given any thought to what steps you might have to take to
> solve this task?
>
> Take care,
> Don
>
>


-- 
Thanks & Regards

Sai Chetan Pothula
408-203-3323
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130419/3b6e67df/attachment-0001.html>

From alan.gauld at btinternet.com  Sat Apr 20 00:07:50 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 19 Apr 2013 23:07:50 +0100
Subject: [Tutor] How to find reverse pair words in a list of Words that
 has to be accessed through a URL
In-Reply-To: <CABr0M0z73q6pgbB2kQ5usinw4=HPhcBKDjYanqPJtcHYO-xh-g@mail.gmail.com>
References: <CABr0M0zSp4CymDNy8Yp7e2q8nmapgj17U1v9g=p1W1VMaPuHUg@mail.gmail.com>
	<6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com>
	<CABr0M0z73q6pgbB2kQ5usinw4=HPhcBKDjYanqPJtcHYO-xh-g@mail.gmail.com>
Message-ID: <kksf7i$uk7$1@ger.gmane.org>

On 19/04/13 22:19, Chetan Sai wrote:

> I'm a beginner in Python Programming.

The language isn't really the issue here the issue is the algorithm.
So how would you do it manually with a paper and pen? (forget about 
fetching the list from the URL for now)

One possibility is to use sets (Python has a set data type).
create a set of words.
Now create a set of reversed words.
The intersection of those sets is the set of words which
also have a reversed pair.

print the intersection set.

just one way.

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


From emile at fenx.com  Sat Apr 20 00:16:52 2013
From: emile at fenx.com (emile)
Date: Fri, 19 Apr 2013 15:16:52 -0700
Subject: [Tutor] How to find reverse pair words in a list of Words that
 has to be accessed through a URL
In-Reply-To: <kksf7i$uk7$1@ger.gmane.org>
References: <CABr0M0zSp4CymDNy8Yp7e2q8nmapgj17U1v9g=p1W1VMaPuHUg@mail.gmail.com>
	<6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com>
	<CABr0M0z73q6pgbB2kQ5usinw4=HPhcBKDjYanqPJtcHYO-xh-g@mail.gmail.com>
	<kksf7i$uk7$1@ger.gmane.org>
Message-ID: <kksfoa$478$1@ger.gmane.org>

On 04/19/2013 03:07 PM, Alan Gauld wrote:
> On 19/04/13 22:19, Chetan Sai wrote:
>
>> I'm a beginner in Python Programming.
>
> The language isn't really the issue here the issue is the algorithm.
> So how would you do it manually with a paper and pen? (forget about
> fetching the list from the URL for now)
>
> One possibility is to use sets (Python has a set data type).
> create a set of words.
> Now create a set of reversed words.
> The intersection of those sets is the set of words which
> also have a reversed pair.
>
> print the intersection set.

The gotcha with this approach is the border case of self paired words 
that aren't pairs.  (pop,wow,mom,etc)

I got 94 distinct pairs.  Which is a better result than the 124.5 pairs 
I got the first pass through.

Emile




From amitsaha.in at gmail.com  Sat Apr 20 00:48:43 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Sat, 20 Apr 2013 08:48:43 +1000
Subject: [Tutor] Python Script: Downloading Youtube videos by search
	result
In-Reply-To: <CAAT-4OROOdx04Vk2uq-iggCD-SOge+1dBuHcG0Tuy4ovMWtEyw@mail.gmail.com>
References: <CAAT-4OROOdx04Vk2uq-iggCD-SOge+1dBuHcG0Tuy4ovMWtEyw@mail.gmail.com>
Message-ID: <CANODV3n55nccR-KAS99BWLoCUis6r9kn-iBmJZ7BeZCW612HDA@mail.gmail.com>

On Fri, Apr 19, 2013 at 9:44 PM, Sayan Chatterjee
<sayanchatterjee at gmail.com> wrote:
> Dear All,
>
> I want to download some music from youtube.There are already marvellous
> python scripts like youtube-dl which downloads videos and playlists from
> numerous sites,but what I want to do is to download videos from youtube with
> a search string. The user will give a search string, and the script will
> download first 20(say) videos from the youtube.The script will use
> youtube-dl on the backend and avconv tool for video to MP3 conversion etc.
>
> How should I proceed to make such a script. I am a newbie in Python but I am
> sure with your guidance I can pick it up quite fast. :)

May be take a look at the YouTube Data API? [1] Hopefully, the Getting
Started section will help you [2].

[1] https://developers.google.com/youtube/1.0/developers_guide_python#SearchingVideos

[2] https://developers.google.com/youtube/1.0/developers_guide_python#GettingStarted

Best,
Amit.

--
http://amitsaha.github.com/

From alan.gauld at btinternet.com  Sat Apr 20 01:57:07 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 20 Apr 2013 00:57:07 +0100
Subject: [Tutor] How to find reverse pair words in a list of Words that
 has to be accessed through a URL
In-Reply-To: <kksfoa$478$1@ger.gmane.org>
References: <CABr0M0zSp4CymDNy8Yp7e2q8nmapgj17U1v9g=p1W1VMaPuHUg@mail.gmail.com>
	<6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com>
	<CABr0M0z73q6pgbB2kQ5usinw4=HPhcBKDjYanqPJtcHYO-xh-g@mail.gmail.com>
	<kksf7i$uk7$1@ger.gmane.org> <kksfoa$478$1@ger.gmane.org>
Message-ID: <kkslkf$o2m$1@ger.gmane.org>

On 19/04/13 23:16, emile wrote:

> The gotcha with this approach is the border case of self paired words
> that aren't pairs.  (pop,wow,mom,etc)

yeah, but those exceptions are easy to catch as you generate the 
reversed list:

if reversed(word) == word

And its a bit of a moot point whether you should
perhaps count a palindromic word as a pair of itself...


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


From steve at pearwood.info  Sat Apr 20 02:48:31 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 20 Apr 2013 10:48:31 +1000
Subject: [Tutor] How to find reverse pair words in a list of Words that
 has to be accessed through a URL
In-Reply-To: <kkslkf$o2m$1@ger.gmane.org>
References: <CABr0M0zSp4CymDNy8Yp7e2q8nmapgj17U1v9g=p1W1VMaPuHUg@mail.gmail.com>
	<6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com>
	<CABr0M0z73q6pgbB2kQ5usinw4=HPhcBKDjYanqPJtcHYO-xh-g@mail.gmail.com>
	<kksf7i$uk7$1@ger.gmane.org> <kksfoa$478$1@ger.gmane.org>
	<kkslkf$o2m$1@ger.gmane.org>
Message-ID: <5171E5DF.5000007@pearwood.info>

On 20/04/13 09:57, Alan Gauld wrote:
> On 19/04/13 23:16, emile wrote:
>
>> The gotcha with this approach is the border case of self paired words
>> that aren't pairs.  (pop,wow,mom,etc)
>
> yeah, but those exceptions are easy to catch as you generate the reversed list:
>
> if reversed(word) == word


An easy mistake to make, but reversed() returns an iterator which will only
compare equal to itself:

py> reversed("abc")
<reversed object at 0xb7ea256c>


You need to convert the reversed object back into a string:

py> "".join(reversed("abc"))
'cba'


But the best way to reverse a string is with a slice:

py> 'abc'[::-1]
'cba'


The syntax is a little obscure, but "slicing" takes between 0 and 3 arguments,
written inside square brackets [ ] and separated by colons. The full form of a
slice is:

string[start:end:step]

where start defaults to the beginning of the string, end defaults to the end of
the string, and step defaults to 1. If step is 1, you can leave it out:

string[start:end]

otherwise you need to include colons to mark the missing values:

string[2::3]

says to return a slice of the string, starting at character 2, going to the end,
and taking every third character. (Remember that counting starts at 0 in Python,
not 1, so character 2 is the *third* character.)

py> "python is cool"[2::3]
'tnso'


A negative step goes backwards, so a fast and efficient way to reverse a string
or other sequence is to use slice it using [::-1].



> And its a bit of a moot point whether you should
> perhaps count a palindromic word as a pair of itself...

That word you use, I do not think it means what you think it means, to quote
the Spaniard.

A moot point is a point which is not relevant. If your house has just been
flattened by a hurricane, it is a moot point whether or not you left the front
door unlocked. I think it is quite relevant whether or not palindromes should
count or not.



-- 
Steven

From alan.gauld at btinternet.com  Sat Apr 20 03:17:22 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 20 Apr 2013 02:17:22 +0100
Subject: [Tutor] How to find reverse pair words in a list of Words that
 has to be accessed through a URL
In-Reply-To: <5171E5DF.5000007@pearwood.info>
References: <CABr0M0zSp4CymDNy8Yp7e2q8nmapgj17U1v9g=p1W1VMaPuHUg@mail.gmail.com>
	<6D403979-81A8-48F8-9B6D-E449B3ADD083@gmail.com>
	<CABr0M0z73q6pgbB2kQ5usinw4=HPhcBKDjYanqPJtcHYO-xh-g@mail.gmail.com>
	<kksf7i$uk7$1@ger.gmane.org> <kksfoa$478$1@ger.gmane.org>
	<kkslkf$o2m$1@ger.gmane.org> <5171E5DF.5000007@pearwood.info>
Message-ID: <kksqau$ttp$1@ger.gmane.org>

On 20/04/13 01:48, Steven D'Aprano wrote:

> A moot point is a point which is not relevant.

It most certainly is not. It is a point that is open to debate.
Specifically it is a point that would be posted on the agenda
for the weekly meetings in the local Moot Hall - the town
guild/council's meeting place in medieval times.

There are several towns in England where Moot Halls still
exist and a few still have ceremonial Moot meetings where
topics of local interest are occasionally debated.

A fine example of a Moot Hall is in Aldeburgh in Suffolk:

http://en.wikipedia.org/wiki/Aldeburgh

[ And it must never, ever, be spelled a *mute* point - something
that bugs me constantly since it infers almost the opposite
of the real meaning! ]

PS.
On the subject of reversed() you are quite right although I wasn't 
thinking of python at the time I wrote it I was just indicating
the algorithmic fix required to filter the palindromes.

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


From fomcl at yahoo.com  Sat Apr 20 11:00:31 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Sat, 20 Apr 2013 02:00:31 -0700 (PDT)
Subject: [Tutor] design question (Django?)
In-Reply-To: <CANLXbfAkf6c0Trqg0Ybdes09YZhQuJ_5HPmJnW2Mwhxe9p3peg@mail.gmail.com>
References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkb3a8$b2a$1@ger.gmane.org>
	<1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkbi22$99c$1@ger.gmane.org>
	<1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<B4EF0C7D-44E9-42C3-8EAC-3256C5F974A3@gmail.com>
	<alpine.DEB.2.02.1304180739170.3322@gilgamesh>
	<CANLXbfAkf6c0Trqg0Ybdes09YZhQuJ_5HPmJnW2Mwhxe9p3peg@mail.gmail.com>
Message-ID: <1366448431.52046.YahooMailNeo@web163801.mail.gq1.yahoo.com>



On Sun, 14 Apr 2013, Don Jennings wrote:
>
>
>>
>>
>>>On Apr 14, 2013, at 7:06 AM, Albert-Jan Roskam wrote:
>>>
>>>
>>>
>>>>
>>>>> Subject: Re: [Tutor] design question (Django?)
>>>>
>>>>
>>>>>On 13/04/13 09:48, Albert-Jan Roskam wrote:
>>>>>
>>>>>
>>>>>I think I have to make a diagram of this. This stuff is quite hard
>>>>>>
>>>>>
>>>>Would it also be a good idea to simultaneously make a paper-and-pencil drawing of the UI?
>>>>
>>>
>>>Absolutely! Test it with three users. See Jakob Nielsen's brief take on the matter:
>>>
>>>
>
>
>You might check out Pencil, which I quite like.?
>
>
>http://pencil.evolus.vn/
>
>Hi Wayne, Walter,
>
>Thank you! I checked out both Pencil and Balsamiq. Based on the websites, Pencil seems to work better for me. It can export to html, among others so I could use it as a basis for my Django template. Not sure if Balsamiq can do this (I watched the video demo). The following doesn't apply to my case (as it is just a hobby project), but is there a potential risk that a mock up creates the illusion for clients that the entire job (not just a nonfunctional UI) is "almost done"?
>
>Regards,
>Albert-Jan
>
>ps: sorry about the formatting. Yahoo's rich text formatting won't turn of anymore
>

From payo2000 at gmail.com  Sat Apr 20 11:38:55 2013
From: payo2000 at gmail.com (pa yo)
Date: Sat, 20 Apr 2013 11:38:55 +0200
Subject: [Tutor] design question (Django?)
In-Reply-To: <1366448431.52046.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <1365838482.63494.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkb3a8$b2a$1@ger.gmane.org>
	<1365842881.24846.YahooMailNeo@web163804.mail.gq1.yahoo.com>
	<kkbi22$99c$1@ger.gmane.org>
	<1365937572.26277.YahooMailNeo@web163801.mail.gq1.yahoo.com>
	<B4EF0C7D-44E9-42C3-8EAC-3256C5F974A3@gmail.com>
	<alpine.DEB.2.02.1304180739170.3322@gilgamesh>
	<CANLXbfAkf6c0Trqg0Ybdes09YZhQuJ_5HPmJnW2Mwhxe9p3peg@mail.gmail.com>
	<1366448431.52046.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <CAOM=29Q+Cbe+NoPF9VZnTfSP3NCDUj=Y1s2G09+jEBd3KP3CfA@mail.gmail.com>

It doesn't do everything you want but you might try using the "Create Map"
function on Google maps.

You can draw lines and mark points in different colours. You cannot count
households - though i am not sure how you plan to do that with python;
where will the nHouseholds data come from?



On Sat, Apr 20, 2013 at 11:00 AM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:

>
>
> On Sun, 14 Apr 2013, Don Jennings wrote:
> >
> >
> >>
> >>
> >>>On Apr 14, 2013, at 7:06 AM, Albert-Jan Roskam wrote:
> >>>
> >>>
> >>>
> >>>>
> >>>>> Subject: Re: [Tutor] design question (Django?)
> >>>>
> >>>>
> >>>>>On 13/04/13 09:48, Albert-Jan Roskam wrote:
> >>>>>
> >>>>>
> >>>>>I think I have to make a diagram of this. This stuff is quite hard
> >>>>>>
> >>>>>
> >>>>Would it also be a good idea to simultaneously make a paper-and-pencil
> drawing of the UI?
> >>>>
> >>>
> >>>Absolutely! Test it with three users. See Jakob Nielsen's brief take on
> the matter:
> >>>
> >>>
> >
> >
> >You might check out Pencil, which I quite like.
> >
> >
> >http://pencil.evolus.vn/
> >
> >Hi Wayne, Walter,
> >
> >Thank you! I checked out both Pencil and Balsamiq. Based on the websites,
> Pencil seems to work better for me. It can export to html, among others so
> I could use it as a basis for my Django template. Not sure if Balsamiq can
> do this (I watched the video demo). The following doesn't apply to my case
> (as it is just a hobby project), but is there a potential risk that a mock
> up creates the illusion for clients that the entire job (not just a
> nonfunctional UI) is "almost done"?
> >
> >Regards,
> >Albert-Jan
> >
> >ps: sorry about the formatting. Yahoo's rich text formatting won't turn
> of anymore
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130420/4c880919/attachment.html>

From cybervigilante at gmail.com  Sat Apr 20 20:32:00 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 20 Apr 2013 11:32:00 -0700
Subject: [Tutor] 3to2?
Message-ID: <CALRAYNWoQtnn8Q6faen5=hpgPZP7XQFuGAhG4p977pvqqOunYQ@mail.gmail.com>

I was looking at google pengine for python and it only supports 2.7. I've
installed 3 and would rather not go back (I kept doing Print without the
parentheses for awhile and it was really annoying ;')

So the question comes up. If there is a 2to3 script, which I got working,
is there a 3to2 script?. Or does that even makes sense since 3 has features
2 does not, although I read somewhere that many have been backported?

-- 
*Jim Mooney

Today is the day that would have been tomorrow if yesterday was today
*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130420/f124eaa5/attachment.html>

From eryksun at gmail.com  Sat Apr 20 21:50:51 2013
From: eryksun at gmail.com (eryksun)
Date: Sat, 20 Apr 2013 15:50:51 -0400
Subject: [Tutor] 3to2?
In-Reply-To: <CALRAYNWoQtnn8Q6faen5=hpgPZP7XQFuGAhG4p977pvqqOunYQ@mail.gmail.com>
References: <CALRAYNWoQtnn8Q6faen5=hpgPZP7XQFuGAhG4p977pvqqOunYQ@mail.gmail.com>
Message-ID: <CACL+1au8YRDEYFqx8+ak7-N+kHdatHkNpGKVDX3oEV5bQMoqLw@mail.gmail.com>

On Sat, Apr 20, 2013 at 2:32 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> I was looking at google pengine for python and it only supports 2.7. I've
> installed 3 and would rather not go back

Do you mean Google App Engine (GAE)?

Django 1.5 supports 3.x (via Six), but GAE is at 1.4. I'm not sure if
GAE has other dependencies holding it up, but AFAIK Google hasn't even
published a release schedule for 3.x support. See issue 909:

https://code.google.com/p/googleappengine/issues/detail?id=909

Six:
http://pythonhosted.org/six

> So the question comes up. If there is a 2to3 script, which I got working, is
> there a 3to2 script?. Or does that even makes sense since 3 has features 2
> does not, although I read somewhere that many have been backported?

https://bitbucket.org/amentajo/lib3to2

As you've already guessed, 3to2 can't backport all 3.x code.

From cybervigilante at gmail.com  Sat Apr 20 22:14:50 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 20 Apr 2013 13:14:50 -0700
Subject: [Tutor] 3to2?
In-Reply-To: <CACL+1au8YRDEYFqx8+ak7-N+kHdatHkNpGKVDX3oEV5bQMoqLw@mail.gmail.com>
References: <CALRAYNWoQtnn8Q6faen5=hpgPZP7XQFuGAhG4p977pvqqOunYQ@mail.gmail.com>
	<CACL+1au8YRDEYFqx8+ak7-N+kHdatHkNpGKVDX3oEV5bQMoqLw@mail.gmail.com>
Message-ID: <CALRAYNXFto_KnEHPw8Sz28aZLZCih6jOSS9sU1JUGXMH8-xM1g@mail.gmail.com>

On 20 April 2013 12:50, eryksun <eryksun at gmail.com> wrote:

> On Sat, Apr 20, 2013 at 2:32 PM, Jim Mooney <cybervigilante at gmail.com>
> wrote:
> > I was looking at google pengine for python and it only supports 2.7. I've
> > installed 3 and would rather not go back
>
> Do you mean Google App Engine (GAE)?
>
-- 

Yeah, looks like my fingers got tangled. New keyboard.  I'm not used to
flat buttons.  I picked Python to learn since I'm retired and it seemed
like the most fun (although I won't turn down a Python contract now and
then if I ever learn it well ;').  I tried Ruby and Python and liked the Py
indentations so I chose that. But to me, it really is so much more
enjoyable to learn it for fun than I've-got-to-learn-this-to-make-money.
That doesn't mean I wan to just dabble, though. This is the first language
I want to learn formally and in detail, not just to get it over with so I
can hack a website.

But still, past a certain point, since I was a webmaster, I would of course
want to make web-use of it, if only for a nonprofit site, since I've run a
few of those.

*Jim Mooney

Today is the day that would have been tomorrow if yesterday was today
*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130420/ea9f9a99/attachment.html>

From alan.gauld at btinternet.com  Sat Apr 20 23:31:29 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 20 Apr 2013 22:31:29 +0100
Subject: [Tutor] 3to2?
In-Reply-To: <CALRAYNWoQtnn8Q6faen5=hpgPZP7XQFuGAhG4p977pvqqOunYQ@mail.gmail.com>
References: <CALRAYNWoQtnn8Q6faen5=hpgPZP7XQFuGAhG4p977pvqqOunYQ@mail.gmail.com>
Message-ID: <kkv1fd$s3c$1@ger.gmane.org>

On 20/04/13 19:32, Jim Mooney wrote:
> I was looking at google pengine for python and it only supports 2.7.
> I've installed 3 and would rather not go back

This is why we tend to recommend 2.7 for anyone doing serious work in 
Python.

Any dependency on a 3rd party library is much more likely to succeed if 
you stick with 2.x.

And as for automated tools - its very unusual to provide tools to port 
backwards, most folks want to go the other way...


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


From fahraynk at gmail.com  Sun Apr 21 00:07:51 2013
From: fahraynk at gmail.com (Frank Schiro)
Date: Sat, 20 Apr 2013 18:07:51 -0400
Subject: [Tutor] does anyone know a good module for automation
Message-ID: <CA+QG++FWWArsjCFfcSr87RtAJbLgE9dgN5WR8pPXvev7YErAkg@mail.gmail.com>

I once had a friend who built a bot to play a strategy game called Red
Alert : Tiberian Sun.  I guess it would be similar to warcraft 3.

Im wondering, does anyone know a good python module that would help me if I
wanted to accomplish something similar? All I have found so far while
surfing has been for webgames that you can take a screenshot and program
with coordinates from the screenshot.

Ive just gotten the hang of pywinauto, and now I realized I need to get
another program called selenium just to use Internet Explorer properly. So
I figure Ill need another module ontop of that to run other programs such
as games like sim city and other programs like that...

Unless you think pywinauto would work in a game envoirnment ? I think it
might but have not tried it because no games on my pc... I just know it
didnt work for internet explorer.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130420/63ace4ca/attachment.html>

From alan.gauld at btinternet.com  Sun Apr 21 02:28:56 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 21 Apr 2013 01:28:56 +0100
Subject: [Tutor] does anyone know a good module for automation
In-Reply-To: <CA+QG++FWWArsjCFfcSr87RtAJbLgE9dgN5WR8pPXvev7YErAkg@mail.gmail.com>
References: <CA+QG++FWWArsjCFfcSr87RtAJbLgE9dgN5WR8pPXvev7YErAkg@mail.gmail.com>
Message-ID: <kkvbs4$ibo$1@ger.gmane.org>

On 20/04/13 23:07, Frank Schiro wrote:
>
> Unless you think pywinauto would work in a game envoirnment ? I think it
> might but have not tried it because no games on my pc... I just know it
> didnt work for internet explorer.

I don't know pywinauto but the lowest common denominator on Windows is 
the Win32 API and the Windows messages. You can use either ctypes or 
pythonwin to access those and/or create your own to simulate button 
presses and mouse clicks etc. Doing that you can automate anything in 
windows, but its a non trivial, error prone and frustrating exercise so 
its better to get a higher level library if you can.


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


From cybervigilante at gmail.com  Sun Apr 21 04:10:23 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 20 Apr 2013 19:10:23 -0700
Subject: [Tutor] Time frame for Py 3 Maturity
Message-ID: <CALRAYNX0C9CSp9TYKB8vxH_VLo9jc1x7FLzgibjq4qQm4TNAuw@mail.gmail.com>

> This is why we tend to recommend 2.7 for anyone doing serious work in
> Python.
>

Understood. I am in no rush, but what do you think it the time frame when
Py 3 will be mature? A year from now? Two years? At some point I might want
to use it more practically. Or maybe there will be huge inflation, I'll go
broke, and have to use it more practically ;')

Also, is there a good syllabus for the best way to progress in this
language? One can certainly get sidetracked.

-- 
*Jim Mooney

Today is the day that would have been tomorrow if yesterday was today
*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130420/e2023111/attachment.html>

From steve at pearwood.info  Sun Apr 21 06:02:36 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 21 Apr 2013 14:02:36 +1000
Subject: [Tutor] Time frame for Py 3 Maturity
In-Reply-To: <CALRAYNX0C9CSp9TYKB8vxH_VLo9jc1x7FLzgibjq4qQm4TNAuw@mail.gmail.com>
References: <CALRAYNX0C9CSp9TYKB8vxH_VLo9jc1x7FLzgibjq4qQm4TNAuw@mail.gmail.com>
Message-ID: <517364DC.3080209@pearwood.info>

On 21/04/13 12:10, Jim Mooney wrote:
>> This is why we tend to recommend 2.7 for anyone doing serious work in
>> Python.
>>
>
> Understood. I am in no rush, but what do you think it the time frame when
> Py 3 will be mature? A year from now? Two years? At some point I might want
> to use it more practically. Or maybe there will be huge inflation, I'll go
> broke, and have to use it more practically ;')

Define "mature".

As a language, Python 3 was fully mature by the time Python 3.1 came out.
(Python 3.0 was, alas, seriously broken, and slow, and is no longer supported.)
Since 3.1, Python has simply become *better*, with more features, better
text handling, the decimal module is now nearly as fast as built-in floats,
a few rough edges have been cleaned up. I expect 3.4 will be better still.

Likewise for the standard library. All of the standard library is fully
compliant with Python 3. Naturally.

As for the external ecosystem of Python libraries and applications, I think
the answer is, "it depends".

There are still people relying on Python 1.5 (!), so from the perspective of
"when will everyone migrate to the latest version?", the answer is "Never",
and even Python 2 is not fully mature.

On the other hand, from the perspective of "When will the *majority* of
publicly-available libraries and packages support Python 3, then the answer
is "Right now". The Python 3 Wall of Shame turned mostly green some time ago,
and is now known as the Python 3 Wall of Superpowers:

https://python3wos.appspot.com/

Based on the number of downloads, almost three quarters of the Top 50 Python
packages support Python 3:

http://py3ksupport.appspot.com/

On the third hand, if *you personally* require one of the packages which has
not been updated, then the answer for you will depend on the specific package
you care about.

When Python 3 was first floated as a backwards-incompatible version, it was
expected that the overall migration would take about ten years. We're now
half-way through that decade, and uptake is going according to plan, possibly
even a little faster than expected. The early adopters have been using 3 for
many years now, the majority of libraries and packages have been updated,
the Linux distros are starting to plan for the day when Python 3 is the default,
and the majority of trolls have given up complaining about Python 3.


> Also, is there a good syllabus for the best way to progress in this
> language? One can certainly get sidetracked.

I don't quite understand that question. Syllabus? As in a list of topics like
this?

"You must learn A, then B, then C, then D, ... and now you are an expert!"


No.




-- 
Steven

From steve at pearwood.info  Sun Apr 21 07:32:44 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 21 Apr 2013 15:32:44 +1000
Subject: [Tutor] 3to2?
In-Reply-To: <CALRAYNWoQtnn8Q6faen5=hpgPZP7XQFuGAhG4p977pvqqOunYQ@mail.gmail.com>
References: <CALRAYNWoQtnn8Q6faen5=hpgPZP7XQFuGAhG4p977pvqqOunYQ@mail.gmail.com>
Message-ID: <517379FC.3050905@pearwood.info>

On 21/04/13 04:32, Jim Mooney wrote:
> I was looking at google pengine for python and it only supports 2.7. I've
> installed 3 and would rather not go back (I kept doing Print without the
> parentheses for awhile and it was really annoying ;')
>
> So the question comes up. If there is a 2to3 script, which I got working,
> is there a 3to2 script?. Or does that even makes sense since 3 has features
> 2 does not, although I read somewhere that many have been backported?


Is google broken in your part of the world? *wink*

https://duckduckgo.com/html/?q=python+3to2

https://www.google.com.au/search?q=python+3to2

http://au.search.yahoo.com/search?p=python+3to2

http://www.bing.com/search?q=python+3to2


Some features of Python 3 have already been back-ported, like the with
statement. Some can be optionally enabled, e.g.:

from __future__ import division, print_function

from future_builtins import *


In general, provided you only care about Python 2.7, you can write code
which behaves the same way in both 2 and 3. But as you go further back,
it becomes harder and harder. By the time you're trying to support 2.4
onwards, it becomes very annoying, and I'm speaking from experience.

Although I see that CherryPy actually manages to support everything from
2.3 onwards using a single code base, which truly astonishes me!



-- 
Steven

From alan.gauld at btinternet.com  Sun Apr 21 09:46:34 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 21 Apr 2013 08:46:34 +0100
Subject: [Tutor] Time frame for Py 3 Maturity
In-Reply-To: <CALRAYNX0C9CSp9TYKB8vxH_VLo9jc1x7FLzgibjq4qQm4TNAuw@mail.gmail.com>
References: <CALRAYNX0C9CSp9TYKB8vxH_VLo9jc1x7FLzgibjq4qQm4TNAuw@mail.gmail.com>
Message-ID: <kl05gm$58s$1@ger.gmane.org>

On 21/04/13 03:10, Jim Mooney wrote:

>>     This is why we tend to recommend 2.7 for anyone doing serious work in
>>     Python.
>
> Understood. I am in no rush, but what do you think it the time frame
> when Py 3 will be mature?

As Steven has already pointed out Python 3 itself is mature.
The problem is that many of the key 3rd party libraries have not
been ported yet or the ports are not stable. (Many others have
been so it depends what you need.)

But one of the problems in OpenSource is that the developments
are all done by volunteers. There is no central corporate
program of work to drive the porting process or set its priority
level. It just depends on what each project team sees as its
priority - adding features to the existing code, fixing bugs, or porting 
to Python3 (and thereafter maintaining 2 codebases...).

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


From cybervigilante at gmail.com  Sun Apr 21 18:24:06 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 21 Apr 2013 09:24:06 -0700
Subject: [Tutor] Py 3 package maturity - good links
Message-ID: <CALRAYNX_1XmVJ85Lmcz4Y-748S6uDJtbHhuHBdy6TC-9uwTBvA@mail.gmail.com>

> On the other hand, from the perspective of "When will the *majority* of
> publicly-available libraries and packages support Python 3, then the answer
> is "Right now". The Python 3 Wall of Shame turned mostly green some time
> ago,
> and is now known as the Python 3 Wall of Superpowers:
>
> https://python3wos.appspot.com/
>
> Based on the number of downloads, almost three quarters of the Top 50
> Python
> packages support Python 3:
>
> http://py3ksupport.appspot.com/
>

Thanks. Very useful links to save that would have taken time for me to find
on my own.

As for "syllabus," probably a dream for a dynamic language ;')  I was
thinking of the time my brother, a Lit grad, gave me a syllabus of
literature to read - still working on it forty years later.

Jim
*
*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130421/f1a36fa0/attachment.html>

From davea at davea.name  Sun Apr 21 22:05:42 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 21 Apr 2013 16:05:42 -0400
Subject: [Tutor] Py 3 package maturity - good links
In-Reply-To: <CALRAYNX_1XmVJ85Lmcz4Y-748S6uDJtbHhuHBdy6TC-9uwTBvA@mail.gmail.com>
References: <CALRAYNX_1XmVJ85Lmcz4Y-748S6uDJtbHhuHBdy6TC-9uwTBvA@mail.gmail.com>
Message-ID: <51744696.2090903@davea.name>

On 04/21/2013 12:24 PM, Jim Mooney wrote:
>> On the other hand, from the perspective of "When will the *majority* of
>> publicly-available libraries and packages support Python 3, then the answer
>> is "Right now". The Python 3 Wall of Shame turned mostly green some time
>> ago,
>> and is now known as the Python 3 Wall of Superpowers:
>>
>> https://python3wos.appspot.com/
>>
>> Based on the number of downloads, almost three quarters of the Top 50
>> Python
>> packages support Python 3:
>>
>> http://py3ksupport.appspot.com/
>>
>
> Thanks. Very useful links to save that would have taken time for me to find
> on my own.
>
> As for "syllabus," probably a dream for a dynamic language ;')  I was
> thinking of the time my brother, a Lit grad, gave me a syllabus of
> literature to read - still working on it forty years later.
>
>
>
http://pymotw.com/2/
     This could be one way to learn about new (to you) Python modules in 
a systematic way.

On the other hand, if you're looking for a syllabus of studying 
languages (plural), consider
    1) a dynamic language
    2) a compile one
    3) an assembler
    4) other    (lisp, Forth, ML, Prolog, ...)

Each category is enough different that you have to learn all new habits. 
  But knowing each one is valuable when using the other three types.




-- 
DaveA

From dime26 at yahoo.com  Mon Apr 22 02:49:09 2013
From: dime26 at yahoo.com (Alex Baker)
Date: Sun, 21 Apr 2013 17:49:09 -0700 (PDT)
Subject: [Tutor] Testing a method in a class with nosetests
In-Reply-To: <mailman.13.1366538402.24676.tutor@python.org>
References: <mailman.13.1366538402.24676.tutor@python.org>
Message-ID: <1366591749.43705.YahooMailNeo@web120205.mail.ne1.yahoo.com>

Hello,
I've been lurking tutor for the last couple months and have quite enjoyed it!

I'm having a problem testing a method using nosetests. The assignment (Learn Python the Hard Way) asks that I write tests for a package using assert_equal and assert_raises. I've?conquered the assert_equals but I'm having issues with assert_raises. I can't figure out how am I supposed to test a method in a class with an __init__. I understand the assert_raises works assert_raises("ERROR", callable, parameters), and the parameters get sent to nosetests, but because of the __init__ I have no parameters to send.


# main module code
class ParserError(Exception):
? ? pass

class Parser(object):

? ? def __init__(self, word_list):
? ? ? ? self.word_list = word_list

? ? def parse_object(self):
? ? ? ? skip(self.word_list, 'stop')
? ? ? ? next = peek(self.word_list)

? ? ? ? if next == 'noun':
? ? ? ? ? ? return match(self.word_list, 'noun')
? ? ? ? if next == 'direction':
? ? ? ? ? ? return match(self.word_list, 'direction')
? ? ? ? else:
? ? ? ? ? ? raise ParserError("Expected a noun or direction next.")

# test code
from nose.tools import *
from ex48 import parser
from ex48 import lexicon

def _test_words(input): ? ?
? ? words = lexicon.scan(input)
? ? test = parser.Parser(words)
? ? return test

def test_parse_object(): ? ?
? ? assert_equal(_test_words("the bear").parse_object(),?
? ? ? ? ? ? ? ? ('noun', 'bear'))
? ? assert_equal(_test_words("the the ?princess").parse_object(),
? ? ? ? ? ? ? ? ('noun', 'princess'))
? ? assert_equal(_test_words("the nortH").parse_object(),?
? ? ? ? ? ? ? ? ('direction', 'north'))
? ? assert_raises("ParserError", _test_words("will fail"))

# nosetests output
ERROR: tests.parser_tests.test_parse_object
----------------------------------------------------------------------
Traceback (most recent call last):
? File "/Library/Python/2.7/site-packages/nose/case.py", line 197, in runTest
? ? self.test(*self.arg)
? File "/Users/robotsmack/hack/python_projects/ex48/tests/parser_tests.py", line 17, in test_parse_object
? ? assert_raises("ParserError", _test_words("will fail"))
? File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 456, in assertRaises
? File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 113, in __exit__
TypeError: issubclass() arg 2 must be a class or tuple of classes

Obviously a bunch a code was snipped, but I don't think its relevant to my question. But just in case, I'm currently fumbling my way through putting up the whole package on GitHub.

Thanks in advance!
_Alex


________________________________
 From: "tutor-request at python.org" <tutor-request at python.org>
To: tutor at python.org 
Sent: Sunday, April 21, 2013 4:00 AM
Subject: Tutor Digest, Vol 110, Issue 86
 

Send Tutor mailing list submissions to
??? tutor at python.org

To subscribe or unsubscribe via the World Wide Web, visit
??? http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
??? tutor-request at python.org

You can reach the person managing the list at
??? tutor-owner at python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

?  1. Time frame for Py 3 Maturity (Jim Mooney)
?  2. Re: Time frame for Py 3 Maturity (Steven D'Aprano)
?  3. Re: 3to2? (Steven D'Aprano)
?  4. Re: Time frame for Py 3 Maturity (Alan Gauld)


----------------------------------------------------------------------

Message: 1
Date: Sat, 20 Apr 2013 19:10:23 -0700
From: Jim Mooney <cybervigilante at gmail.com>
To: tutor at python.org
Subject: [Tutor] Time frame for Py 3 Maturity
Message-ID:
??? <CALRAYNX0C9CSp9TYKB8vxH_VLo9jc1x7FLzgibjq4qQm4TNAuw at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

> This is why we tend to recommend 2.7 for anyone doing serious work in
> Python.
>

Understood. I am in no rush, but what do you think it the time frame when
Py 3 will be mature? A year from now? Two years? At some point I might want
to use it more practically. Or maybe there will be huge inflation, I'll go
broke, and have to use it more practically ;')

Also, is there a good syllabus for the best way to progress in this
language? One can certainly get sidetracked.

-- 
*Jim Mooney

Today is the day that would have been tomorrow if yesterday was today
*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130420/e2023111/attachment-0001.html>

------------------------------

Message: 2
Date: Sun, 21 Apr 2013 14:02:36 +1000
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Subject: Re: [Tutor] Time frame for Py 3 Maturity
Message-ID: <517364DC.3080209 at pearwood.info>
Content-Type: text/plain; charset=UTF-8; format=flowed

On 21/04/13 12:10, Jim Mooney wrote:
>> This is why we tend to recommend 2.7 for anyone doing serious work in
>> Python.
>>
>
> Understood. I am in no rush, but what do you think it the time frame when
> Py 3 will be mature? A year from now? Two years? At some point I might want
> to use it more practically. Or maybe there will be huge inflation, I'll go
> broke, and have to use it more practically ;')

Define "mature".

As a language, Python 3 was fully mature by the time Python 3.1 came out.
(Python 3.0 was, alas, seriously broken, and slow, and is no longer supported.)
Since 3.1, Python has simply become *better*, with more features, better
text handling, the decimal module is now nearly as fast as built-in floats,
a few rough edges have been cleaned up. I expect 3.4 will be better still.

Likewise for the standard library. All of the standard library is fully
compliant with Python 3. Naturally.

As for the external ecosystem of Python libraries and applications, I think
the answer is, "it depends".

There are still people relying on Python 1.5 (!), so from the perspective of
"when will everyone migrate to the latest version?", the answer is "Never",
and even Python 2 is not fully mature.

On the other hand, from the perspective of "When will the *majority* of
publicly-available libraries and packages support Python 3, then the answer
is "Right now". The Python 3 Wall of Shame turned mostly green some time ago,
and is now known as the Python 3 Wall of Superpowers:

https://python3wos.appspot.com/

Based on the number of downloads, almost three quarters of the Top 50 Python
packages support Python 3:

http://py3ksupport.appspot.com/

On the third hand, if *you personally* require one of the packages which has
not been updated, then the answer for you will depend on the specific package
you care about.

When Python 3 was first floated as a backwards-incompatible version, it was
expected that the overall migration would take about ten years. We're now
half-way through that decade, and uptake is going according to plan, possibly
even a little faster than expected. The early adopters have been using 3 for
many years now, the majority of libraries and packages have been updated,
the Linux distros are starting to plan for the day when Python 3 is the default,
and the majority of trolls have given up complaining about Python 3.


> Also, is there a good syllabus for the best way to progress in this
> language? One can certainly get sidetracked.

I don't quite understand that question. Syllabus? As in a list of topics like
this?

"You must learn A, then B, then C, then D, ... and now you are an expert!"


No.




-- 
Steven


------------------------------

Message: 3
Date: Sun, 21 Apr 2013 15:32:44 +1000
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Subject: Re: [Tutor] 3to2?
Message-ID: <517379FC.3050905 at pearwood.info>
Content-Type: text/plain; charset=UTF-8; format=flowed

On 21/04/13 04:32, Jim Mooney wrote:
> I was looking at google pengine for python and it only supports 2.7. I've
> installed 3 and would rather not go back (I kept doing Print without the
> parentheses for awhile and it was really annoying ;')
>
> So the question comes up. If there is a 2to3 script, which I got working,
> is there a 3to2 script?. Or does that even makes sense since 3 has features
> 2 does not, although I read somewhere that many have been backported?


Is google broken in your part of the world? *wink*

https://duckduckgo.com/html/?q=python+3to2

https://www.google.com.au/search?q=python+3to2

http://au.search.yahoo.com/search?p=python+3to2

http://www.bing.com/search?q=python+3to2


Some features of Python 3 have already been back-ported, like the with
statement. Some can be optionally enabled, e.g.:

from __future__ import division, print_function

from future_builtins import *


In general, provided you only care about Python 2.7, you can write code
which behaves the same way in both 2 and 3. But as you go further back,
it becomes harder and harder. By the time you're trying to support 2.4
onwards, it becomes very annoying, and I'm speaking from experience.

Although I see that CherryPy actually manages to support everything from
2.3 onwards using a single code base, which truly astonishes me!



-- 
Steven


------------------------------

Message: 4
Date: Sun, 21 Apr 2013 08:46:34 +0100
From: Alan Gauld <alan.gauld at btinternet.com>
To: tutor at python.org
Subject: Re: [Tutor] Time frame for Py 3 Maturity
Message-ID: <kl05gm$58s$1 at ger.gmane.org>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

On 21/04/13 03:10, Jim Mooney wrote:

>>? ?  This is why we tend to recommend 2.7 for anyone doing serious work in
>>? ?  Python.
>
> Understood. I am in no rush, but what do you think it the time frame
> when Py 3 will be mature?

As Steven has already pointed out Python 3 itself is mature.
The problem is that many of the key 3rd party libraries have not
been ported yet or the ports are not stable. (Many others have
been so it depends what you need.)

But one of the problems in OpenSource is that the developments
are all done by volunteers. There is no central corporate
program of work to drive the porting process or set its priority
level. It just depends on what each project team sees as its
priority - adding features to the existing code, fixing bugs, or porting 
to Python3 (and thereafter maintaining 2 codebases...).

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



------------------------------

Subject: Digest Footer

_______________________________________________
Tutor maillist? -? Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


------------------------------

End of Tutor Digest, Vol 110, Issue 86
**************************************
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130421/bf6f9009/attachment-0001.html>

From dime26 at yahoo.com  Mon Apr 22 03:09:08 2013
From: dime26 at yahoo.com (Alex Baker)
Date: Sun, 21 Apr 2013 18:09:08 -0700 (PDT)
Subject: [Tutor] Testing a method in a class with nosetests (Alex Baker)
In-Reply-To: <mailman.4738.1366591912.3113.tutor@python.org>
References: <mailman.4738.1366591912.3113.tutor@python.org>
Message-ID: <1366592948.75062.YahooMailNeo@web120204.mail.ne1.yahoo.com>

Dang, forgot to send in plain text! Sorry...?

Here is the GitHub link?http://github.com/robotsmack/ex48


________________________________
 From: "tutor-request at python.org" <tutor-request at python.org>
To: tutor at python.org 
Sent: Sunday, April 21, 2013 6:51 PM
Subject: Tutor Digest, Vol 110, Issue 87
 

Send Tutor mailing list submissions to
??? tutor at python.org

To subscribe or unsubscribe via the World Wide Web, visit
??? http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
??? tutor-request at python.org

You can reach the person managing the list at
??? tutor-owner at python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

?  1. Py 3 package maturity - good links (Jim Mooney)
?  2. Re: Py 3 package maturity - good links (Dave Angel)
?  3. Testing a method in a class with nosetests (Alex Baker)


----------------------------------------------------------------------

Message: 1
Date: Sun, 21 Apr 2013 09:24:06 -0700
From: Jim Mooney <cybervigilante at gmail.com>
To: tutor at python.org
Subject: [Tutor] Py 3 package maturity - good links
Message-ID:
??? <CALRAYNX_1XmVJ85Lmcz4Y-748S6uDJtbHhuHBdy6TC-9uwTBvA at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

> On the other hand, from the perspective of "When will the *majority* of
> publicly-available libraries and packages support Python 3, then the answer
> is "Right now". The Python 3 Wall of Shame turned mostly green some time
> ago,
> and is now known as the Python 3 Wall of Superpowers:
>
> https://python3wos.appspot.com/
>
> Based on the number of downloads, almost three quarters of the Top 50
> Python
> packages support Python 3:
>
> http://py3ksupport.appspot.com/
>

Thanks. Very useful links to save that would have taken time for me to find
on my own.

As for "syllabus," probably a dream for a dynamic language ;')? I was
thinking of the time my brother, a Lit grad, gave me a syllabus of
literature to read - still working on it forty years later.

Jim
*
*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130421/f1a36fa0/attachment-0001.html>

------------------------------

Message: 2
Date: Sun, 21 Apr 2013 16:05:42 -0400
From: Dave Angel <davea at davea.name>
To: tutor at python.org
Subject: Re: [Tutor] Py 3 package maturity - good links
Message-ID: <51744696.2090903 at davea.name>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

On 04/21/2013 12:24 PM, Jim Mooney wrote:
>> On the other hand, from the perspective of "When will the *majority* of
>> publicly-available libraries and packages support Python 3, then the answer
>> is "Right now". The Python 3 Wall of Shame turned mostly green some time
>> ago,
>> and is now known as the Python 3 Wall of Superpowers:
>>
>> https://python3wos.appspot.com/
>>
>> Based on the number of downloads, almost three quarters of the Top 50
>> Python
>> packages support Python 3:
>>
>> http://py3ksupport.appspot.com/
>>
>
> Thanks. Very useful links to save that would have taken time for me to find
> on my own.
>
> As for "syllabus," probably a dream for a dynamic language ;')? I was
> thinking of the time my brother, a Lit grad, gave me a syllabus of
> literature to read - still working on it forty years later.
>
>
>
http://pymotw.com/2/
? ?  This could be one way to learn about new (to you) Python modules in 
a systematic way.

On the other hand, if you're looking for a syllabus of studying 
languages (plural), consider
? ? 1) a dynamic language
? ? 2) a compile one
? ? 3) an assembler
? ? 4) other? ? (lisp, Forth, ML, Prolog, ...)

Each category is enough different that you have to learn all new habits. 
? But knowing each one is valuable when using the other three types.




-- 
DaveA


------------------------------

Message: 3
Date: Sun, 21 Apr 2013 17:49:09 -0700 (PDT)
From: Alex Baker <dime26 at yahoo.com>
To: "tutor at python.org" <tutor at python.org>
Subject: [Tutor] Testing a method in a class with nosetests
Message-ID:
??? <1366591749.43705.YahooMailNeo at web120205.mail.ne1.yahoo.com>
Content-Type: text/plain; charset="iso-8859-1"

Hello,
I've been lurking tutor for the last couple months and have quite enjoyed it!

I'm having a problem testing a method using nosetests. The assignment (Learn Python the Hard Way) asks that I write tests for a package using assert_equal and assert_raises. I've?conquered the assert_equals but I'm having issues with assert_raises. I can't figure out how am I supposed to test a method in a class with an __init__. I understand the assert_raises works assert_raises("ERROR", callable, parameters), and the parameters get sent to nosetests, but because of the __init__ I have no parameters to send.


# main module code
class ParserError(Exception):
? ? pass

class Parser(object):

? ? def __init__(self, word_list):
? ? ? ? self.word_list = word_list

? ? def parse_object(self):
? ? ? ? skip(self.word_list, 'stop')
? ? ? ? next = peek(self.word_list)

? ? ? ? if next == 'noun':
? ? ? ? ? ? return match(self.word_list, 'noun')
? ? ? ? if next == 'direction':
? ? ? ? ? ? return match(self.word_list, 'direction')
? ? ? ? else:
? ? ? ? ? ? raise ParserError("Expected a noun or direction next.")

# test code
from nose.tools import *
from ex48 import parser
from ex48 import lexicon

def _test_words(input): ? ?
? ? words = lexicon.scan(input)
? ? test = parser.Parser(words)
? ? return test

def test_parse_object(): ? ?
? ? assert_equal(_test_words("the bear").parse_object(),?
? ? ? ? ? ? ? ? ('noun', 'bear'))
? ? assert_equal(_test_words("the the ?princess").parse_object(),
? ? ? ? ? ? ? ? ('noun', 'princess'))
? ? assert_equal(_test_words("the nortH").parse_object(),?
? ? ? ? ? ? ? ? ('direction', 'north'))
? ? assert_raises("ParserError", _test_words("will fail"))

# nosetests output
ERROR: tests.parser_tests.test_parse_object
----------------------------------------------------------------------
Traceback (most recent call last):
? File "/Library/Python/2.7/site-packages/nose/case.py", line 197, in runTest
? ? self.test(*self.arg)
? File "/Users/robotsmack/hack/python_projects/ex48/tests/parser_tests.py", line 17, in test_parse_object
? ? assert_raises("ParserError", _test_words("will fail"))
? File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 456, in assertRaises
? File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 113, in __exit__
TypeError: issubclass() arg 2 must be a class or tuple of classes

Obviously a bunch a code was snipped, but I don't think its relevant to my question. But just in case, I'm currently fumbling my way through putting up the whole package on GitHub.

Thanks in advance!
_Alex


________________________________
From: "tutor-request at python.org" <tutor-request at python.org>
To: tutor at python.org 
Sent: Sunday, April 21, 2013 4:00 AM
Subject: Tutor Digest, Vol 110, Issue 86


Send Tutor mailing list submissions to
??? tutor at python.org

To subscribe or unsubscribe via the World Wide Web, visit
??? http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
??? tutor-request at python.org

You can reach the person managing the list at
??? tutor-owner at python.org

When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."


Today's Topics:

?? 1. Time frame for Py 3 Maturity (Jim Mooney)
?? 2. Re: Time frame for Py 3 Maturity (Steven D'Aprano)
?? 3. Re: 3to2? (Steven D'Aprano)
?? 4. Re: Time frame for Py 3 Maturity (Alan Gauld)


----------------------------------------------------------------------

Message: 1
Date: Sat, 20 Apr 2013 19:10:23 -0700
From: Jim Mooney <cybervigilante at gmail.com>
To: tutor at python.org
Subject: [Tutor] Time frame for Py 3 Maturity
Message-ID:
??? <CALRAYNX0C9CSp9TYKB8vxH_VLo9jc1x7FLzgibjq4qQm4TNAuw at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"

> This is why we tend to recommend 2.7 for anyone doing serious work in
> Python.
>

Understood. I am in no rush, but what do you think it the time frame when
Py 3 will be mature? A year from now? Two years? At some point I might want
to use it more practically. Or maybe there will be huge inflation, I'll go
broke, and have to use it more practically ;')

Also, is there a good syllabus for the best way to progress in this
language? One can certainly get sidetracked.

-- 
*Jim Mooney

Today is the day that would have been tomorrow if yesterday was today
*
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130420/e2023111/attachment-0001.html>

------------------------------

Message: 2
Date: Sun, 21 Apr 2013 14:02:36 +1000
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Subject: Re: [Tutor] Time frame for Py 3 Maturity
Message-ID: <517364DC.3080209 at pearwood.info>
Content-Type: text/plain; charset=UTF-8; format=flowed

On 21/04/13 12:10, Jim Mooney wrote:
>> This is why we tend to recommend 2.7 for anyone doing serious work in
>> Python.
>>
>
> Understood. I am in no rush, but what do you think it the time frame when
> Py 3 will be mature? A year from now? Two years? At some point I might want
> to use it more practically. Or maybe there will be huge inflation, I'll go
> broke, and have to use it more practically ;')

Define "mature".

As a language, Python 3 was fully mature by the time Python 3.1 came out.
(Python 3.0 was, alas, seriously broken, and slow, and is no longer supported.)
Since 3.1, Python has simply become *better*, with more features, better
text handling, the decimal module is now nearly as fast as built-in floats,
a few rough edges have been cleaned up. I expect 3.4 will be better still.

Likewise for the standard library. All of the standard library is fully
compliant with Python 3. Naturally.

As for the external ecosystem of Python libraries and applications, I think
the answer is, "it depends".

There are still people relying on Python 1.5 (!), so from the perspective of
"when will everyone migrate to the latest version?", the answer is "Never",
and even Python 2 is not fully mature.

On the other hand, from the perspective of "When will the *majority* of
publicly-available libraries and packages support Python 3, then the answer
is "Right now". The Python 3 Wall of Shame turned mostly green some time ago,
and is now known as the Python 3 Wall of Superpowers:

https://python3wos.appspot.com/

Based on the number of downloads, almost three quarters of the Top 50 Python
packages support Python 3:

http://py3ksupport.appspot.com/

On the third hand, if *you personally* require one of the packages which has
not been updated, then the answer for you will depend on the specific package
you care about.

When Python 3 was first floated as a backwards-incompatible version, it was
expected that the overall migration would take about ten years. We're now
half-way through that decade, and uptake is going according to plan, possibly
even a little faster than expected. The early adopters have been using 3 for
many years now, the majority of libraries and packages have been updated,
the Linux distros are starting to plan for the day when Python 3 is the default,
and the majority of trolls have given up complaining about Python 3.


> Also, is there a good syllabus for the best way to progress in this
> language? One can certainly get sidetracked.

I don't quite understand that question. Syllabus? As in a list of topics like
this?

"You must learn A, then B, then C, then D, ... and now you are an expert!"


No.




-- 
Steven


------------------------------

Message: 3
Date: Sun, 21 Apr 2013 15:32:44 +1000
From: Steven D'Aprano <steve at pearwood.info>
To: tutor at python.org
Subject: Re: [Tutor] 3to2?
Message-ID: <517379FC.3050905 at pearwood.info>
Content-Type: text/plain; charset=UTF-8; format=flowed

On 21/04/13 04:32, Jim Mooney wrote:
> I was looking at google pengine for python and it only supports 2.7. I've
> installed 3 and would rather not go back (I kept doing Print without the
> parentheses for awhile and it was really annoying ;')
>
> So the question comes up. If there is a 2to3 script, which I got working,
> is there a 3to2 script?. Or does that even makes sense since 3 has features
> 2 does not, although I read somewhere that many have been backported?


Is google broken in your part of the world? *wink*

https://duckduckgo.com/html/?q=python+3to2

https://www.google.com.au/search?q=python+3to2

http://au.search.yahoo.com/search?p=python+3to2

http://www.bing.com/search?q=python+3to2


Some features of Python 3 have already been back-ported, like the with
statement. Some can be optionally enabled, e.g.:

from __future__ import division, print_function

from future_builtins import *


In general, provided you only care about Python 2.7, you can write code
which behaves the same way in both 2 and 3. But as you go further back,
it becomes harder and harder. By the time you're trying to support 2.4
onwards, it becomes very annoying, and I'm speaking from experience.

Although I see that CherryPy actually manages to support everything from
2.3 onwards using a single code base, which truly astonishes me!



-- 
Steven


------------------------------

Message: 4
Date: Sun, 21 Apr 2013 08:46:34 +0100
From: Alan Gauld <alan.gauld at btinternet.com>
To: tutor at python.org
Subject: Re: [Tutor] Time frame for Py 3 Maturity
Message-ID: <kl05gm$58s$1 at ger.gmane.org>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed

On 21/04/13 03:10, Jim Mooney wrote:

>>? ?? This is why we tend to recommend 2.7 for anyone doing serious work in
>>? ?? Python.
>
> Understood. I am in no rush, but what do you think it the time frame
> when Py 3 will be mature?

As Steven has already pointed out Python 3 itself is mature.
The problem is that many of the key 3rd party libraries have not
been ported yet or the ports are not stable. (Many others have
been so it depends what you need.)

But one of the problems in OpenSource is that the developments
are all done by volunteers. There is no central corporate
program of work to drive the porting process or set its priority
level. It just depends on what each project team sees as its
priority - adding features to the existing code, fixing bugs, or porting 
to Python3 (and thereafter maintaining 2 codebases...).

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



------------------------------

Subject: Digest Footer

_______________________________________________
Tutor maillist? -? Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


------------------------------

End of Tutor Digest, Vol 110, Issue 86
**************************************
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130421/bf6f9009/attachment.html>

------------------------------

Subject: Digest Footer

_______________________________________________
Tutor maillist? -? Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor


------------------------------

End of Tutor Digest, Vol 110, Issue 87
**************************************
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130421/11fe085d/attachment-0001.html>

From steve at pearwood.info  Mon Apr 22 03:33:33 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 22 Apr 2013 11:33:33 +1000
Subject: [Tutor] Testing a method in a class with nosetests
In-Reply-To: <1366591749.43705.YahooMailNeo@web120205.mail.ne1.yahoo.com>
References: <mailman.13.1366538402.24676.tutor@python.org>
	<1366591749.43705.YahooMailNeo@web120205.mail.ne1.yahoo.com>
Message-ID: <5174936D.5020300@pearwood.info>

On 22/04/13 10:49, Alex Baker wrote:
> Hello,
> I've been lurking tutor for the last couple months and have quite enjoyed it!


Welcome, and congratulations on your first post! Unfortunately I have to start with a complaint :-( but it's NOT because you failed to post plain text, since you actually did.

When starting a new thread, please create a new, blank email, don't reply to an existing email. Especially not when that email is a digest containing four complete emails completely unrelated to your post! The end result is that at the bottom of your post is a copy of a complete digest, nearly 200 lines worth of unrelated, irrelevant stuff. (And we're lucky it was only 200 lines, during a busy week, digests could potentially be thousands of lines!) And then you compounded it by replying to the first email, and so ended up with those 200 lines quoted TWICE.


> I'm having a problem testing a method using nosetests. The assignment (Learn Python the Hard Way) asks that I write tests for a package using assert_equal and assert_raises. I've conquered the assert_equals but I'm having issues with assert_raises. I can't figure out how am I supposed to test a method in a class with an __init__. I understand the assert_raises works assert_raises("ERROR", callable, parameters), and the parameters get sent to nosetests, but because of the __init__ I have no parameters to send.


Unfortunately, I'm not familiar with nose, and so I'm guessing, but I would say replace this call:


     assert_raises("ParserError", _test_words("will fail"))

with this:

     assert_raises("ParserError", _test_words, "will fail")

or possibly this:

     assert_raises("ParserError", _test_words, ["will fail"])



I expect that the first version fails because the call to _test_words() function raises an exception before nose gets to handle it. This is why assert_raises takes a function argument, followed by its argument.




-- 
Steven

From cybervigilante at gmail.com  Mon Apr 22 03:35:00 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 21 Apr 2013 18:35:00 -0700
Subject: [Tutor] is there an explicit eof to test in Py 3?
Message-ID: <CALRAYNU1D=h8fuZFN9qcCii2EMBKikKqzg-hY+HiAmomZRyMWg@mail.gmail.com>

  I'm reading a book that suggests finding EOF when the readLine == ""

 But wouldn't that end erroneously on blank lines, that really contain
'\n', in which case more lines might follow? What 'empties' are
considered equal in Python? I'm coming from javascript which has a
cluster of rules for that.

Yes, I know the easy way is a for loop, which automatically breaks on
eof, but at times I want to use a while loop and break out of it
explicitly on eof. But I can't seem to find an explicit eof marker in
python. Is there one?

--
Jim Mooney

Today is the day that would have been tomorrow if yesterday was today

From cybervigilante at gmail.com  Mon Apr 22 04:50:00 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 21 Apr 2013 19:50:00 -0700
Subject: [Tutor] multiple versions of python on windows?
Message-ID: <CALRAYNUK6pQ9Hik6q-SeZNK7tGUKBZY5_O5Y1JXc+O7R6OEaog@mail.gmail.com>

My plan for starting on Py 3 may need some adjustment. I doiwnloaded
an irc client that needs Py 2.6 and I think Plone wants 2.7.

Is it possible to install multiple versions of python on the same
machine or will windows choke?

-- 
Jim Mooney

Today is the day that would have been tomorrow if yesterday was today

From davea at davea.name  Mon Apr 22 06:32:12 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 22 Apr 2013 00:32:12 -0400
Subject: [Tutor] is there an explicit eof to test in Py 3?
In-Reply-To: <CALRAYNU1D=h8fuZFN9qcCii2EMBKikKqzg-hY+HiAmomZRyMWg@mail.gmail.com>
References: <CALRAYNU1D=h8fuZFN9qcCii2EMBKikKqzg-hY+HiAmomZRyMWg@mail.gmail.com>
Message-ID: <5174BD4C.5050502@davea.name>

On 04/21/2013 09:35 PM, Jim Mooney wrote:
>    I'm reading a book that suggests finding EOF when the readLine == ""
>
>   But wouldn't that end erroneously on blank lines, that really contain
> '\n', in which case more lines might follow? What 'empties' are
> considered equal in Python? I'm coming from javascript which has a
> cluster of rules for that.
>
> Yes, I know the easy way is a for loop, which automatically breaks on
> eof, but at times I want to use a while loop and break out of it
> explicitly on eof. But I can't seem to find an explicit eof marker in
> python. Is there one?
>

A little experimenting could have told you the answer.  readline() 
returns a newline character for a blank line, and an empty string for 
end of file.




-- 
DaveA

From eryksun at gmail.com  Mon Apr 22 07:25:46 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 22 Apr 2013 01:25:46 -0400
Subject: [Tutor] is there an explicit eof to test in Py 3?
In-Reply-To: <CALRAYNU1D=h8fuZFN9qcCii2EMBKikKqzg-hY+HiAmomZRyMWg@mail.gmail.com>
References: <CALRAYNU1D=h8fuZFN9qcCii2EMBKikKqzg-hY+HiAmomZRyMWg@mail.gmail.com>
Message-ID: <CACL+1aumQtF8HvowAFO6GQBBw-FPhdraFcyr9WEKfOZrx8n5xA@mail.gmail.com>

On Sun, Apr 21, 2013 at 9:35 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> I'm reading a book that suggests finding EOF when the readLine == ""
>
>  But wouldn't that end erroneously on blank lines, that really contain
> '\n', in which case more lines might follow? What 'empties' are
> considered equal in Python? I'm coming from javascript which has a
> cluster of rules for that.

The newline (os.linesep) isn't stripped, though depending on the
"newline" option for open() it may be translated.

You shouldn't be testing equality. You know that reading from a file
returns either bytes or a string, so just rely on the boolean value.
Any type that implements __len_ (collections.abc.Sized) has an
implicit boolean value:

http://docs.python.org/3/reference/datamodel.html#object.__bool__

For example:

    while True:
        line = file.readline()
        if not line:
            break
        process(line)

From eryksun at gmail.com  Mon Apr 22 07:46:01 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 22 Apr 2013 01:46:01 -0400
Subject: [Tutor] multiple versions of python on windows?
In-Reply-To: <CALRAYNUK6pQ9Hik6q-SeZNK7tGUKBZY5_O5Y1JXc+O7R6OEaog@mail.gmail.com>
References: <CALRAYNUK6pQ9Hik6q-SeZNK7tGUKBZY5_O5Y1JXc+O7R6OEaog@mail.gmail.com>
Message-ID: <CACL+1auu9X5EBdeVpSpwgFqnEJ2LG1i24rez8dPUdrEq1BORQw@mail.gmail.com>

On Sun, Apr 21, 2013 at 10:50 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> My plan for starting on Py 3 may need some adjustment. I doiwnloaded
> an irc client that needs Py 2.6 and I think Plone wants 2.7.
>
> Is it possible to install multiple versions of python on the same
> machine or will windows choke?

Installing multiple versions is fine. Just disable the option to
update file type associations. When you installed Python 3, .py files
were associated with py.exe. This allows you to use a shebang to run a
script with a specific interpreter. Or in the console you can run a
specific version like this:

    C:\>py -2.5 -c "import __hello__"  &:: -c runs a command
    Hello world...

From cybervigilante at gmail.com  Mon Apr 22 08:42:50 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 21 Apr 2013 23:42:50 -0700
Subject: [Tutor] multiple versions of python on windows?
In-Reply-To: <747FF00B-976E-4367-BA7E-4A99998ADE0A@s.dcsdk12.org>
References: <CALRAYNUK6pQ9Hik6q-SeZNK7tGUKBZY5_O5Y1JXc+O7R6OEaog@mail.gmail.com>
	<747FF00B-976E-4367-BA7E-4A99998ADE0A@s.dcsdk12.org>
Message-ID: <CALRAYNWCkWZ4OOe40LOJQcGQt+oasBTEeuL7VA6xEGb1N9q-tQ@mail.gmail.com>

On 21 April 2013 22:47, School <northriptl at s.dcsdk12.org> wrote:
> You can install multiple versions. The programs use the version they were assigned to, so there shouldn't be any conflict.

This brings up the question of installing multiple versions of Wing
101 IDE. I forget the install but even if I can install in a different
directory for Py 2.7, Windows awful Registry might trip me up. I've
grown to love portables since they bypass Windows Worst Idea, but Wing
isn't one of them.

If anyone knows, does the paid version of wing allow to switch between
multipe installs? I know, this is probably a Wing discuss question,
but I'm burned out on joining discussion groups to ask one question,
since otherwise Wing is very easy to grasp.

-- 
Jim Mooney

Today is the day that would have been tomorrow if yesterday was today

From eryksun at gmail.com  Mon Apr 22 08:51:58 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 22 Apr 2013 02:51:58 -0400
Subject: [Tutor] Testing a method in a class with nosetests
In-Reply-To: <5174936D.5020300@pearwood.info>
References: <mailman.13.1366538402.24676.tutor@python.org>
	<1366591749.43705.YahooMailNeo@web120205.mail.ne1.yahoo.com>
	<5174936D.5020300@pearwood.info>
Message-ID: <CACL+1auBjeYtgeXvXS5YbZu_NerGT5XV_wESjK-xWbs3nRpXRA@mail.gmail.com>

On Sun, Apr 21, 2013 at 9:33 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> it's NOT because you failed to post plain text, since you actually did.

Actually it's a multipart message with both plain text and HTML, with
the digest quoted in each version. It helps that the HTML is using
"&nbsp;" and <br> that map directly to "=A0" and "=0A". The <span> and
<div> tags are used for color and font styling, rather than layout.

From oscar.j.benjamin at gmail.com  Mon Apr 22 17:25:09 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Mon, 22 Apr 2013 16:25:09 +0100
Subject: [Tutor] is there an explicit eof to test in Py 3?
In-Reply-To: <CALRAYNU1D=h8fuZFN9qcCii2EMBKikKqzg-hY+HiAmomZRyMWg@mail.gmail.com>
References: <CALRAYNU1D=h8fuZFN9qcCii2EMBKikKqzg-hY+HiAmomZRyMWg@mail.gmail.com>
Message-ID: <CAHVvXxQ5jw_UA7SDt8HxUZuJE+xSQPeCui6peddFFZq196eLXg@mail.gmail.com>

On 22 April 2013 02:35, Jim Mooney <cybervigilante at gmail.com> wrote:
>   I'm reading a book that suggests finding EOF when the readLine == ""
>
>  But wouldn't that end erroneously on blank lines, that really contain
> '\n', in which case more lines might follow? What 'empties' are
> considered equal in Python? I'm coming from javascript which has a
> cluster of rules for that.

In Python the rules for this are very simple. Strings compare equal if
they have exactly the same sequence of characters. Otherwise they
compare unequal.

> Yes, I know the easy way is a for loop, which automatically breaks on
> eof, but at times I want to use a while loop and break out of it
> explicitly on eof. But I can't seem to find an explicit eof marker in
> python. Is there one?

Why do you want to do this? The only reason I can think of is to avoif
buffering. Generally, the for loop is not just easier and clearer but
also more efficient (because of the buffering). It also allows you to
write code that can work just as easily with anything that is iterable
such as a list of strings.


Oscar

From amckenzie4 at gmail.com  Mon Apr 22 18:26:56 2013
From: amckenzie4 at gmail.com (Andy McKenzie)
Date: Mon, 22 Apr 2013 12:26:56 -0400
Subject: [Tutor] multiple versions of python on windows?
In-Reply-To: <CALRAYNWCkWZ4OOe40LOJQcGQt+oasBTEeuL7VA6xEGb1N9q-tQ@mail.gmail.com>
References: <CALRAYNUK6pQ9Hik6q-SeZNK7tGUKBZY5_O5Y1JXc+O7R6OEaog@mail.gmail.com>
	<747FF00B-976E-4367-BA7E-4A99998ADE0A@s.dcsdk12.org>
	<CALRAYNWCkWZ4OOe40LOJQcGQt+oasBTEeuL7VA6xEGb1N9q-tQ@mail.gmail.com>
Message-ID: <CAJttDkrKbg4ZaJruGyQUaQkNTeTXSXpXWwtx3B0ieS7TKjeiLQ@mail.gmail.com>

I have no idea on Wing, but I'm using Eclipse with the PyDev plugin, and
I'm able to associate projects with either Python 2.7 or 3.2 in Windows.
 It checks for correct grammar in each, and if I tell it to run as a Python
script, it uses the correct executable.

So if you're not tied to Wing, you might give Eclipse/PyDev a try.

-Andy


On Mon, Apr 22, 2013 at 2:42 AM, Jim Mooney <cybervigilante at gmail.com>wrote:

> On 21 April 2013 22:47, School <northriptl at s.dcsdk12.org> wrote:
> > You can install multiple versions. The programs use the version they
> were assigned to, so there shouldn't be any conflict.
>
> This brings up the question of installing multiple versions of Wing
> 101 IDE. I forget the install but even if I can install in a different
> directory for Py 2.7, Windows awful Registry might trip me up. I've
> grown to love portables since they bypass Windows Worst Idea, but Wing
> isn't one of them.
>
> If anyone knows, does the paid version of wing allow to switch between
> multipe installs? I know, this is probably a Wing discuss question,
> but I'm burned out on joining discussion groups to ask one question,
> since otherwise Wing is very easy to grasp.
>
> --
> Jim Mooney
>
> Today is the day that would have been tomorrow if yesterday was today
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130422/5c9296c6/attachment.html>

From wayne at waynewerner.com  Mon Apr 22 18:55:34 2013
From: wayne at waynewerner.com (Wayne Werner)
Date: Mon, 22 Apr 2013 11:55:34 -0500 (CDT)
Subject: [Tutor] 3to2?
In-Reply-To: <517379FC.3050905@pearwood.info>
References: <CALRAYNWoQtnn8Q6faen5=hpgPZP7XQFuGAhG4p977pvqqOunYQ@mail.gmail.com>
	<517379FC.3050905@pearwood.info>
Message-ID: <alpine.DEB.2.02.1304221148230.3322@gilgamesh>

On Sun, 21 Apr 2013, Steven D'Aprano wrote:

> On 21/04/13 04:32, Jim Mooney wrote:
>> I was looking at google pengine for python and it only supports 2.7. I've
>> installed 3 and would rather not go back (I kept doing Print without the
>> parentheses for awhile and it was really annoying ;')
>> 
>> So the question comes up. If there is a 2to3 script, which I got working,
>> is there a 3to2 script?. Or does that even makes sense since 3 has features
>> 2 does not, although I read somewhere that many have been backported?
>
> from __future__ import division, print_function
>
> from future_builtins import *

This is the route I recommend, and take myself. Usually I'll do:

from __future__ import print_function, division, unicode_literals

try:
     input = raw_input
     range = xrange
except NameError:
     pass #using python 3 already, whee!


which makes you able to write code that mostly looks to Python3.


You could also look at how Django does their 2/3 support: 
https://www.djangoproject.com/weblog/2012/aug/19/experimental-python-3-support/

Looks like they use the `six` library:
http://pythonhosted.org/six/


HTH,
-W

From cybervigilante at gmail.com  Tue Apr 23 03:47:41 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Mon, 22 Apr 2013 18:47:41 -0700
Subject: [Tutor] Why is my list index going out of range
Message-ID: <CALRAYNXz+PdHeYm+Jj8SM4myXGKR5W_m9m1sW6B78X_zRfXw-A@mail.gmail.com>

Okay, what am I doing wrong here? I'm generating primes from a list
and getting "list index out of range," but since the for loops
controls the indexes I don't see how that's happening. I thought it
was the list append, but I commented that out and put in a print
statement, and I still got the line 5 error:

primeList = [1]
numList = list(range(2,101))
for e in numList:
  for f in primeList:
    if numList[e] % primeList[f] != 0: #list index out of range
      primeList.append(numList[e])

print(primeList)

--
Jim Mooney

The Real Reason Things Keep Going Wrong:

At the beginning of time, God set a Magic Top Spinning... and spinning...
and spinning... and spinning... and spinning... and spinning... and
spinning...

After a few hundred million years God got bored and gave the top a good
kick; so it went rebounding away, flinging off planets and stars and
dinosaurs, and later, people who wrote about dinosaurs.

Then God realized that although Order and Regularity are virtuous, if you
want interesting stories, now and then you have to give things a good Kick!

This explains a lot.

From msirenef at lightbird.net  Tue Apr 23 04:02:42 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Mon, 22 Apr 2013 22:02:42 -0400
Subject: [Tutor] Why is my list index going out of range
In-Reply-To: <CALRAYNXz+PdHeYm+Jj8SM4myXGKR5W_m9m1sW6B78X_zRfXw-A@mail.gmail.com>
References: <CALRAYNXz+PdHeYm+Jj8SM4myXGKR5W_m9m1sW6B78X_zRfXw-A@mail.gmail.com>
Message-ID: <5175EBC2.8010706@lightbird.net>

On 04/22/2013 09:47 PM, Jim Mooney wrote:
> Okay, what am I doing wrong here? I'm generating primes from a list
> and getting "list index out of range," but since the for loops
> controls the indexes I don't see how that's happening. I thought it
> was the list append, but I commented that out and put in a print
> statement, and I still got the line 5 error:
>
> primeList = [1]
> numList = list(range(2,101))
> for e in numList:
>    for f in primeList:
>      if numList[e] % primeList[f] != 0: #list index out of range
>        primeList.append(numList[e])
>
> print(primeList)


You are doing, basically:
x = [1]
for f in x:
   x[f]

x[1] is out of range, because x is length=1, and
the last valid index is 0.

  -m

>
> --
> Jim Mooney
>
> The Real Reason Things Keep Going Wrong:
>
> At the beginning of time, God set a Magic Top Spinning... and spinning...
> and spinning... and spinning... and spinning... and spinning... and
> spinning...
>
> After a few hundred million years God got bored and gave the top a good
> kick; so it went rebounding away, flinging off planets and stars and
> dinosaurs, and later, people who wrote about dinosaurs.
>
> Then God realized that although Order and Regularity are virtuous, if you
> want interesting stories, now and then you have to give things a good Kick!
>
> This explains a lot.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/


From davea at davea.name  Tue Apr 23 04:03:18 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 22 Apr 2013 22:03:18 -0400
Subject: [Tutor] Why is my list index going out of range
In-Reply-To: <CALRAYNXz+PdHeYm+Jj8SM4myXGKR5W_m9m1sW6B78X_zRfXw-A@mail.gmail.com>
References: <CALRAYNXz+PdHeYm+Jj8SM4myXGKR5W_m9m1sW6B78X_zRfXw-A@mail.gmail.com>
Message-ID: <5175EBE6.1090307@davea.name>

On 04/22/2013 09:47 PM, Jim Mooney wrote:
> Okay, what am I doing wrong here? I'm generating primes from a list
> and getting "list index out of range," but since the for loops
> controls the indexes I don't see how that's happening. I thought it
> was the list append, but I commented that out and put in a print
> statement, and I still got the line 5 error:
>
> primeList = [1]
> numList = list(range(2,101))
> for e in numList:
>    for f in primeList:

e and f are now values from the lists;  they are *not* indexes into the 
list.
>      if numList[e] % primeList[f] != 0: #list index out of range

        if e % f != 0:    #will get rid of the exception

>        primeList.append(numList[e])
>

Unfortunately, you still have an algorithm bug.  But now that you 
shouldn't get exceptions, I'll leave you to find the bug.



-- 
DaveA

From alan.gauld at btinternet.com  Tue Apr 23 10:42:07 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Tue, 23 Apr 2013 09:42:07 +0100
Subject: [Tutor] Why is my list index going out of range
In-Reply-To: <CALRAYNXz+PdHeYm+Jj8SM4myXGKR5W_m9m1sW6B78X_zRfXw-A@mail.gmail.com>
References: <CALRAYNXz+PdHeYm+Jj8SM4myXGKR5W_m9m1sW6B78X_zRfXw-A@mail.gmail.com>
Message-ID: <kl5hgq$ic4$1@ger.gmane.org>

On 23/04/13 02:47, Jim Mooney wrote:
> Okay, what am I doing wrong here?

> primeList = [1]
> numList = list(range(2,101))
> for e in numList:
>    for f in primeList:
>      if numList[e] % primeList[f] != 0: #list index out of range

for lops in Python do not generate indexes they return the actual 
entries in the list. They are like a foreach loop in other languages.

What you are doing is like

pets = ['cat', 'dog','mouse']
for animal in pets:
     if pets[animal] == 'rabbit':
        print 'thats weird'

You cannot use the animal string as an index.
You use it directly like so:

pets = ['cat', 'dog','mouse']
for animal in pets:
     if animal == 'rabbit':
        print 'thats better'

Once you get used to this style of loop it is much easier
than trying do do things with indexes.

In your case its doubly confusing because the contents of your lists are 
numbers that could be used as indexes but would not give the result you 
expect. You were lucky that you started with a list of one element which 
was not zero.


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


From fomcl at yahoo.com  Tue Apr 23 16:14:06 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Tue, 23 Apr 2013 07:14:06 -0700 (PDT)
Subject: [Tutor] string.Template
Message-ID: <1366726446.81624.YahooMailNeo@web163805.mail.gq1.yahoo.com>

Hello,

Is there a better, *built-in* alternative for the code below? The recursion works,
but it feels like reinventing the wheel.

import string

def translate(template, *args):
??? """Recursively $-substitute <template> using <args> as a replacement"""
??? syntax = string.Template(template).substitute(*args)
??? if "$" in syntax:
??????? return translate(syntax, *args)
??? return syntax

template = """\
Monty $surname
$more
"""
more = """\
The quest for the holy $grail
"""
surname="Python"
grail="Grail"
print translate(template, locals())

Thank you!

Regards,
Albert-Jan


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a 
fresh water system, and public health, what have the Romans ever done for us?
????~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~?

From kwpolska at gmail.com  Tue Apr 23 16:47:05 2013
From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=)
Date: Tue, 23 Apr 2013 16:47:05 +0200
Subject: [Tutor] string.Template
In-Reply-To: <1366726446.81624.YahooMailNeo@web163805.mail.gq1.yahoo.com>
References: <1366726446.81624.YahooMailNeo@web163805.mail.gq1.yahoo.com>
Message-ID: <CAMw+j7KU7=Fw0xA5zk5be+e-Wrgqno0raPb1AZw+DBH==6s_KQ@mail.gmail.com>

On Tue, Apr 23, 2013 at 4:14 PM, Albert-Jan Roskam <fomcl at yahoo.com> wrote:
> Hello,
>
> Is there a better, *built-in* alternative for the code below? The recursion works,
> but it feels like reinventing the wheel.
>
> import string
>
> def translate(template, *args):
>     """Recursively $-substitute <template> using <args> as a replacement"""
>     syntax = string.Template(template).substitute(*args)
>     if "$" in syntax:
>         return translate(syntax, *args)
>     return syntax
>
> template = """\
> Monty $surname
> $more
> """
> more = """\
> The quest for the holy $grail
> """
> surname="Python"
> grail="Grail"
> print translate(template, locals())
>
> Thank you!
>
> Regards,
> Albert-Jan
>
>
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a
> fresh water system, and public health, what have the Romans ever done for us?
>     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor

1. locals() is hacky and you shouldn?t use it.
2. Do you need ?$??  Why not use the newfangled {} syntax (since
Python 2.6)?  Example:
       '2 + 2 = {val}'.format(val='fish')
   Or:
       '2 + 2 = {0}'.format('fish')
   Or even:
       '2 + 2 = {}'.format('fish')
3. I doubt that there is anything better if you want $.

--
Kwpolska <http://kwpolska.tk> | GPG KEY: 5EAAEA16
stop html mail                | always bottom-post
http://asciiribbon.org        | http://caliburn.nl/topposting.html

From steve at pearwood.info  Tue Apr 23 16:55:06 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 24 Apr 2013 00:55:06 +1000
Subject: [Tutor] string.Template
In-Reply-To: <1366726446.81624.YahooMailNeo@web163805.mail.gq1.yahoo.com>
References: <1366726446.81624.YahooMailNeo@web163805.mail.gq1.yahoo.com>
Message-ID: <5176A0CA.9000509@pearwood.info>

On 24/04/13 00:14, Albert-Jan Roskam wrote:
> Hello,
>
> Is there a better, *built-in* alternative for the code below? The recursion works,
> but it feels like reinventing the wheel.

What makes you think it is reinventing the wheel? The following looks like a perfectly sensible use for recursion. If your replacement strings themselves contain $-template strings, and you want to replace them as well, recursion seems like a good call.

Although, of course, the recursion may not converge on a single result. Consider what happens if you use the following replacement strings:

$spam -> $eggs
$eggs -> $spam



> import string
>
> def translate(template, *args):
>      """Recursively $-substitute <template> using <args> as a replacement"""
>      syntax = string.Template(template).substitute(*args)
>      if "$" in syntax:
>          return translate(syntax, *args)
>      return syntax
>
> template = """\
> Monty $surname
> $more
> """
> more = """\
> The quest for the holy $grail
> """
> surname="Python"
> grail="Grail"
> print translate(template, locals())



-- 
Steven

From steve at pearwood.info  Tue Apr 23 17:03:33 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Wed, 24 Apr 2013 01:03:33 +1000
Subject: [Tutor] string.Template
In-Reply-To: <CAMw+j7KU7=Fw0xA5zk5be+e-Wrgqno0raPb1AZw+DBH==6s_KQ@mail.gmail.com>
References: <1366726446.81624.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<CAMw+j7KU7=Fw0xA5zk5be+e-Wrgqno0raPb1AZw+DBH==6s_KQ@mail.gmail.com>
Message-ID: <5176A2C5.3090401@pearwood.info>

On 24/04/13 00:47, Chris ?Kwpolska? Warrick wrote:

> 1. locals() is hacky and you shouldn?t use it.

Actually this, or something like this, is exactly one of the use-cases for the locals() function.

Using locals() as a read-only mapping of name:value pairs is perfectly safe. It's only unsafe if you try to write to it. It may or may not work.


> 2. Do you need ?$??  Why not use the newfangled {} syntax

The two advantages of the $-template system are:

- It's simpler for non-programmers to use.

- By using the safe_substitute method instead of substitute, it can avoid raising an exception when a replacement is missing. Sometimes that's useful.


py> from string import Template
py> template = Template("Nobody expects the $nationality Inquisition!")
py> template.substitute(nationality="Spanish")
'Nobody expects the Spanish Inquisition!'
py> template.safe_substitute(country="Spain")
'Nobody expects the $nationality Inquisition!'




-- 
Steven

From andyc.2007 at yahoo.co.uk  Tue Apr 23 19:57:48 2013
From: andyc.2007 at yahoo.co.uk (Andrew Allan Cook)
Date: Tue, 23 Apr 2013 18:57:48 +0100 (BST)
Subject: [Tutor] .....
Message-ID: <1366739868.50483.YahooMailNeo@web133206.mail.ir2.yahoo.com>

Single Mom Makes $89,844/Yr in Her Spare Time on The Computer Without Selling Anything 

http://homeforsaleneartoronto.com/hwork55.html 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130423/84593aaf/attachment.html>

From collins.pat0108 at gmail.com  Sat Apr 20 22:33:32 2013
From: collins.pat0108 at gmail.com (Pat Collins)
Date: Sat, 20 Apr 2013 13:33:32 -0700
Subject: [Tutor] Why do I get an "unvalid syntax" on the print line for
	number1
Message-ID: <CAOgswiYvCwX+u0iuZoJ4KpT48fvG6hLToYzd+hG6OEiVew8zzQ@mail.gmail.com>

Any help appreciated.


#!/usr/bin/env python
"""
number.py Demonstrates collecting a number from the user.
"""

number_string1 = float(input("Give me a number: "))
number1 = (number_string1)

number_string2 = float(input("Give me another number: "))
number2 = (number_string2)

print number1, "times", number, "+", number1 * number2
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130420/6191aa99/attachment.html>

From kwpolska at gmail.com  Tue Apr 23 20:19:28 2013
From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=)
Date: Tue, 23 Apr 2013 20:19:28 +0200
Subject: [Tutor] Why do I get an "unvalid syntax" on the print line for
	number1
In-Reply-To: <CAOgswiYvCwX+u0iuZoJ4KpT48fvG6hLToYzd+hG6OEiVew8zzQ@mail.gmail.com>
References: <CAOgswiYvCwX+u0iuZoJ4KpT48fvG6hLToYzd+hG6OEiVew8zzQ@mail.gmail.com>
Message-ID: <CAMw+j7LBXMR_r8HogNS_WzSk2N7TW0kC3iRFQec0Gek8zz04wQ@mail.gmail.com>

On Sat, Apr 20, 2013 at 10:33 PM, Pat Collins <collins.pat0108 at gmail.com> wrote:
> Any help appreciated.
>
>
> #!/usr/bin/env python
> """
> number.py Demonstrates collecting a number from the user.
> """
>
> number_string1 = float(input("Give me a number: "))
> number1 = (number_string1)
>
> number_string2 = float(input("Give me another number: "))
> number2 = (number_string2)
>
> print number1, "times", number, "+", number1 * number2
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

You are probably using Python 3 (check with `python --version`).  In
this version, print is a function.  You need to do the following
instead:

print(number1, "times", number, "+", number1 * number2)

--
Kwpolska <http://kwpolska.tk> | GPG KEY: 5EAAEA16
stop html mail                | always bottom-post
http://asciiribbon.org        | http://caliburn.nl/topposting.html

From breamoreboy at yahoo.co.uk  Tue Apr 23 20:24:35 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 23 Apr 2013 19:24:35 +0100
Subject: [Tutor] Why do I get an "unvalid syntax" on the print line for
	number1
In-Reply-To: <CAOgswiYvCwX+u0iuZoJ4KpT48fvG6hLToYzd+hG6OEiVew8zzQ@mail.gmail.com>
References: <CAOgswiYvCwX+u0iuZoJ4KpT48fvG6hLToYzd+hG6OEiVew8zzQ@mail.gmail.com>
Message-ID: <kl6jl1$3l9$1@ger.gmane.org>

On 20/04/2013 21:33, Pat Collins wrote:
> Any help appreciated.
>
>
> #!/usr/bin/env python
> """
> number.py Demonstrates collecting a number from the user.
> """
>
> number_string1 = float(input("Give me a number: "))
> number1 = (number_string1)

Why not number1 = float(input("Give me a number: ")) ?

>
> number_string2 = float(input("Give me another number: "))
> number2 = (number_string2)

Ditto.

>
> print number1, "times", number, "+", number1 * number2
>

You're using Python 3 so print needs parenthesis as it's a function and 
not a statement.


-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From ramit.prasad at jpmorgan.com  Tue Apr 23 20:27:07 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 23 Apr 2013 18:27:07 +0000
Subject: [Tutor] Why do I get an "unvalid syntax" on the print line
	for	number1
In-Reply-To: <CAOgswiYvCwX+u0iuZoJ4KpT48fvG6hLToYzd+hG6OEiVew8zzQ@mail.gmail.com>
References: <CAOgswiYvCwX+u0iuZoJ4KpT48fvG6hLToYzd+hG6OEiVew8zzQ@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF47418340B76@SCACMX008.exchad.jpmchase.net>

Pat Collins wrote:
> Any help appreciated.
> 
> 
> #!/usr/bin/env python
> """
> number.py Demonstrates collecting a number from the user.
> """
> 
> number_string1 = float(input("Give me a number: "))
> number1 = (number_string1)

number_string1 is not a string as you have already converted
it to a float. number1 will be the same as number_string1
and so this line is pointless.

> 
> number_string2 = float(input("Give me another number: "))
> number2 = (number_string2)
> 
> print number1, "times", number, "+", number1 * number2

It is always to your benefit to provide Python version, operating
system, and a full error message including trace (copy/paste,
do not paraphrase).

>>> '2' sdfs 2
  File "<input>", line 1
    '2' sdfs 2
           ^
SyntaxError: invalid syntax

When it comes to syntax errors Python will usually denote where
the error occurs with a "^". The error will be at or before 
the "^". Occasionally it will be on the previous line; typically
where a missing end bracket/brace/parenthesis.

I suspect you are on Python 3 and need to use print as a 
function. If not, please include the full error message.

print(number1)


Note: If you are on Python 2, you should use raw_input() 
and not input().

~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.  

From dfjennings at gmail.com  Tue Apr 23 20:55:01 2013
From: dfjennings at gmail.com (Don Jennings)
Date: Tue, 23 Apr 2013 14:55:01 -0400
Subject: [Tutor] Why do I get an "unvalid syntax" on the print line for
	number1
In-Reply-To: <CAMw+j7LBXMR_r8HogNS_WzSk2N7TW0kC3iRFQec0Gek8zz04wQ@mail.gmail.com>
References: <CAOgswiYvCwX+u0iuZoJ4KpT48fvG6hLToYzd+hG6OEiVew8zzQ@mail.gmail.com>
	<CAMw+j7LBXMR_r8HogNS_WzSk2N7TW0kC3iRFQec0Gek8zz04wQ@mail.gmail.com>
Message-ID: <C8016C08-EF21-4E61-ADE2-164CC6A00922@gmail.com>


On Apr 23, 2013, at 2:19 PM, Chris ?Kwpolska? Warrick wrote:

> On Sat, Apr 20, 2013 at 10:33 PM, Pat Collins <collins.pat0108 at gmail.com> wrote:
>> Any help appreciated.
>> 
>> 
>> #!/usr/bin/env python
>> """
>> number.py Demonstrates collecting a number from the user.
>> """
>> 
>> number_string1 = float(input("Give me a number: "))
>> number1 = (number_string1)
>> 
>> number_string2 = float(input("Give me another number: "))
>> number2 = (number_string2)
>> 
>> print number1, "times", number, "+", number1 * number2
>> 
>> 
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>> 
> 
> You are probably using Python 3 (check with `python --version`).  In
> this version, print is a function.  You need to do the following
> instead:
> 
> print(number1, "times", number, "+", number1 * number2)

Once the OP fixes that error, I suspect another one will appear:

NameError: name 'number' is not defined

Take care,
Don


From fomcl at yahoo.com  Tue Apr 23 21:35:51 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Tue, 23 Apr 2013 12:35:51 -0700 (PDT)
Subject: [Tutor] string.Template
In-Reply-To: <5176A0CA.9000509@pearwood.info>
References: <1366726446.81624.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<5176A0CA.9000509@pearwood.info>
Message-ID: <1366745751.17245.YahooMailNeo@web163801.mail.gq1.yahoo.com>



> Subject: Re: [Tutor] string.Template
> 
> On 24/04/13 00:14, Albert-Jan Roskam wrote:
>>  Hello,
>> 
>>  Is there a better, *built-in* alternative for the code below? The recursion 
> works,
>>  but it feels like reinventing the wheel.
> 
> What makes you think it is reinventing the wheel? 

Hi Steven,

Well, using a template they way I am doing seems a very common thing to do to me. So I thought it would be part of string.Template or something similar already. Maybe I expected more of string.Template after having read a little about Django's template system for the past days. ;-) This version does not require the string module, and it's not less readable IMHO:

def translate(template, args):
??? """Recursively %-substitute <template> using <args> as a replacement"""
??? syntax = template % args
??? if "%" in syntax:
??????? return translate(syntax, args)
??? return syntax

template = """\
Monty %(surname)s
%(more)s
"""
more = """\
The quest for the holy %(grail)s
"""
surname="Python"
grail="Grail"
print translate(template, locals())


From rwobben at hotmail.com  Tue Apr 23 21:39:51 2013
From: rwobben at hotmail.com (Roelof Wobben)
Date: Tue, 23 Apr 2013 19:39:51 +0000
Subject: [Tutor] why does this not work
Message-ID: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>

Im trying to learn python by a course at codeacademy. Now I have this code : def shut_down(s):
    s = s.lower()
    if s == "yes":
        return "Shutting down..."
    elif s == "no" :
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you"
    But when I run it  I see this message: It looks like output other than yes/no does not return 
"Sorry, I didn't understand you." So can anyone explain to me what I did wrong. Roelof  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130423/d71bbc0d/attachment.html>

From karanmatic at gmail.com  Tue Apr 23 21:45:21 2013
From: karanmatic at gmail.com (Karan Goel)
Date: Tue, 23 Apr 2013 12:45:21 -0700
Subject: [Tutor] why does this not work
In-Reply-To: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
References: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
Message-ID: <CA+uS7hL9Eb9YHdVmMdrqEtR8iHQ8L4Yu5D_DoTdSg8L2LbtSkw@mail.gmail.com>

You're missing a dot (.)

*Sorry, I didn't understand you.*

- Karan Goel

----------------------------

The Real Reason Things Keep Going Wrong:

At the beginning of time, God set a Magic Top Spinning... and spinning...
and spinning... and spinning... and spinning... and spinning... and
spinning...

After a few hundred million years God got bored and gave the top a good
kick; so it went rebounding away, flinging off planets and stars and
dinosaurs, and later, people who wrote about dinosaurs.

Then God realized that although Order and Regularity are virtuous, if you
want interesting stories, now and then you have to give things a good Kick!

This explains a lot.


On Tue, Apr 23, 2013 at 12:39 PM, Roelof Wobben <rwobben at hotmail.com> wrote:

> Im trying to learn python by a course at codeacademy.
>
> Now I have this code :
>
> def shut_down(s):
>     s = s.lower()
>     if s == "yes":
>         return "Shutting down..."
>     elif s == "no" :
>         return "Shutdown aborted!"
>     else:
>         return "Sorry, I didn't understand you"
>
> But when I run it  I see this message:
>
> It looks like output other than yes/no does not return "Sorry, I didn't
> understand you."
>
> So can anyone explain to me what I did wrong.
>
> Roelof
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130423/e12701fc/attachment-0001.html>

From losermeloser at yahoo.com  Tue Apr 23 21:50:54 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Tue, 23 Apr 2013 12:50:54 -0700 (PDT)
Subject: [Tutor] trouble installing library
Message-ID: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>

im not sure if anyone is familiar with virtualenv but im tryng to follow a tutorial that has asked me to install virtualenv. i downloaded it in the form of a tar file and extracted it. There was no .exe file to install. The tutorial?asks for me to type this code :

$ virtualenv --no-site-packages gmapenv 
$ cd gmapenv

but i get a few errors. 1st virtualenv isnt a know command, so i put python infront of it and get an import error:

ImportError: No module named virtualenv

Am i installing it correctly? can anyone offer any help? Im on Windows Vista, and i have both python 2 and 3 but i would prefer to use Python 3
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130423/aea84e44/attachment.html>

From dyoo at hashcollision.org  Tue Apr 23 22:06:06 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Tue, 23 Apr 2013 14:06:06 -0600
Subject: [Tutor] trouble installing library
In-Reply-To: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
Message-ID: <CAGZAPF6RJwjW1GUYhKLsWrPaKj7edrSWUnRkDVV14Ba7O89y+Q@mail.gmail.com>

According to the documentation in:

    http://www.virtualenv.org/en/latest/

and:

    https://pypi.python.org/pypi/virtualenv

the "Installation" section in the documentation walks through what you
need to do to install the software.


Can you use Python's package managment system "pip" to handle the work
of installing the 'virtualenv' package?

    http://www.pip-installer.org/en/latest/

From fomcl at yahoo.com  Tue Apr 23 22:04:24 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Tue, 23 Apr 2013 13:04:24 -0700 (PDT)
Subject: [Tutor] trouble installing library
In-Reply-To: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
Message-ID: <1366747464.87574.YahooMailNeo@web163804.mail.gq1.yahoo.com>

ImportError: No module named virtualenv

>
>what happens if you cd to the directory where you untarred the file, then run "python setup.py install"Did you download the right version (for Python3)?
>Am i installing it correctly? can anyone offer any help? Im on Windows Vista, and i have both python 2 and 3 but i would prefer to use Python 3
>
>It's an honour to be communicating with the world's last Vista user ;-)))
>

From breamoreboy at yahoo.co.uk  Tue Apr 23 22:00:31 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 23 Apr 2013 21:00:31 +0100
Subject: [Tutor] why does this not work
In-Reply-To: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
References: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
Message-ID: <kl6p8u$343$1@ger.gmane.org>

On 23/04/2013 20:39, Roelof Wobben wrote:
> Im trying to learn python by a course at codeacademy.
>
> Now I have this code :
>
> def shut_down(s):
>      s = s.lower()
>      if s == "yes":
>          return "Shutting down..."
>      elif s == "no" :
>          return "Shutdown aborted!"
>      else:
>          return "Sorry, I didn't understand you"
>
> But when I run it  I see this message:
>
> It looks like output other than yes/no does not return "Sorry, I didn't
> understand you."
>
> So can anyone explain to me what I did wrong.
>
> Roelof

PEBKAC or PEBCAK? :)

c:\Users\Mark\MyPython>type b.py
def shut_down(s):
     s = s.lower()
     if s == "yes":
         return "Shutting down..."
     elif s == "no" :
         return "Shutdown aborted!"
     else:
         return "Sorry, I didn't understand you"

for s in 'what', 'the', 'heck?', 'YES', 'NO', 'works', 'okay', 'for', 'me':
     print(s, shut_down(s))

c:\Users\Mark\MyPython>b.py
what Sorry, I didn't understand you
the Sorry, I didn't understand you
heck? Sorry, I didn't understand you
YES Shutting down...
NO Shutdown aborted!
works Sorry, I didn't understand you
okay Sorry, I didn't understand you
for Sorry, I didn't understand you
me Sorry, I didn't understand you


-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From dyoo at hashcollision.org  Tue Apr 23 22:17:12 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Tue, 23 Apr 2013 14:17:12 -0600
Subject: [Tutor] why does this not work
In-Reply-To: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
References: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
Message-ID: <CAGZAPF752ogZ5vWkyBwsJ+-vKN527uOgUuthQR8BV6=ikf7pQw@mail.gmail.com>

Hi Roelof,

On Tue, Apr 23, 2013 at 1:39 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
> Im trying to learn python by a course at codeacademy.
>
> Now I have this code :
>
> def shut_down(s):
>     s = s.lower()
>     if s == "yes":
>         return "Shutting down..."
>     elif s == "no" :
>         return "Shutdown aborted!"
>     else:
>         return "Sorry, I didn't understand you"
>
> But when I run it  I see this message:
>
> It looks like output other than yes/no does not return "Sorry, I didn't
> understand you."


What inputs are you testing?  What output do you get?

You were doing fine, but summarized a little bit too much at the end.
Unlikely as it might seem, those details might matter, or at the very
least may help us discount certain possibilities.  Can you show us how
you're testing it?


(One of those "silly" possibilities: the function you're calling might
not be the function you've defined.  You call your function
shut_down(), but given that underscore, maybe you've defined a
function "shutdown" by accident?  It's those sort of niggling details
we need to discount; without seeing how you're doing your testing, we
have to leave that distant possibility open.)

From losermeloser at yahoo.com  Tue Apr 23 22:33:32 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Tue, 23 Apr 2013 13:33:32 -0700 (PDT)
Subject: [Tutor] trouble installing library
In-Reply-To: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
Message-ID: <1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>



Thanks for your response guys:
?
>> what happens if you cd to the directory where you untarred the file, then run "python setup.py install"
?
This seems to have done the trick!
?
>> It's an honour to be communicating with the world's last Vista user ;-)))
?
lol And this was very uncalled for :((
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130423/5efe2deb/attachment-0001.html>

From oscar.j.benjamin at gmail.com  Tue Apr 23 22:42:53 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Tue, 23 Apr 2013 21:42:53 +0100
Subject: [Tutor] why does this not work
In-Reply-To: <CAGZAPF752ogZ5vWkyBwsJ+-vKN527uOgUuthQR8BV6=ikf7pQw@mail.gmail.com>
References: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
	<CAGZAPF752ogZ5vWkyBwsJ+-vKN527uOgUuthQR8BV6=ikf7pQw@mail.gmail.com>
Message-ID: <CAHVvXxRARyDfqMQshiscSiW9bLT78ese65uZUX=xqEfPzdsj7Q@mail.gmail.com>

On 23 April 2013 21:17, Danny Yoo <dyoo at hashcollision.org> wrote:
> Hi Roelof,
>
> On Tue, Apr 23, 2013 at 1:39 PM, Roelof Wobben <rwobben at hotmail.com> wrote:
>> Im trying to learn python by a course at codeacademy.
>>
>> Now I have this code :
>>
>> def shut_down(s):
>>     s = s.lower()
>>     if s == "yes":
>>         return "Shutting down..."
>>     elif s == "no" :
>>         return "Shutdown aborted!"
>>     else:
>>         return "Sorry, I didn't understand you"
>>
>> But when I run it  I see this message:
>>
>> It looks like output other than yes/no does not return "Sorry, I didn't
>> understand you."
>
>
> What inputs are you testing?  What output do you get?
>
> You were doing fine, but summarized a little bit too much at the end.

I think that maybe the program is not running on the OP's computer but
on the codeacademy website
http://www.codecademy.com/#!/exercises/0
and that the message comes from the server that assesses the program.


Oscar

From losermeloser at yahoo.com  Tue Apr 23 23:03:05 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Tue, 23 Apr 2013 14:03:05 -0700 (PDT)
Subject: [Tutor] trouble installing library
In-Reply-To: <1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
Message-ID: <1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>

guys having got the install to work, a part of the process fails me.. the full code instruction is:
?
$ virtualenv --no-site-packages gmapenv 
$ cd gmapenv 
$ ls 
bin/? include/? lib/ 
$ . bin/activate
?
since im on windows i used dir instead of ls, but this line:
?
$ . bin/activate
?
is not recognised as a command. If i try to open it wth python cmd says no such file or directory
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130423/5d84fcd2/attachment.html>

From ramit.prasad at jpmorgan.com  Tue Apr 23 22:59:31 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 23 Apr 2013 20:59:31 +0000
Subject: [Tutor] string.Template
In-Reply-To: <1366745751.17245.YahooMailNeo@web163801.mail.gq1.yahoo.com>
References: <1366726446.81624.YahooMailNeo@web163805.mail.gq1.yahoo.com>
	<5176A0CA.9000509@pearwood.info>
	<1366745751.17245.YahooMailNeo@web163801.mail.gq1.yahoo.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF4741834102E@SCACMX008.exchad.jpmchase.net>

Albert-Jan Roskam wrote:
> > On 24/04/13 00:14, Albert-Jan Roskam wrote:
> >>  Hello,
> >>
> >>  Is there a better, *built-in* alternative for the code below? The recursion
> > works,
> >>  but it feels like reinventing the wheel.
> >
> > What makes you think it is reinventing the wheel?
> 
> Hi Steven,
> 
> Well, using a template they way I am doing seems a very common thing to do to me. So I thought it
> would be part of string.Template or something similar already. Maybe I expected more of
> string.Template after having read a little about Django's template system for the past days. ;-) This
> version does not require the string module, and it's not less readable IMHO:
> 
> def translate(template, args):
> ??? """Recursively %-substitute <template> using <args> as a replacement"""
> ??? syntax = template % args
> ??? if "%" in syntax:
> ??????? return translate(syntax, args)
> ??? return syntax

Just a side note, if you ever need to have a string with "%" in it, this will
recurse infinitely (or rather until Python throws an exception).

t = "Monty Python is #@!#%% %(status)s"
translate(t, {'status': 'awesome!'})


~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.  

From fomcl at yahoo.com  Tue Apr 23 23:28:13 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Tue, 23 Apr 2013 14:28:13 -0700 (PDT)
Subject: [Tutor] trouble installing library
In-Reply-To: <1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
Message-ID: <1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>



Subject: Re: [Tutor] trouble installing library
 

>
>guys having got the install to work, a part of the process fails me.. the full code instruction is:
>?
>$ virtualenv --no-site-packages gmapenv 
>$ cd gmapenv 
>$ ls 
>bin/? include/? lib/ 
>$ . bin/activate
>?
>since im on windows i used dir instead of ls, but this line:
>?
>$ . bin/activate
>?
>is not recognised as a command. If i try to open it wth python cmd says no such file or directory
>
>
>The dot (.) command is used to source a file, It executes Unix like commands in bin/activate. Not relevant when? you're on windows. Is there a .bat or .cmd file instead?
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130423/255534ac/attachment.html>

From ramit.prasad at jpmorgan.com  Tue Apr 23 23:18:10 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 23 Apr 2013 21:18:10 +0000
Subject: [Tutor] trouble installing library
In-Reply-To: <1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183410FF@SCACMX008.exchad.jpmchase.net>

Lolo Lolo wrote:
[snip]
> since im on windows i used dir instead of ls, but this line:
> 
> $ . bin/activate
> 
> is not recognised as a command. If i try to open it wth python cmd says no such file or directory
>
[snip]

Instead of trying `. bin/activate` try `bin/activate` 
(note the lack of ". " at the beginning)

From the documentation for Windows[1]:
`\path\to\env\Scripts\activate`

[1] https://pypi.python.org/pypi/virtualenv

~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.  

From losermeloser at yahoo.com  Tue Apr 23 23:59:50 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Tue, 23 Apr 2013 14:59:50 -0700 (PDT)
Subject: [Tutor] trouble installing library
In-Reply-To: <1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
Message-ID: <1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>

>> The dot (.) command is used to source a file, It executes Unix like commands in bin/activate. Not relevant when? you're on windows. >> Is there a .bat or .cmd file instead?
?
oh i had no idea.. i found the activate file inside a folder name Scripts (instead of bin) and and tried the same command, but now i get this error:
?
? File "Scripts/activate", line 4
??? deactivate () {
????????????????? ^
SyntaxError: invalid syntax
?
i looked at the activate file which doesnt have an extension. the code is not in python so im trying to figure out code i have no clue where its from. that line where the error is contains the javascript like braces after functions {} maybe thats it but it seems this tutorial doesnt want me to study it:(
Here is some of the code:
?
deactivate () {
??? unset pydoc
??? # reset old environment variables
??? if [ -n "$_OLD_VIRTUAL_PATH" ] ; then
??????? PATH="$_OLD_VIRTUAL_PATH"
??????? export PATH
??????? unset _OLD_VIRTUAL_PATH
??? fi
??? if [ -n "$_OLD_VIRTUAL_PYTHONHOME" ] ; then
??????? PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME"
??????? export PYTHONHOME
??????? unset _OLD_VIRTUAL_PYTHONHOME
?
what worries me is that it has comments, and on each comment this? is already there: 
?
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands.? Without forgetting
# past commands the $PATH changes we made may not be respected
?
but it still doesnt explain the invalid syntax on line 4:(
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130423/b633e788/attachment.html>

From alan.gauld at btinternet.com  Wed Apr 24 02:43:43 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 24 Apr 2013 01:43:43 +0100
Subject: [Tutor] trouble installing library
In-Reply-To: <1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
Message-ID: <kl79rq$8vo$1@ger.gmane.org>

On 23/04/13 22:59, Lolo Lolo wrote:

>    File "Scripts/activate", line 4
>      deactivate () {
>                    ^
> SyntaxError: invalid syntax

That's a bash/zsh script not a Python one. You will need to find a 
Windows equivalent bat file or cmd file or maybe wsh.

No idea if such a thing exists - maybe a Google search will help?

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


From eryksun at gmail.com  Wed Apr 24 04:01:44 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 23 Apr 2013 22:01:44 -0400
Subject: [Tutor] trouble installing library
In-Reply-To: <1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
Message-ID: <CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>

On Tue, Apr 23, 2013 at 5:59 PM, Lolo Lolo <losermeloser at yahoo.com> wrote:
> found the activate file inside a folder name Scripts (instead of bin) and
> and tried the same command, but now i get this error:
>
>   File "Scripts/activate", line 4
>     deactivate () {
>                   ^
> SyntaxError: invalid syntax

Run Scripts\activate.bat if your shell is cmd, or Scripts\activate.ps1
if you're using PowerShell. These are shell scripts. Do not run them
with Python.

----

>From the outset, use an elevated console and make sure you use the
desired version of Python when you install distribute/setuptools (use
distribute in 3.x). Be explicit here. For example, if 2.7 is in
C:\Python27, run

    CWD\>C:\Python27\python setup.py install

CWD is substituting here for your actual "current working directory",
as displayed in the default cmd shell prompt.

Or use pylauncher (installed with 3.3):

    CWD\>py -2.7 setup.py install

Then install pip with easy_install:

    CWD\>C:\Python27\Scripts\easy_install -Z pip

Finally virtualenv:

    CWD\>C:\Python27\Scripts\pip install virtualenv

If you're using Python 3.3, you may instead want to use the new
virtual environment module "venv" described in PEP 405:

http://www.python.org/dev/peps/pep-0405

Once the system-wide installation is finished you no longer need to
(and really shouldn't) work in an elevated console.

----

Generally I recommend using pip instead of easy_install. However, if
you have exe installers for pre-compiled packages, you can install
them with easy_install, at least if the installer is built with
distutils. pip can't do this. For example:

    (gmapenv) CWD\>easy_install -Z package-XXX-py2.7.exe

Note that "(gmapenv)" in the prompt signals that the "gmapenv" virtual
environment is active. Run "deactivate" to quit the virtual
environment and restore the original PROMPT and PATH.

From davea at davea.name  Wed Apr 24 04:47:38 2013
From: davea at davea.name (Dave Angel)
Date: Tue, 23 Apr 2013 22:47:38 -0400
Subject: [Tutor] why does this not work
In-Reply-To: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
References: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
Message-ID: <517747CA.30200@davea.name>

On 04/23/2013 03:39 PM, Roelof Wobben wrote:
> Im trying to learn python by a course at codeacademy. Now I have this code : def shut_down(s):
>      s = s.lower()
>      if s == "yes":
>          return "Shutting down..."
>      elif s == "no" :
>          return "Shutdown aborted!"
>      else:
>          return "Sorry, I didn't understand you"
>      But when I run it  I see this message: It looks like output other than yes/no does not return
> "Sorry, I didn't understand you." So can anyone explain to me what I did wrong. Roelof  		 	   		
>

Wrong?
1) your message is in html, not text.  So the formatting is messy.  It 
could have been worse, so please learn how to make your email program 
behave.
2) You didn't show your whole program.  If this is all you have in the 
file, then nothing will print because nothing calls your function.
3) You didn't describe your environment, including python version & OS. 
  And if Oscar's conjecture is correct, all bets are off because most of 
us won't be familiar with the strange environment.
4) I can't see how you could possibly get the message:
'It looks like output other than yes/no does not return "Sorry, I 
didn\'t understand you."'  And in fact the last part of the message is 
different than the literal in the program, so you've got a typo besides. 
  Please use cut&paste to show your actual code, your actual output.

After reading oscar's comment, my guess is that codeacademy (not Python) 
is complaining about the period at the end of your last literal string.

-- 
DaveA

From losermeloser at yahoo.com  Wed Apr 24 05:01:38 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Tue, 23 Apr 2013 20:01:38 -0700 (PDT)
Subject: [Tutor] trouble installing library
In-Reply-To: <CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
Message-ID: <1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>



 

________________________________

>> Run Scripts\activate.bat if your shell is cmd, or Scripts\activate.ps1
>> if you're using PowerShell. These are shell scripts. Do not run them
>> with Python.

I have to get some sleep but i believe i got the installation in the right version it also installed pip. I will go over your instructions just to make sure tomorrow. Also:

Scripts\activate.bat ... returns this error:

'Scripts' is not recognized as an internal or external command,
operable program or batch file.

it might want a program or command to run the bat fine
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130423/b35d5430/attachment-0001.html>

From eryksun at gmail.com  Wed Apr 24 05:18:13 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 23 Apr 2013 23:18:13 -0400
Subject: [Tutor] trouble installing library
In-Reply-To: <1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
	<1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>
Message-ID: <CACL+1avDGO2Pq32K_AkS8K1SHuAg4LZqyC0Bb081HJEeJYXdRg@mail.gmail.com>

On Tue, Apr 23, 2013 at 11:01 PM, Lolo Lolo <losermeloser at yahoo.com> wrote:
> Scripts\activate.bat ... returns this error:
>
> 'Scripts' is not recognized as an internal or external command,
> operable program or batch file.
> it might want a program or command to run the bat fine

Scripts\activate.bat is a relative path, assuming your current working
directory is that of the virtual environment.

From fred.f.bat at gmail.com  Wed Apr 24 05:27:04 2013
From: fred.f.bat at gmail.com (frederico Batista)
Date: Wed, 24 Apr 2013 00:27:04 -0300
Subject: [Tutor] why does this not work
In-Reply-To: <517747CA.30200@davea.name>
References: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
	<517747CA.30200@davea.name>
Message-ID: <CAOi=Wa1_Q_qeHHqfUQwx7rMjrRiWxJs1vB0_ORHB5OoBdf+J4w@mail.gmail.com>

Dave, you clearly don't know codecademy.
Please be nice to him.
Also, I recommend the codecademy forums. They have a lot of material about
every exercise.
On Apr 23, 2013 11:50 PM, "Dave Angel" <davea at davea.name> wrote:

> On 04/23/2013 03:39 PM, Roelof Wobben wrote:
>
>> Im trying to learn python by a course at codeacademy. Now I have this
>> code : def shut_down(s):
>>      s = s.lower()
>>      if s == "yes":
>>          return "Shutting down..."
>>      elif s == "no" :
>>          return "Shutdown aborted!"
>>      else:
>>          return "Sorry, I didn't understand you"
>>      But when I run it  I see this message: It looks like output other
>> than yes/no does not return
>> "Sorry, I didn't understand you." So can anyone explain to me what I did
>> wrong. Roelof
>>
>>
> Wrong?
> 1) your message is in html, not text.  So the formatting is messy.  It
> could have been worse, so please learn how to make your email program
> behave.
> 2) You didn't show your whole program.  If this is all you have in the
> file, then nothing will print because nothing calls your function.
> 3) You didn't describe your environment, including python version & OS.
>  And if Oscar's conjecture is correct, all bets are off because most of us
> won't be familiar with the strange environment.
> 4) I can't see how you could possibly get the message:
> 'It looks like output other than yes/no does not return "Sorry, I didn\'t
> understand you."'  And in fact the last part of the message is different
> than the literal in the program, so you've got a typo besides.  Please use
> cut&paste to show your actual code, your actual output.
>
> After reading oscar's comment, my guess is that codeacademy (not Python)
> is complaining about the period at the end of your last literal string.
>
> --
> DaveA
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/48c02923/attachment.html>

From silideba at gmail.com  Wed Apr 24 06:12:52 2013
From: silideba at gmail.com (Debashish Saha)
Date: Wed, 24 Apr 2013 09:42:52 +0530
Subject: [Tutor] problem with saving data in a text file
Message-ID: <CA+b=61BSod=c0yVkzpBA+Mea0yfPT9Wp8pWG1jYA0ZLpJVd4sA@mail.gmail.com>

I tried the following:

Am_cor=np.vectorize(Am_cor)

#plt.plot(t, signal, color='blue', label='Original signal')
fig=plt.figure()
plt.xlabel('Time(minute)')
plt.ylabel('$ Re(<E1.E2>)$')
plt.xlim([t[0], t[-1]])
plt.ylim((-.3*a1-a1,a1+.3*a1))
plt.grid()
plt.plot(t,Am_cor(t),'o-',label='with parallax', markersize=2)
plt.legend(loc="best")
plt.show()


f = open("Amp_cor_with_parallax(sd=.001)Ilamda=5.txt", "w")
f.write("# time(minute) \t                Amp_cor_with_parallax(sd=.001)
\n")  # column names
np.savetxt(f, np.array([t, Am_cor(t)]).T)
f.close()


now the error which I am getting is

   166             else:
    167                 filename = fname
--> 168             exec compile(scripttext, filename, 'exec') in glob, loc
    169     else:
    170         def execfile(fname, *where):

C:\Users\as\desktop\24_04_13\testing23_04.py in <module>()
    191 f = open("Amp_cor_with_parallax(sd=.001)Ilamda=5.txt", "w")
    192 f.write("# time(minute) \t
 Amp_cor_with_parallax(sd=.001) \n")  # column names
--> 193 np.savetxt(f, np.array([t, Am_cor(t)]).T)
    194 f.close()
    195

error: First argument must be a callable function.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/187bdaf6/attachment.html>

From alan.gauld at btinternet.com  Wed Apr 24 09:51:22 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 24 Apr 2013 08:51:22 +0100
Subject: [Tutor] trouble installing library
In-Reply-To: <1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
	<1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>
Message-ID: <kl82tm$esp$1@ger.gmane.org>

On 24/04/13 04:01, Lolo Lolo wrote:
>
>  >> Run Scripts\activate.bat
> Scripts\activate.bat ... returns this error:
> 'Scripts' is not recognized as an internal or external command,

Check your spacing. It looks like you have a space between
Scripts and activate somewhere.


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


From alan.gauld at btinternet.com  Wed Apr 24 10:00:36 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 24 Apr 2013 09:00:36 +0100
Subject: [Tutor] why does this not work
In-Reply-To: <CAOi=Wa1_Q_qeHHqfUQwx7rMjrRiWxJs1vB0_ORHB5OoBdf+J4w@mail.gmail.com>
References: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
	<517747CA.30200@davea.name>
	<CAOi=Wa1_Q_qeHHqfUQwx7rMjrRiWxJs1vB0_ORHB5OoBdf+J4w@mail.gmail.com>
Message-ID: <kl83f0$ljp$1@ger.gmane.org>

On 24/04/13 04:27, frederico Batista wrote:
> Dave, you clearly don't know codecademy.
> Please be nice to him.

To be fair to Dave he was very polite and showed the OP all the things 
that were needed to enable the users of this forum to help him. Very few 
of us are familiar with codeacademy - indeed until this thread I don't 
think I've come across it before. I certainly didn't know it
had its own runtime environment.

> Also, I recommend the codecademy forums. They have a lot of material
> about every exercise.

Posting in the most specific forum is always best so if the issue is 
with codeacademy that would be the best place. But I guess it would be 
hard for the OP to figure out if his problem is with Python or with 
Codeacademy...

>     Wrong?
>     1) your message is in html, not text.  So the formatting is messy.
>       It could have been worse, so please learn how to make your email
>     program behave.
>     2) You didn't show your whole program.  If this is all you have in
>     the file, then nothing will print because nothing calls your function.
>     3) You didn't describe your environment, including python version &
>     OS.  And if Oscar's conjecture is correct, all bets are off because
>     most of us won't be familiar with the strange environment.
>     4) I can't see how you could possibly get the message:
>     'It looks like output other than yes/no does not return "Sorry, I
>     didn\'t understand you."'  And in fact the last part of the message
>     is different than the literal in the program, so you've got a typo
>     besides.  Please use cut&paste to show your actual code, your actual
>     output.
>
>     After reading oscar's comment, my guess is that codeacademy (not
>     Python) is complaining about the period at the end of your last
>     literal string.
>
>     --
>     DaveA

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


From eryksun at gmail.com  Wed Apr 24 10:22:38 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 24 Apr 2013 04:22:38 -0400
Subject: [Tutor] problem with saving data in a text file
In-Reply-To: <CA+b=61BSod=c0yVkzpBA+Mea0yfPT9Wp8pWG1jYA0ZLpJVd4sA@mail.gmail.com>
References: <CA+b=61BSod=c0yVkzpBA+Mea0yfPT9Wp8pWG1jYA0ZLpJVd4sA@mail.gmail.com>
Message-ID: <CACL+1av7BMOLk6fSnvD_KGxq7pwZk+KhHd-dzpK3=Anz6Bywsg@mail.gmail.com>

On Wed, Apr 24, 2013 at 12:12 AM, Debashish Saha <silideba at gmail.com> wrote:
>
> --> 168             exec compile(scripttext, filename, 'exec') in glob, loc

This part of the traceback is from IPython. It would help if you ran
your script in the console using just python.exe, and provide the
complete traceback.

> --> 193 np.savetxt(f, np.array([t, Am_cor(t)]).T)
>
> error: First argument must be a callable function.

The above error is probably from SciPy interpolate (fitpack.error),
integrate (quadpack.error), or optimize (minpack.error) -- and looks
to be raised in Am_cor(t).

Example error:

    >>> integrate._quadpack._qagie('not a callable', 1.0, 1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    quadpack.error: First argument must be a callable function.

From breamoreboy at yahoo.co.uk  Wed Apr 24 10:56:07 2013
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Wed, 24 Apr 2013 09:56:07 +0100
Subject: [Tutor] trouble installing library
In-Reply-To: <CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
Message-ID: <kl86n5$olh$1@ger.gmane.org>

On 24/04/2013 03:01, eryksun wrote:
> On Tue, Apr 23, 2013 at 5:59 PM, Lolo Lolo <losermeloser at yahoo.com> wrote:
>> found the activate file inside a folder name Scripts (instead of bin) and
>> and tried the same command, but now i get this error:
>>
>>    File "Scripts/activate", line 4
>>      deactivate () {
>>                    ^
>> SyntaxError: invalid syntax
>
>
>  From the outset, use an elevated console
>

I have an image of a user sitting at their keyboard staring at a console 
on the ceiling :)  I'm assuming you mean use a console/command prompt 
with administrator privileges, am I correct?

-- 
If you're using GoogleCrap? please read this 
http://wiki.python.org/moin/GoogleGroupsPython.

Mark Lawrence


From rwobben at hotmail.com  Wed Apr 24 12:35:28 2013
From: rwobben at hotmail.com (Roelof Wobben)
Date: Wed, 24 Apr 2013 10:35:28 +0000
Subject: [Tutor] why does this not work
In-Reply-To: <kl83f0$ljp$1@ger.gmane.org>
References: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>,
	<517747CA.30200@davea.name>,
	<CAOi=Wa1_Q_qeHHqfUQwx7rMjrRiWxJs1vB0_ORHB5OoBdf+J4w@mail.gmail.com>,
	<kl83f0$ljp$1@ger.gmane.org>
Message-ID: <DUB121-W33FA4A78F13E6D0D459187AEB50@phx.gbl>


Thanks for all the remarks.

The problem was indeed a missing . at the end.

Roelof

> To: tutor at python.org
> From: alan.gauld at btinternet.com
> Date: Wed, 24 Apr 2013 09:00:36 +0100
> Subject: Re: [Tutor] why does this not work
> 
> On 24/04/13 04:27, frederico Batista wrote:
> > Dave, you clearly don't know codecademy.
> > Please be nice to him.
> 
> To be fair to Dave he was very polite and showed the OP all the things 
> that were needed to enable the users of this forum to help him. Very few 
> of us are familiar with codeacademy - indeed until this thread I don't 
> think I've come across it before. I certainly didn't know it
> had its own runtime environment.
> 
> > Also, I recommend the codecademy forums. They have a lot of material
> > about every exercise.
> 
> Posting in the most specific forum is always best so if the issue is 
> with codeacademy that would be the best place. But I guess it would be 
> hard for the OP to figure out if his problem is with Python or with 
> Codeacademy...
> 
> >     Wrong?
> >     1) your message is in html, not text.  So the formatting is messy.
> >       It could have been worse, so please learn how to make your email
> >     program behave.
> >     2) You didn't show your whole program.  If this is all you have in
> >     the file, then nothing will print because nothing calls your function.
> >     3) You didn't describe your environment, including python version &
> >     OS.  And if Oscar's conjecture is correct, all bets are off because
> >     most of us won't be familiar with the strange environment.
> >     4) I can't see how you could possibly get the message:
> >     'It looks like output other than yes/no does not return "Sorry, I
> >     didn\'t understand you."'  And in fact the last part of the message
> >     is different than the literal in the program, so you've got a typo
> >     besides.  Please use cut&paste to show your actual code, your actual
> >     output.
> >
> >     After reading oscar's comment, my guess is that codeacademy (not
> >     Python) is complaining about the period at the end of your last
> >     literal string.
> >
> >     --
> >     DaveA
> 
> -- 
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/bf18fe8a/attachment.html>

From losermeloser at yahoo.com  Wed Apr 24 14:51:09 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Wed, 24 Apr 2013 05:51:09 -0700 (PDT)
Subject: [Tutor] trouble installing library
In-Reply-To: <CACL+1avDGO2Pq32K_AkS8K1SHuAg4LZqyC0Bb081HJEeJYXdRg@mail.gmail.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
	<1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<CACL+1avDGO2Pq32K_AkS8K1SHuAg4LZqyC0Bb081HJEeJYXdRg@mail.gmail.com>
Message-ID: <1366807869.19889.YahooMailNeo@web121104.mail.ne1.yahoo.com>

Thanks for the help guys
?
>>?Scripts\activate.bat is a relative path, assuming your current working
>>?directory is that of the virtual environment.
?
your suggestion work.?Initially i was doing?Scripts/activate or Scripts/activate.bat. I guess it didnt like "/" and i didnt realise the difference. I have stumbled on a new error. The tutorial is aware i willl get an error because its explaining virtualenv. it wants me to type:
?
$ virtualenv --no-site-packages gmapenv 
$ cd gmapenv 
$ ls 
bin/? include/? lib/ 
$ . bin/activate 
$ python -c 'import googlemaps' 
Traceback (most recent call last):??????????????
? File "<string>", line 1, in <module> 
ImportError: No module named googlemaps?????????????????? <<<<<<<< error line
?
so i get the import error, but when i type:
?
python -c 'import googlemaps' or py -3 -c 'import googlemaps' i get this error:
?
? File "<string>", line 1
??? 'import
????????? ^
SyntaxError: EOL while scanning string literal
?
which i guess means my program didnt get up to trying to import the file
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/79f83eff/attachment.html>

From eryksun at gmail.com  Wed Apr 24 14:52:56 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 24 Apr 2013 08:52:56 -0400
Subject: [Tutor] trouble installing library
In-Reply-To: <kl86n5$olh$1@ger.gmane.org>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
	<kl86n5$olh$1@ger.gmane.org>
Message-ID: <CACL+1asS8Xonj+rawA4PPG9OujMM+QpfYp6aZ1_wW3JjnvexeA@mail.gmail.com>

On Wed, Apr 24, 2013 at 4:56 AM, Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:
> I have an image of a user sitting at their keyboard staring at a console on
> the ceiling :)  I'm assuming you mean use a console/command prompt with
> administrator privileges, am I correct?

LOL... sorry for being unclear. I think the most common expression is
"elevated command prompt" (1.7 million hits on Google). In this
context "elevated" refers to an elevated security token. With UAC,
even members of the Administrators group need to request elevation.

I dislike the name "command prompt".  "Elevated shell" would suit me,
but on Windows "shell" typically refers to the graphical shell
(desktop, taskbar, start menu) and associated Shell32 APIs such as
ShellExecute. Calling the console shell the "Command Prompt" is left
over from DOS,
for which it was literally named for the "Command" shell (like saying
bash prompt). Now it's like calling a tissue a Kleenex.

From eryksun at gmail.com  Wed Apr 24 15:29:03 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 24 Apr 2013 09:29:03 -0400
Subject: [Tutor] trouble installing library
In-Reply-To: <1366807869.19889.YahooMailNeo@web121104.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
	<1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<CACL+1avDGO2Pq32K_AkS8K1SHuAg4LZqyC0Bb081HJEeJYXdRg@mail.gmail.com>
	<1366807869.19889.YahooMailNeo@web121104.mail.ne1.yahoo.com>
Message-ID: <CACL+1as4sSg05tcSe8nGZHpjcaqC95y975WRN9+uoyOfQkN6ew@mail.gmail.com>

On Wed, Apr 24, 2013 at 8:51 AM, Lolo Lolo <losermeloser at yahoo.com> wrote:
> Thanks for the help guys
>
>>> Scripts\activate.bat is a relative path, assuming your current working
>>> directory is that of the virtual environment.
>
> your suggestion work. Initially i was doing Scripts/activate or
> Scripts/activate.bat. I guess it didnt like "/" and i didnt realise the
> difference.

Many Windows APIs accept slash and backslash interchangeably in paths,
but the cmd shell uses slash for options (e.g. dir /a:d) and only
permits backslash in paths.

> python -c 'import googlemaps' or py -3 -c 'import googlemaps' i get this
> error:

Generally you wouldn't  use the py launcher in an active virtual
environment.  The Scripts directory is prepended to the PATH, so just
run "python".

>   File "<string>", line 1
>     'import
>           ^
> SyntaxError: EOL while scanning string literal
>
> which i guess means my program didnt get up to trying to import the file

Notice the single quote. The syntax error is because the command line
was parsed like this:

    ['python', '-c', "'import", "googlemaps'"]

The -c option expects the command to be in the subsequent argument. So
it's as if you had a script with just the following in it:

    'import

Clearly that's a syntax error in the string literal. But you didn't
want a string literal in the first place.

The command line is split into arguments on spaces and tabs. You have
to use quotes for any string you don't want split up.  While a POSIX
shell uses both single and double quotes for this (single-quoted
strings are treated more literally), Microsoft's C/C++ runtime only
uses double quotes. So just change it to the following:

    python -c "import googlemaps"

----

Reference: Parsing C++ Command-Line Arguments
http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.100%29

From mlybrand at gmail.com  Wed Apr 24 15:35:10 2013
From: mlybrand at gmail.com (Mark Lybrand)
Date: Wed, 24 Apr 2013 06:35:10 -0700
Subject: [Tutor] trouble installing library
In-Reply-To: <CACL+1as4sSg05tcSe8nGZHpjcaqC95y975WRN9+uoyOfQkN6ew@mail.gmail.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
	<1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<CACL+1avDGO2Pq32K_AkS8K1SHuAg4LZqyC0Bb081HJEeJYXdRg@mail.gmail.com>
	<1366807869.19889.YahooMailNeo@web121104.mail.ne1.yahoo.com>
	<CACL+1as4sSg05tcSe8nGZHpjcaqC95y975WRN9+uoyOfQkN6ew@mail.gmail.com>
Message-ID: <CALsUBty1q4+GzYFf6pT1FE+AxvNwxm0bfgRHheRptjb19O47Xg@mail.gmail.com>

What tutorial are you using BTW?


On Wed, Apr 24, 2013 at 6:29 AM, eryksun <eryksun at gmail.com> wrote:

> On Wed, Apr 24, 2013 at 8:51 AM, Lolo Lolo <losermeloser at yahoo.com> wrote:
> > Thanks for the help guys
> >
> >>> Scripts\activate.bat is a relative path, assuming your current working
> >>> directory is that of the virtual environment.
> >
> > your suggestion work. Initially i was doing Scripts/activate or
> > Scripts/activate.bat. I guess it didnt like "/" and i didnt realise the
> > difference.
>
> Many Windows APIs accept slash and backslash interchangeably in paths,
> but the cmd shell uses slash for options (e.g. dir /a:d) and only
> permits backslash in paths.
>
> > python -c 'import googlemaps' or py -3 -c 'import googlemaps' i get this
> > error:
>
> Generally you wouldn't  use the py launcher in an active virtual
> environment.  The Scripts directory is prepended to the PATH, so just
> run "python".
>
> >   File "<string>", line 1
> >     'import
> >           ^
> > SyntaxError: EOL while scanning string literal
> >
> > which i guess means my program didnt get up to trying to import the file
>
> Notice the single quote. The syntax error is because the command line
> was parsed like this:
>
>     ['python', '-c', "'import", "googlemaps'"]
>
> The -c option expects the command to be in the subsequent argument. So
> it's as if you had a script with just the following in it:
>
>     'import
>
> Clearly that's a syntax error in the string literal. But you didn't
> want a string literal in the first place.
>
> The command line is split into arguments on spaces and tabs. You have
> to use quotes for any string you don't want split up.  While a POSIX
> shell uses both single and double quotes for this (single-quoted
> strings are treated more literally), Microsoft's C/C++ runtime only
> uses double quotes. So just change it to the following:
>
>     python -c "import googlemaps"
>
> ----
>
> Reference: Parsing C++ Command-Line Arguments
> http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.100%29
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Mark :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/e9e0bf9b/attachment-0001.html>

From fomcl at yahoo.com  Wed Apr 24 16:12:23 2013
From: fomcl at yahoo.com (Albert-Jan Roskam)
Date: Wed, 24 Apr 2013 07:12:23 -0700 (PDT)
Subject: [Tutor] trouble installing library
In-Reply-To: <1366807869.19889.YahooMailNeo@web121104.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
	<1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<CACL+1avDGO2Pq32K_AkS8K1SHuAg4LZqyC0Bb081HJEeJYXdRg@mail.gmail.com>
	<1366807869.19889.YahooMailNeo@web121104.mail.ne1.yahoo.com>
Message-ID: <1366812743.97219.YahooMailNeo@web163805.mail.gq1.yahoo.com>

Subject: Re: [Tutor] trouble installing library


>
>Thanks for the help guys
>?
>>>?Scripts\activate.bat is a relative path, assuming your current working
>>>?directory is that of the virtual environment.
>
>your suggestion work.?Initially i was doing?Scripts/activate or Scripts/activate.bat. I guess it didnt like "/" and i didnt realise the difference. I have stumbled on a new error. The tutorial is aware i willl get an error because its explaining virtualenv. it wants me to type:
>
>$ virtualenv --no-site-packages gmapenv 
>$ cd gmapenv 
>$ ls 
>bin/? include/? lib/ 
>$ . bin/activate 
>$ python -c 'import googlemaps' 
>Traceback (most recent call last):??????????????
>? File "<string>", line 1, in <module> 
>ImportError: No module named googlemaps?????????????????? <<<<<<<< error line
>
>so i get the import error, but when i type:
>
>
>It seems like you're almost there now. Instead of downloading the .tar.gz file, you might have also followed the following:
>http://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python
>?
>http? -->?download it manually (no curl in windows?)://peak.telecommunity.com/dist/ez_setup.py
>python ez_setup.py
>easy_install pip
>pip install virtualenv

From s.shall at virginmedia.com  Wed Apr 24 16:59:39 2013
From: s.shall at virginmedia.com (Sydney Shall)
Date: Wed, 24 Apr 2013 15:59:39 +0100
Subject: [Tutor] totalViruses[i] /= float(numTrials),
Message-ID: <5177F35B.2060308@virginmedia.com>

//I am a beginner just learning Python.

I have come across the following usage for the first time.

   totalViruses[i] /= float(numTrials)

Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
-- 
Sydney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/f44bc8c8/attachment.html>

From losermeloser at yahoo.com  Wed Apr 24 17:18:33 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Wed, 24 Apr 2013 08:18:33 -0700 (PDT)
Subject: [Tutor] trouble installing library
In-Reply-To: <CACL+1as4sSg05tcSe8nGZHpjcaqC95y975WRN9+uoyOfQkN6ew@mail.gmail.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
	<1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<CACL+1avDGO2Pq32K_AkS8K1SHuAg4LZqyC0Bb081HJEeJYXdRg@mail.gmail.com>
	<1366807869.19889.YahooMailNeo@web121104.mail.ne1.yahoo.com>
	<CACL+1as4sSg05tcSe8nGZHpjcaqC95y975WRN9+uoyOfQkN6ew@mail.gmail.com>
Message-ID: <1366816713.10224.YahooMailNeo@web121104.mail.ne1.yahoo.com>

>> Microsoft's C/C++ runtime only
>> uses double quotes. So just change it to the following:

? ? >> python -c "import googlemaps"
?
Thanks this solved the issue, now another issue has been thrown. Just not my day. after the 1st module error happens, they show the correct way to install google maps, i will show there results, then mine.
?
$ pip install googlemaps 
Downloading/unpacking googlemaps 
? Downloading googlemaps-1.0.2.tar.gz (60Kb): 60Kb downloaded 
? Running setup.py egg_info for package googlemaps 
Installing collected packages: googlemaps 
? Running setup.py install for googlemaps 
Successfully installed googlemaps 
Cleaning up... 
?
?
Here is mine: 
?
?
(gmapenv) D:\Data\Files Data\virtualenv-1.9.1\scripts\gmapenv>pip instal
l googlemaps

Downloading/unpacking googlemaps
? Downloading googlemaps-1.0.2.tar.gz (60kB): 60kB downloaded
? Running setup.py egg_info for package googlemaps
??? Traceback (most recent call last):
????? File "<string>", line 16, in <module>
????? File "D:\Data\Files Data\virtualenv-1.9.1\scripts\gmapenv\build\go
oglemaps\setup.py", line 18, in <module>
??????? import googlemaps
????? File "googlemaps\googlemaps.py", line 471
??????? print main.__doc__
???????????????? ^
??? SyntaxError: invalid syntax
??? Complete output from command python setup.py egg_info:
??? Traceback (most recent call last):
? File "<string>", line 16, in <module>
? File "D:\Data\Files Data\virtualenv-1.9.1\scripts\gmapenv\build\google
maps\setup.py", line 18, in <module>
??? import googlemaps
? File "googlemaps\googlemaps.py", line 471
??? print main.__doc__
???????????? ^
SyntaxError: invalid syntax
----------------------------------------
Command python setup.py egg_info failed with error code 1 in D:\Data\Fil
es Data\virtualenv-1.9.1\scripts\gmapenv\build\googlemaps
Storing complete log in C:\Users\Lolo\pip\pip.log
?
?
The 2 syntax errors look like python 2 vs python 3 errors:
?
print main.__doc__?
?
The googlemaps package was created but im just not comfortable with the error as it may be incomplete. and i dont know if its wise to go into the file i change it to? print(main.__doc__), will there be a lot more errors like these? was googlemaps meant only to be used with python 2 and not 3? If i do change the print statements that caused the?errors,?do i delete the created googlemaps directory and do it again as the previous one might be incomplete?? can anyone please offer help as to what i should do next
?
?
>> Reference: Parsing C++ Command-Line Arguments
>> http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.100%29
?
C++ is behind the windows command line? 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/1ed1db32/attachment.html>

From kwpolska at gmail.com  Wed Apr 24 17:26:39 2013
From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=)
Date: Wed, 24 Apr 2013 17:26:39 +0200
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <5177F35B.2060308@virginmedia.com>
References: <5177F35B.2060308@virginmedia.com>
Message-ID: <CAMw+j7Lwwp0b5oQGqRgRWy5fdWMcpPiL962_xPw8ZpRiXqnLHA@mail.gmail.com>

On Wed, Apr 24, 2013 at 4:59 PM, Sydney Shall <s.shall at virginmedia.com> wrote:
>  I am a beginner just learning Python.
>
> I have come across the following usage for the first time.
>
>   totalViruses[i] /= float(numTrials)
>
> Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
> --
> Sydney
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Yup.  Similar expressions exist for other binary operators (+, -, *, etc.)

--
Kwpolska <http://kwpolska.tk> | GPG KEY: 5EAAEA16
stop html mail                | always bottom-post
http://asciiribbon.org        | http://caliburn.nl/topposting.html

From fred.f.bat at gmail.com  Wed Apr 24 17:27:36 2013
From: fred.f.bat at gmail.com (frederico Batista)
Date: Wed, 24 Apr 2013 12:27:36 -0300
Subject: [Tutor] why does this not work
In-Reply-To: <kl83f0$ljp$1@ger.gmane.org>
References: <DUB121-W350DCF2797038EFE6171BEAEB40@phx.gbl>
	<517747CA.30200@davea.name>
	<CAOi=Wa1_Q_qeHHqfUQwx7rMjrRiWxJs1vB0_ORHB5OoBdf+J4w@mail.gmail.com>
	<kl83f0$ljp$1@ger.gmane.org>
Message-ID: <CAOi=Wa2TB9y004H3FPtyTn2f9XbJjtWK9dBX9n7B=V_vrw8YVA@mail.gmail.com>

Well then, sorry about it Dave.
My bad.
 On Apr 24, 2013 5:05 AM, "Alan Gauld" <alan.gauld at btinternet.com> wrote:

> On 24/04/13 04:27, frederico Batista wrote:
>
>> Dave, you clearly don't know codecademy.
>> Please be nice to him.
>>
>
> To be fair to Dave he was very polite and showed the OP all the things
> that were needed to enable the users of this forum to help him. Very few of
> us are familiar with codeacademy - indeed until this thread I don't think
> I've come across it before. I certainly didn't know it
> had its own runtime environment.
>
>  Also, I recommend the codecademy forums. They have a lot of material
>> about every exercise.
>>
>
> Posting in the most specific forum is always best so if the issue is with
> codeacademy that would be the best place. But I guess it would be hard for
> the OP to figure out if his problem is with Python or with Codeacademy...
>
>      Wrong?
>>     1) your message is in html, not text.  So the formatting is messy.
>>       It could have been worse, so please learn how to make your email
>>     program behave.
>>     2) You didn't show your whole program.  If this is all you have in
>>     the file, then nothing will print because nothing calls your function.
>>     3) You didn't describe your environment, including python version &
>>     OS.  And if Oscar's conjecture is correct, all bets are off because
>>     most of us won't be familiar with the strange environment.
>>     4) I can't see how you could possibly get the message:
>>     'It looks like output other than yes/no does not return "Sorry, I
>>     didn\'t understand you."'  And in fact the last part of the message
>>     is different than the literal in the program, so you've got a typo
>>     besides.  Please use cut&paste to show your actual code, your actual
>>     output.
>>
>>     After reading oscar's comment, my guess is that codeacademy (not
>>     Python) is complaining about the period at the end of your last
>>     literal string.
>>
>>     --
>>     DaveA
>>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/398caf72/attachment.html>

From msirenef at lightbird.net  Wed Apr 24 17:29:53 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Wed, 24 Apr 2013 11:29:53 -0400
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <5177F35B.2060308@virginmedia.com>
References: <5177F35B.2060308@virginmedia.com>
Message-ID: <5177FA71.3010609@lightbird.net>

On 04/24/2013 10:59 AM, Sydney Shall wrote:
> //I am a beginner just learning Python.
>
> I have come across the following usage for the first time.
>
>   totalViruses[i] /= float(numTrials)
>
> Does it mean? ; totalViruses[i] = totalViruses[i]/float(numTrials)
> -- 
> Sydney
>

That's exactly right, you can also use *= , +=, -=, |=, &= and
maybe there are others?  -m


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/


From davea at davea.name  Wed Apr 24 17:46:30 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 24 Apr 2013 11:46:30 -0400
Subject: [Tutor] trouble installing library
In-Reply-To: <1366816713.10224.YahooMailNeo@web121104.mail.ne1.yahoo.com>
References: <1366746654.2391.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<1366749212.51678.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<1366750985.69438.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<1366752493.85043.YahooMailNeo@web163802.mail.gq1.yahoo.com>
	<1366754390.65719.YahooMailNeo@web121102.mail.ne1.yahoo.com>
	<CACL+1asBH5L-NDkBzSKXLN0kJfEs3gkLvS02uXYuJdN-xncNZw@mail.gmail.com>
	<1366772498.81100.YahooMailNeo@web121106.mail.ne1.yahoo.com>
	<CACL+1avDGO2Pq32K_AkS8K1SHuAg4LZqyC0Bb081HJEeJYXdRg@mail.gmail.com>
	<1366807869.19889.YahooMailNeo@web121104.mail.ne1.yahoo.com>
	<CACL+1as4sSg05tcSe8nGZHpjcaqC95y975WRN9+uoyOfQkN6ew@mail.gmail.com>
	<1366816713.10224.YahooMailNeo@web121104.mail.ne1.yahoo.com>
Message-ID: <5177FE56.4090100@davea.name>

On 04/24/2013 11:18 AM, Lolo Lolo wrote:
>>> Microsoft's C/C++ runtime only
>>> uses double quotes. So just change it to the following:
>
>      >> python -c "import googlemaps"
>
> Thanks this solved the issue, now another issue has been thrown. Just not my day. after the 1st module error happens, they show the correct way to install google maps, i will show there results, then mine.
>
>              <SNIP>

>>> Reference: Parsing C++ Command-Line Arguments
>>> http://msdn.microsoft.com/en-us/library/17w5ykft%28v=vs.100%29
>
> C++ is behind the windows command line?
>

No, the Windows command line does no parsing at all.  It's just a 
string.  However, CPython is built using the Microsoft C (C++) compiler, 
so by default it uses their runtime library, with its quirks.

It would certainly be possible to write ones own argv builder, but by 
using the "standard" one, CPython is more consistent with other Windows 
apps, most of which now use the same library functions.

In Unix type systems, the command line implementation is very different. 
  I don't know if it's even possible to access the raw command line.

-- 
DaveA

From davea at davea.name  Wed Apr 24 17:52:38 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 24 Apr 2013 11:52:38 -0400
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <5177F35B.2060308@virginmedia.com>
References: <5177F35B.2060308@virginmedia.com>
Message-ID: <5177FFC6.1090904@davea.name>

On 04/24/2013 10:59 AM, Sydney Shall wrote:
> //I am a beginner just learning Python.
>

Welcome to the mailing list.  I hope you enjoy your experience with Python.


> I have come across the following usage for the first time.
>
>    totalViruses[i] /= float(numTrials)
>
> Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
>
>
As the others have said, that's exactly right, at least if 
totalViruses[i] is immutable, like an int or a float.

It's a subtle distinction, but for now, just remember that it's true for 
"numbers", but that somebody might redefine one of these operators for 
other object types.  They could not do that for numbers, however.


-- 
DaveA

From sparkle.plenty12481632 at gmail.com  Wed Apr 24 18:52:01 2013
From: sparkle.plenty12481632 at gmail.com (sparkle Plenty)
Date: Wed, 24 Apr 2013 12:52:01 -0400
Subject: [Tutor] Concatenating numeric data in Python 3.3
Message-ID: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>

What is the best way to concatenate packed numeric data?  I am building a
message to send to a device and it has a very specific header format and
variable length payload.  Converting to string, concatenating, and then
converting back to numeric introduced errors.  The tuple() function also
introduced errors.

The code is proprietary so I am not comfortable posting it.  I have been
programming in Python for a few weeks.  It is my first OOP language.  My
background, in the dim and distant past, is mainframe.

Any help would be greatly appreciated.  Thank you in advance.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/0ad20081/attachment.html>

From robert.day at merton.oxon.org  Wed Apr 24 19:21:01 2013
From: robert.day at merton.oxon.org (Rob Day)
Date: Wed, 24 Apr 2013 18:21:01 +0100
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
Message-ID: <CAH1RVih-k0EBa3poTUTW86YLaeLaZxEz+7NNC+YJMrMELowh+g@mail.gmail.com>

So, for example, you'd be trying to concatenate the binary data
01010101 and 10101010, and get 0101010110101010? You can do that by
shifting the bits:

>>> (0b01010101 << 8) + 0b10101010
21930

which is equivalent to:

>>> 0b0101010110101010
21930

You can also do it with numerical data:

>>> 0b10101010
170
>>> 0b01010101
85
>>> (85 << 8) + 170
21930
>>> "{:b}".format((85 << 8) + 170)
'101010110101010'


On 24 April 2013 17:52, sparkle Plenty <sparkle.plenty12481632 at gmail.com> wrote:
> What is the best way to concatenate packed numeric data?  I am building a
> message to send to a device and it has a very specific header format and
> variable length payload.  Converting to string, concatenating, and then
> converting back to numeric introduced errors.  The tuple() function also
> introduced errors.
>
> The code is proprietary so I am not comfortable posting it.  I have been
> programming in Python for a few weeks.  It is my first OOP language.  My
> background, in the dim and distant past, is mainframe.
>
> Any help would be greatly appreciated.  Thank you in advance.
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Robert K. Day
robert.day at merton.oxon.org

From davea at davea.name  Wed Apr 24 19:29:01 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 24 Apr 2013 13:29:01 -0400
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
Message-ID: <5178165D.2020306@davea.name>

On 04/24/2013 12:52 PM, sparkle Plenty wrote:
> What is the best way to concatenate packed numeric data?  I am building a
> message to send to a device and it has a very specific header format and
> variable length payload.  Converting to string, concatenating, and then
> converting back to numeric introduced errors.  The tuple() function also
> introduced errors.
>
> The code is proprietary so I am not comfortable posting it.  I have been
> programming in Python for a few weeks.  It is my first OOP language.  My
> background, in the dim and distant past, is mainframe.
>
> Any help would be greatly appreciated.  Thank you in advance.
>
>
>

Some clues would be useful.  For example, what form is your message 
going to be?  Presumably a byte string b"abc", not a real (Unicode) 
string.  There are no limitations on stuffing binary data into a byte 
string.  But not all byte strings make any sense as Unicode, as you have 
to pick a decoder when converting.

On the other hand, you could be just manipulating an array of unsigned 
char, which doesn't even pretend to represent a string.
Create one with
   import data
   data = array.array("B")
-- 
DaveA

From ramit.prasad at jpmorgan.com  Wed Apr 24 19:30:14 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Wed, 24 Apr 2013 17:30:14 +0000
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF4741834821B@SCACMX008.exchad.jpmchase.net>

sparkle Plenty wrote:
> Sent: Wednesday, April 24, 2013 11:52 AM
> To: Tutor at python.org
> Subject: [Tutor] Concatenating numeric data in Python 3.3
> 
> What is the best way to concatenate packed numeric data?? I am building a message to send to a device
> and it has a very specific header format and variable length payload.? Converting to string,
> concatenating, and then converting back to numeric introduced errors.? The tuple() function also
> introduced errors.
> 
> The code is proprietary so I am not comfortable posting it.? I have been programming in Python for?a
> few?weeks.? It is my first OOP language.? My background, in the dim and distant past, is mainframe.
> 
> Any help would be greatly appreciated.? Thank you in advance.

Try reducing the error section to the minimal amount of code (or create example that
has the same problem) and post that. 

Converting back and forth between strings and numeric types is often a sign of smelly 
code. Why do you need to convert back and forth?  Not that conversion is bad, just a 
sign of a possible design problem.

Repeated string concatenation can be a slow and wasteful procedure. 
Use str's join method to build a string.

>>> ','.join( [ 'a','b','c'] ) # Argument to join must be an iterable (list/set/etc) 
'a,b,c'                        # of strings. Convert data to str before joining.
>>> ' '.join( [ 'a','b','c'] )
'a b c'


~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.  

From sparkle.plenty12481632 at gmail.com  Wed Apr 24 20:23:26 2013
From: sparkle.plenty12481632 at gmail.com (sparkle Plenty)
Date: Wed, 24 Apr 2013 14:23:26 -0400
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF4741834821B@SCACMX008.exchad.jpmchase.net>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741834821B@SCACMX008.exchad.jpmchase.net>
Message-ID: <CABeS=HZ1az3TtU1ed6VG0wPK1oaSMMMXJnOe4N_EpGEOAP1TDg@mail.gmail.com>

Thanks to both of you for your assistance.
Since the completed message must be in hex, I also have an issue with
losing high order zeros during conversions, although the binary shift works
well for adding on to the end of the string.  I cannot pack string data,
and I cannot concatenate numbers, so the conversions, although smelly, were
what I knew to try.  I welcome the idea of abandoning that course of
action.  It didn't work anyway.

 I will have an unknown number of instances, each of which consists of 3
numeric values.  I tried packing each instance using struct.pack, then
converting to  a tuple, then concatenating.  This ran, but introduced
errors: in some instances, high order truncation of a leading zero in the
first of the 3 values.  This throws off the position of all data that
follows.  Error messages and error code are dependent on which technique is
being tried.  The most recent ones are:
TypeError: can't concat bytes to str
TypeError: Can't convert 'tuple' object to str implicitly




On Wed, Apr 24, 2013 at 1:30 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com>wrote:

> sparkle Plenty wrote:
> > Sent: Wednesday, April 24, 2013 11:52 AM
> > To: Tutor at python.org
> > Subject: [Tutor] Concatenating numeric data in Python 3.3
> >
> > What is the best way to concatenate packed numeric data?  I am building
> a message to send to a device
> > and it has a very specific header format and variable length payload.
> Converting to string,
> > concatenating, and then converting back to numeric introduced errors.
> The tuple() function also
> > introduced errors.
> >
> > The code is proprietary so I am not comfortable posting it.  I have been
> programming in Python for a
> > few weeks.  It is my first OOP language.  My background, in the dim and
> distant past, is mainframe.
> >
> > Any help would be greatly appreciated.  Thank you in advance.
>
> Try reducing the error section to the minimal amount of code (or create
> example that
> has the same problem) and post that.
>
> Converting back and forth between strings and numeric types is often a
> sign of smelly
> code. Why do you need to convert back and forth?  Not that conversion is
> bad, just a
> sign of a possible design problem.
>
> Repeated string concatenation can be a slow and wasteful procedure.
> Use str's join method to build a string.
>
> >>> ','.join( [ 'a','b','c'] ) # Argument to join must be an iterable
> (list/set/etc)
> 'a,b,c'                        # of strings. Convert data to str before
> joining.
> >>> ' '.join( [ 'a','b','c'] )
> 'a b c'
>
>
> ~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.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/5464ff51/attachment.html>

From ramit.prasad at jpmorgan.com  Wed Apr 24 20:45:07 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Wed, 24 Apr 2013 18:45:07 +0000
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <CABeS=HZ1az3TtU1ed6VG0wPK1oaSMMMXJnOe4N_EpGEOAP1TDg@mail.gmail.com>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741834821B@SCACMX008.exchad.jpmchase.net>
	<CABeS=HZ1az3TtU1ed6VG0wPK1oaSMMMXJnOe4N_EpGEOAP1TDg@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183483D3@SCACMX008.exchad.jpmchase.net>

Please post your response *after* the quoted context.

sparkle Plenty wrote:
> 
> Thanks to both of you for your assistance.
> Since the completed message?must be in hex, I also have an issue with losing high order zeros during
> conversions, although the binary shift works well for adding on to the end of the string.? I cannot
> pack string data, and I cannot concatenate?numbers, so the conversions, although smelly, were what I
> knew to try.? I welcome the idea of abandoning that course of action.? It didn't work anyway.
> 
> ?I will have an unknown number of instances, each of which consists of 3 numeric values.? I tried
> packing each instance using struct.pack, then converting to? a tuple, then concatenating.? This ran,
> but introduced errors: in?some instances,?high order truncation of?a leading zero?in the first of the
> 3 values.??This throws off the position of all data that follows.? Error messages and error code are
> dependent on which technique is being tried.? The most recent ones are:
> TypeError: can't concat bytes to str
> TypeError: Can't convert 'tuple' object to str implicitly
> 
> 

Can you give us the format and samples of the input and the output? We do not
need real data, often you can just use data of the same type but change values.

If you need hex, you can turn numbers into hex str by using the hex() built-in.

>>> ''.join([hex(15), hex(1239393), hex(49494)])
'0xf0x12e9610xc156' # Need to handle formatting

You may want to also look at the binascii module for some functions for 
converting data. Again, if you provide some sample output (and hopefully input) 
then we can help you better.


~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.  

From alan.gauld at btinternet.com  Wed Apr 24 21:07:33 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 24 Apr 2013 20:07:33 +0100
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <5177FFC6.1090904@davea.name>
References: <5177F35B.2060308@virginmedia.com> <5177FFC6.1090904@davea.name>
Message-ID: <kl9ahg$2d6$1@ger.gmane.org>

On 24/04/13 16:52, Dave Angel wrote:

>> Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
>>
> As the others have said, that's exactly right, at least if
> totalViruses[i] is immutable, like an int or a float.

What difference does immutability make here?
Even if totalViruses[i] is mutable (an object
or another mutable type) it would still work
provided it supported the division operator
for floats. Or am I missing something?

> It's a subtle distinction, but for now, just remember that it's true for
> "numbers", but that somebody might redefine one of these operators for
> other object types.  They could not do that for numbers, however.

Surely you could redefine it for a subclass of numbers too?
Or, again, am I missing something?

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


From eryksun at gmail.com  Wed Apr 24 21:09:27 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 24 Apr 2013 15:09:27 -0400
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <CABeS=HZ1az3TtU1ed6VG0wPK1oaSMMMXJnOe4N_EpGEOAP1TDg@mail.gmail.com>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741834821B@SCACMX008.exchad.jpmchase.net>
	<CABeS=HZ1az3TtU1ed6VG0wPK1oaSMMMXJnOe4N_EpGEOAP1TDg@mail.gmail.com>
Message-ID: <CACL+1asquGdq-NE9F4Tk3DbH1rfh2dBWoE2CjmWnM23bxF1whw@mail.gmail.com>

On Wed, Apr 24, 2013 at 2:23 PM, sparkle Plenty
<sparkle.plenty12481632 at gmail.com> wrote:
>  I will have an unknown number of instances, each of which consists of 3
> numeric values.  I tried packing each instance using struct.pack, then
> converting to  a tuple, then concatenating.  This ran, but introduced
> errors: in some instances, high order truncation of a leading zero in the
> first of the 3 values.  This throws off the position of all data that
> follows.  Error messages and error code are dependent on which technique is
> being tried.  The most recent ones are:
> TypeError: can't concat bytes to str
> TypeError: Can't convert 'tuple' object to str implicitly

If it's simply a matter of packing a number to a fixed number of
bytes, why not use the to_bytes method of a 3.x int?

    >>> b''.join(x.to_bytes(4, 'big') for x in [0x8badf00d,
0xd15ea5ed, 0xdeadd00d])
    b'\x8b\xad\xf0\r\xd1^\xa5\xed\xde\xad\xd0\r'

From alan.gauld at btinternet.com  Wed Apr 24 21:12:49 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 24 Apr 2013 20:12:49 +0100
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
Message-ID: <kl9ard$654$1@ger.gmane.org>

On 24/04/13 17:52, sparkle Plenty wrote:
> What is the best way to concatenate packed numeric data?

There are lots of options but one way to produce a byte string from 
(semi) arbitrary  values is to use the struct module.
It uses a format string to define the data format and lengths and then 
substitutes in the values it is given to 'pack'.

PS.
Its a bit like a PICT string in COBOL if your that kind
of mainframer!

If that doesn't help then we will need a bit more detail of the kind of 
thing you want. Even a made up example with just a couple of fields...

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


From oscar.j.benjamin at gmail.com  Wed Apr 24 21:32:06 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Wed, 24 Apr 2013 20:32:06 +0100
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <kl9ahg$2d6$1@ger.gmane.org>
References: <5177F35B.2060308@virginmedia.com> <5177FFC6.1090904@davea.name>
	<kl9ahg$2d6$1@ger.gmane.org>
Message-ID: <CAHVvXxQ6kDbf14T1kAZeexULSB7oZRuPqYuPxYLhPKOmnks8Ow@mail.gmail.com>

On 24 April 2013 20:07, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 24/04/13 16:52, Dave Angel wrote:
>
>>> Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
>>>
>> As the others have said, that's exactly right, at least if
>> totalViruses[i] is immutable, like an int or a float.
>
>
> What difference does immutability make here?
> Even if totalViruses[i] is mutable (an object
> or another mutable type) it would still work
> provided it supported the division operator
> for floats. Or am I missing something?

Yes.

>> It's a subtle distinction, but for now, just remember that it's true for
>> "numbers", but that somebody might redefine one of these operators for
>> other object types.  They could not do that for numbers, however.
>
> Surely you could redefine it for a subclass of numbers too?
> Or, again, am I missing something?

You can redefine it for numbers but it's just not typically done that
way in Python.

The subtle distinction that Dave is referring to is about modifying an
object in place vs rebinding a name to a newly created object. For
immutable objects a+=b will create a new object, the result of a+b and
bind that new object to the name a. For mutable objects a+=b typically
modifies the object a in place so that other references to the object
will also see the change.

Consider the following program:

def append_zeros(list1, list2):
    list1 = list1 + [0, 0, 0]
    list2 += [0, 0, 0]
    print(list1)
    print(list2)

outerlist1 = [1, 2, 3]
outerlist2 = [1, 2, 3]

append_zeros(outerlist1, outerlist2)

print(outerlist1)
print(outerlist2)

The output is:
[1, 2, 3, 0, 0, 0]
[1, 2, 3, 0, 0, 0]
[1, 2, 3]
[1, 2, 3, 0, 0, 0]

Which behaviour occurs is entirely up to the author of the __iadd__
method of the class in question. This method can modify and return
self or it can return a different object.


Oscar

From ramit.prasad at jpmorgan.com  Wed Apr 24 22:21:18 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Wed, 24 Apr 2013 20:21:18 +0000
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <CABeS=HY__rWzwdCk2V+ij-wxhT1V_kMwD0NaWOXxtcHhfwPGjQ@mail.gmail.com>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741834821B@SCACMX008.exchad.jpmchase.net>
	<CABeS=HZ1az3TtU1ed6VG0wPK1oaSMMMXJnOe4N_EpGEOAP1TDg@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF474183483D3@SCACMX008.exchad.jpmchase.net>
	<CABeS=HY__rWzwdCk2V+ij-wxhT1V_kMwD0NaWOXxtcHhfwPGjQ@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF47418348652@SCACMX008.exchad.jpmchase.net>

Thank you for not replying above, but please continue to CC the tutor list.

sparkle Plenty wrote:
> 
> On Wed, Apr 24, 2013 at 2:45 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote:
> Please post your response *after* the quoted context.
> 
> sparkle Plenty wrote:
> >
> > Thanks to both of you for your assistance.
> > Since the completed message?must be in hex, I also have an issue with losing high order zeros during
> > conversions, although the binary shift works well for adding on to the end of the string.? I cannot
> > pack string data, and I cannot concatenate?numbers, so the conversions, although smelly, were what I
> > knew to try.? I welcome the idea of abandoning that course of action.? It didn't work anyway.
> >
> > ?I will have an unknown number of instances, each of which consists of 3 numeric values.? I tried
> > packing each instance using struct.pack, then converting to? a tuple, then concatenating.? This ran,
> > but introduced errors: in?some instances,?high order truncation of?a leading zero?in the first of
> the
> > 3 values.??This throws off the position of all data that follows.? Error messages and error code are
> > dependent on which technique is being tried.? The most recent ones are:
> > TypeError: can't concat bytes to str
> > TypeError: Can't convert 'tuple' object to str implicitly
> >
> >
> Can you give us the format and samples of the input and the output? We do not
> need real data, often you can just use data of the same type but change values.
> 
> If you need hex, you can turn numbers into hex str by using the hex() built-in.
> 
> >>> ''.join([hex(15), hex(1239393), hex(49494)])
> '0xf0x12e9610xc156' # Need to handle formatting
> 
> You may want to also look at the binascii module for some functions for
> converting data. Again, if you provide some sample output (and hopefully input)
> then we can help you better.
> 
> 
> ~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.
> 
> Input is from? a gui so the first value is obtained from the identifier for the control the user
> changed:
> 1234
> The second value is associated with the first.
> 01
> The third value is, for instance, a switch on/off
> 01 or 00, let's say it's 00.
> 
> the output for this instance would need to be
> 0x04d20x010x00.

Are you sure you want the starting '0x' for each byte?

> 
> Here is my function as it stands now:
> 
> ? def conCatNumbers(numOne, numTwo, numThree):
> ??? global instanceGroup, lengthCounter, instanceCounter
> ??? print("Pre Pack:? ", numOne, " ", numTwo, " ", numThree)
> ??? packValues = struct.pack("HBB", numOne, numTwo, numThree)
> ??? print("Post Pack: ", packValues)
> ??? instanceValues = (packValues, )
> ??? print(instanceValues)
> ??? instanceGroup = (instanceGroup, )
> ??? instanceGroup = instanceGroup + instanceValues
> ??? lengthCounter += 4
> ??? instanceCounter += 1
> ??? return (instanceGroup, lengthCounter, instanceCounter)
> 
> It is the first function I have written, and?it is an ugly little spud.

Why are you using global variables? What purpose do they serve?
If you can provide the rationale for the global variables, chances
are we can suggest a better way to do that. I think you would be
better off having instanceGroup as a list and append to the list.
As it is right now instanceGroup is a weirdly nested list. Look at 
difference between the following two sets of code and output.

>>> blah = ()
>>> def foo():
...     global blah
...     instanceValues = ('\x04\xd2\x01\x00', )
...     blah = (blah,)
...     blah = blah + instanceValues
...     print blah
...     
>>> foo()
((), '\x04\xd2\x01\x00')
>>> foo()
(((), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00')
>>> foo()
((((), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00')
>>> foo()
(((((), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00')
>>> foo()
((((((), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00')

>>> blah = [] 
>>> def foo():
...     instanceValues = '\x04\xd2\x01\x00'
...     blah.append( instanceValues ) # module level object can be mutated without global keyword, 
                                      # just not reassigned (name binding).
...     print blah
...     
>>> foo()
['\x04\xd2\x01\x00']
>>> foo()
['\x04\xd2\x01\x00', '\x04\xd2\x01\x00']
>>> foo()
['\x04\xd2\x01\x00', '\x04\xd2\x01\x00', '\x04\xd2\x01\x00']
>>> foo()
['\x04\xd2\x01\x00', '\x04\xd2\x01\x00', '\x04\xd2\x01\x00', '\x04\xd2\x01\x00']


Your struct.pack() line seems fine, but you might want to specify
endian-ness as the default value may vary by architecture. 
(See http://en.wikipedia.org/wiki/Endian )

>>> struct.pack('>HBB', 1234,1,0 )
'\x04\xd2\x01\x00' # note location of 4 and d2
>>> struct.pack('<HBB', 1234,1,0 )
'\xd2\x04\x01\x00' # note location of 4 and d2 are swapped


[copied from above]
>     lengthCounter += 4
>     instanceCounter += 1
>     return (instanceGroup, lengthCounter, instanceCounter)

It is seems like that you are using these to keep track of length
or iterating over them. If you switch to list you can do something like:

for instance in instanceGroup:
   do_task(instance)
for index, instance in enumerate(instanceGroup): # useful if you want to know iteration number
    do_task(instance)
    if not index % 100: # log heartbeat every 100 iterations
        print('Went through {} iterations'.format(index))
instanceCounter = len(instanceGroup)
lengthCounter = instanceCounter*4 


~Ramit



From sparkle.plenty12481632 at gmail.com  Wed Apr 24 23:01:45 2013
From: sparkle.plenty12481632 at gmail.com (sparkle Plenty)
Date: Wed, 24 Apr 2013 17:01:45 -0400
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47418348652@SCACMX008.exchad.jpmchase.net>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741834821B@SCACMX008.exchad.jpmchase.net>
	<CABeS=HZ1az3TtU1ed6VG0wPK1oaSMMMXJnOe4N_EpGEOAP1TDg@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF474183483D3@SCACMX008.exchad.jpmchase.net>
	<CABeS=HY__rWzwdCk2V+ij-wxhT1V_kMwD0NaWOXxtcHhfwPGjQ@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF47418348652@SCACMX008.exchad.jpmchase.net>
Message-ID: <CABeS=HYf293Q=69rtNcxNMTSkxjkj2g9A1241uqJ8HsUx5vYBQ@mail.gmail.com>

On Wed, Apr 24, 2013 at 4:21 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com>wrote:

> Thank you for not replying above, but please continue to CC the tutor list.
>
> sparkle Plenty wrote:
> >
> > On Wed, Apr 24, 2013 at 2:45 PM, Prasad, Ramit <
> ramit.prasad at jpmorgan.com> wrote:
> > Please post your response *after* the quoted context.
> >
> > sparkle Plenty wrote:
> > >
> > > Thanks to both of you for your assistance.
> > > Since the completed message must be in hex, I also have an issue with
> losing high order zeros during
> > > conversions, although the binary shift works well for adding on to the
> end of the string.  I cannot
> > > pack string data, and I cannot concatenate numbers, so the
> conversions, although smelly, were what I
> > > knew to try.  I welcome the idea of abandoning that course of action.
> It didn't work anyway.
> > >
> > >  I will have an unknown number of instances, each of which consists of
> 3 numeric values.  I tried
> > > packing each instance using struct.pack, then converting to  a tuple,
> then concatenating.  This ran,
> > > but introduced errors: in some instances, high order truncation of a
> leading zero in the first of
> > the
> > > 3 values.  This throws off the position of all data that follows.
> Error messages and error code are
> > > dependent on which technique is being tried.  The most recent ones are:
> > > TypeError: can't concat bytes to str
> > > TypeError: Can't convert 'tuple' object to str implicitly
> > >
> > >
> > Can you give us the format and samples of the input and the output? We
> do not
> > need real data, often you can just use data of the same type but change
> values.
> >
> > If you need hex, you can turn numbers into hex str by using the hex()
> built-in.
> >
> > >>> ''.join([hex(15), hex(1239393), hex(49494)])
> > '0xf0x12e9610xc156' # Need to handle formatting
> >
> > You may want to also look at the binascii module for some functions for
> > converting data. Again, if you provide some sample output (and hopefully
> input)
> > then we can help you better.
> >
> >
> > ~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.
> >
> > Input is from  a gui so the first value is obtained from the identifier
> for the control the user
> > changed:
> > 1234
> > The second value is associated with the first.
> > 01
> > The third value is, for instance, a switch on/off
> > 01 or 00, let's say it's 00.
> >
> > the output for this instance would need to be
> > 0x04d20x010x00.
>
> Are you sure you want the starting '0x' for each byte?
>
> >
> > Here is my function as it stands now:
> >
> >   def conCatNumbers(numOne, numTwo, numThree):
> >     global instanceGroup, lengthCounter, instanceCounter
> >     print("Pre Pack:  ", numOne, " ", numTwo, " ", numThree)
> >     packValues = struct.pack("HBB", numOne, numTwo, numThree)
> >     print("Post Pack: ", packValues)
> >     instanceValues = (packValues, )
> >     print(instanceValues)
> >     instanceGroup = (instanceGroup, )
> >     instanceGroup = instanceGroup + instanceValues
> >     lengthCounter += 4
> >     instanceCounter += 1
> >     return (instanceGroup, lengthCounter, instanceCounter)
> >
> > It is the first function I have written, and it is an ugly little spud.
>
> Why are you using global variables? What purpose do they serve?
> If you can provide the rationale for the global variables, chances
> are we can suggest a better way to do that. I think you would be
> better off having instanceGroup as a list and append to the list.
> As it is right now instanceGroup is a weirdly nested list. Look at
> difference between the following two sets of code and output.
>
> >>> blah = ()
> >>> def foo():
> ...     global blah
> ...     instanceValues = ('\x04\xd2\x01\x00', )
> ...     blah = (blah,)
> ...     blah = blah + instanceValues
> ...     print blah
> ...
> >>> foo()
> ((), '\x04\xd2\x01\x00')
> >>> foo()
> (((), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00')
> >>> foo()
> ((((), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00')
> >>> foo()
> (((((), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'),
> '\x04\xd2\x01\x00')
> >>> foo()
> ((((((), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00'),
> '\x04\xd2\x01\x00'), '\x04\xd2\x01\x00')
>
> >>> blah = []
> >>> def foo():
> ...     instanceValues = '\x04\xd2\x01\x00'
> ...     blah.append( instanceValues ) # module level object can be mutated
> without global keyword,
>                                       # just not reassigned (name binding).
> ...     print blah
> ...
> >>> foo()
> ['\x04\xd2\x01\x00']
> >>> foo()
> ['\x04\xd2\x01\x00', '\x04\xd2\x01\x00']
> >>> foo()
> ['\x04\xd2\x01\x00', '\x04\xd2\x01\x00', '\x04\xd2\x01\x00']
> >>> foo()
> ['\x04\xd2\x01\x00', '\x04\xd2\x01\x00', '\x04\xd2\x01\x00',
> '\x04\xd2\x01\x00']
>
>
> Your struct.pack() line seems fine, but you might want to specify
> endian-ness as the default value may vary by architecture.
> (See http://en.wikipedia.org/wiki/Endian )
>
> >>> struct.pack('>HBB', 1234,1,0 )
> '\x04\xd2\x01\x00' # note location of 4 and d2
> >>> struct.pack('<HBB', 1234,1,0 )
> '\xd2\x04\x01\x00' # note location of 4 and d2 are swapped
>
>
> [copied from above]
> >     lengthCounter += 4
> >     instanceCounter += 1
> >     return (instanceGroup, lengthCounter, instanceCounter)
>
> It is seems like that you are using these to keep track of length
> or iterating over them. If you switch to list you can do something like:
>
> for instance in instanceGroup:
>    do_task(instance)
> for index, instance in enumerate(instanceGroup): # useful if you want to
> know iteration number
>     do_task(instance)
>     if not index % 100: # log heartbeat every 100 iterations
>         print('Went through {} iterations'.format(index))
> instanceCounter = len(instanceGroup)
> lengthCounter = instanceCounter*4
>
>
> ~Ramit
>
>
> Thank you so much!  I knew the Global statement was a cop-out, but I was
frustrated with the endless Unbounded Local Variable errors, and getting a
little wild-eyed and desperate as my project deadline approaches.  I will
implement the changes you suggested, and then retest.

 I have also searched the Tutor archives quite a lot, and noted a number of
websites that I will peruse for another online course (I have taken the one
at Python.org) so I can review class and function best practices.  It is
great to have someone to ask when I get stuck.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130424/cdfd82c8/attachment.html>

From ramit.prasad at jpmorgan.com  Wed Apr 24 23:30:12 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Wed, 24 Apr 2013 21:30:12 +0000
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <CABeS=HYf293Q=69rtNcxNMTSkxjkj2g9A1241uqJ8HsUx5vYBQ@mail.gmail.com>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741834821B@SCACMX008.exchad.jpmchase.net>
	<CABeS=HZ1az3TtU1ed6VG0wPK1oaSMMMXJnOe4N_EpGEOAP1TDg@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF474183483D3@SCACMX008.exchad.jpmchase.net>
	<CABeS=HY__rWzwdCk2V+ij-wxhT1V_kMwD0NaWOXxtcHhfwPGjQ@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF47418348652@SCACMX008.exchad.jpmchase.net>
	<CABeS=HYf293Q=69rtNcxNMTSkxjkj2g9A1241uqJ8HsUx5vYBQ@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF474183488EE@SCACMX008.exchad.jpmchase.net>

sparkle Plenty wrote:
> On Wed, Apr 24, 2013 at 4:21 PM, Prasad, Ramit <ramit.prasad at jpmorgan.com> wrote:
[snip]
> >
> > Here is my function as it stands now:
> >
> > ? def conCatNumbers(numOne, numTwo, numThree):
> > ??? global instanceGroup, lengthCounter, instanceCounter
> > ??? print("Pre Pack:? ", numOne, " ", numTwo, " ", numThree)
> > ??? packValues = struct.pack("HBB", numOne, numTwo, numThree)
> > ??? print("Post Pack: ", packValues)
> > ??? instanceValues = (packValues, )
> > ??? print(instanceValues)
> > ??? instanceGroup = (instanceGroup, )
> > ??? instanceGroup = instanceGroup + instanceValues
> > ??? lengthCounter += 4
> > ??? instanceCounter += 1
> > ??? return (instanceGroup, lengthCounter, instanceCounter)
> >
[snip]
> >>> blah = []
> >>> def foo():
> ... ? ? instanceValues = '\x04\xd2\x01\x00'
> ... ? ? blah.append( instanceValues ) # module level object can be mutated without global keyword,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? # just not reassigned (name binding).
> ... ? ? print blah
> ...
[snip]
> ~Ramit
> 
> Thank you so much!? I knew the Global statement was a cop-out, but I was frustrated with the endless
> Unbounded Local Variable errors, and getting a little wild-eyed and desperate as my project?deadline
> approaches.? I will implement the changes you suggested, and then retest.

Note that the above example is still using a global variable (actually a module level). 
You can eliminate it by just passing in the list as well.

def pack_without_globals(lst, numOne, numTwo, numThree):
    '''Pack values into hex bytes and append to lst.
    '''
    packValues = struct.pack("HBB", numOne, numTwo, numThree)
    lst.append( packValues )
    # No need to return lst because it is modified in place and the calling function should 
    # have access to the object anyway. 

> 
> ?I have also searched the Tutor archives quite a?lot, and?noted a number of websites that I will
> peruse for another online course (I have taken the one at Python.org) so I can review class and
> function best practices.? It is great to have someone to ask when I get stuck.

That is the purpose of this list. :)


~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.  

From gallen at openworld.co.za  Thu Apr 25 00:03:50 2013
From: gallen at openworld.co.za (Gareth Allen)
Date: Thu, 25 Apr 2013 00:03:50 +0200
Subject: [Tutor] Processing Linux command line output
Message-ID: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>

Hi all,

I'm trying to get the output of a command and split it into a list that I
can process.  What is the best way to go about doing this? In bash I would
use tools like grep, sed awk etc.

Here's an example:

ifconfig

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:84253 errors:0 dropped:0 overruns:0 frame:0
          TX packets:84253 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:11763964 (11.2 MiB)  TX bytes:11763964 (11.2 MiB)

I would like to end up with something like this in a file:

<unix timestamp>,lo,rx_errors=0,rx_dropped=0,rx_overruns=0,rx_frame=0

Thanks,
Gareth
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130425/d177426a/attachment.html>

From alan.gauld at btinternet.com  Thu Apr 25 00:41:06 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 24 Apr 2013 23:41:06 +0100
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <CAHVvXxQ6kDbf14T1kAZeexULSB7oZRuPqYuPxYLhPKOmnks8Ow@mail.gmail.com>
References: <5177F35B.2060308@virginmedia.com> <5177FFC6.1090904@davea.name>
	<kl9ahg$2d6$1@ger.gmane.org>
	<CAHVvXxQ6kDbf14T1kAZeexULSB7oZRuPqYuPxYLhPKOmnks8Ow@mail.gmail.com>
Message-ID: <kl9n1u$7cl$1@ger.gmane.org>

On 24/04/13 20:32, Oscar Benjamin wrote:
> On 24 April 2013 20:07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>> On 24/04/13 16:52, Dave Angel wrote:
>>
>>>> Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
>>>>
>>> As the others have said, that's exactly right, at least if
>>> totalViruses[i] is immutable, like an int or a float.
>>
>>
>> What difference does immutability make here?

> The subtle distinction that Dave is referring to is about modifying an
> object in place vs rebinding a name to a newly created object.

Sure, the bejhaviour with regard to the objects after the opreation is 
slightly different. But it makes noi dsifference to the duality of

x += n
v
x = x + n

The mutability issues are identical.

> Which behaviour occurs is entirely up to the author of the __iadd__
> method of the class in question. This method can modify and return
> self or it can return a different object.

This does make a difference because iadd (etc) can make a difference and 
I had forgotten that there are a separate set of operator methods for 
the ixxx operations, I was assuming that ixxx called the standard xxx. 
So in the special case of a user type implementing xxx differently to 
ixxx the behaviour might differ. But for all other cases I can think of 
the duality will still work? Apart from this exception

x += y

will yield the same result as

x = x + y

I think....

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


From bill at celestial.net  Thu Apr 25 00:35:15 2013
From: bill at celestial.net (Bill Campbell)
Date: Wed, 24 Apr 2013 15:35:15 -0700
Subject: [Tutor] Processing Linux command line output
In-Reply-To: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>
References: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>
Message-ID: <20130424223514.GA13114@ayn.mi.celestial.com>

On Thu, Apr 25, 2013, Gareth Allen wrote:
>
>   Hi all,
>   I'm trying to get the output of a command and split it into a list that
>   I can process.  What is the best way to go about doing this? In bash I
>   would use tools like grep, sed awk etc.

The old way to do this uses os.popen

import os

fh = os.popen('ifconfig')
for line in fh:
	# scan line here

The more modern way to handle this is using the subprocess module
with something like:

from subprocess import PIPE, Popen
fh = Popen('ifconfig', stdout=PIPE).stdout
...

Bill
-- 
INTERNET:   bill at celestial.com  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
Voice:          (206) 236-1676  Mercer Island, WA 98040-0820
Fax:            (206) 232-9186  Skype: jwccsllc (206) 855-5792

When the customer has beaten upon you long enough, give him what he asks
for, instead of what he needs.  This is very strong medicine, and is
normally only required once.
    -- The Consultant's Curse:

From ramit.prasad at jpmorgan.com  Thu Apr 25 00:50:57 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Wed, 24 Apr 2013 22:50:57 +0000
Subject: [Tutor] Processing Linux command line output
In-Reply-To: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>
References: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF47418348BDA@SCACMX008.exchad.jpmchase.net>

Gareth Allen wrote:
> Hi all,
> 
> I'm trying to get the output of a command and split it into a list that I can process. ?What is the
> best way to go about doing this? In bash I would use tools like grep, sed awk etc.
> 
> Here's an example:
> 
> ifconfig
> 
> lo ? ? ? ?Link encap:Local Loopback
> ? ? ? ? ? inet addr:127.0.0.1 ?Mask:255.0.0.0
> ? ? ? ? ? inet6 addr: ::1/128 Scope:Host
> ? ? ? ? ? UP LOOPBACK RUNNING ?MTU:16436 ?Metric:1
> ? ? ? ? ? RX packets:84253 errors:0 dropped:0 overruns:0 frame:0
> ? ? ? ? ? TX packets:84253 errors:0 dropped:0 overruns:0 carrier:0
> ? ? ? ? ? collisions:0 txqueuelen:0
> ? ? ? ? ? RX bytes:11763964 (11.2 MiB) ?TX bytes:11763964 (11.2 MiB)
> 
> I would like to end up with something like this in a file:
> 
> <unix timestamp>,lo,rx_errors=0,rx_dropped=0,rx_overruns=0,rx_frame=0
> 

Look at the subprocess module it is better than os.system().
http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate


>>> process = subprocess.Popen(['/sbin/ifconfig'], stdout=subprocess.PIPE)
>>> output = process.communicate() # block until job finishes then return 
                                   # (stdout, stderr)
>>> print output[0] # do something with output

It is sometimes tempting using shell=True (it is False by default),
but it can be insecure and should be avoided when possible.


~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.  

From alan.gauld at btinternet.com  Thu Apr 25 00:56:32 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Wed, 24 Apr 2013 23:56:32 +0100
Subject: [Tutor] Processing Linux command line output
In-Reply-To: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>
References: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>
Message-ID: <kl9nus$g6g$1@ger.gmane.org>

On 24/04/13 23:03, Gareth Allen wrote:

> I'm trying to get the output of a command

The subprocess module is the officially endorsed way of doing that 
nowadays. The docs show many use cases depending on what you need.
That will let you captiure the output as a set of strings.

> and split it into a list that I can process.

You can use the string methods to manipulate the output
You probably want the lines separated then use the
strip() and startswith() methods to identify the lines you are 
interested in.

For each line you might use slicing for fixed width fields or
find() to get the starting index of your substrings or maybe
split() to separate by colons.

As a last resort use regex via the re module, but hopefully
you won't need that

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


From oscar.j.benjamin at gmail.com  Thu Apr 25 00:58:52 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Wed, 24 Apr 2013 23:58:52 +0100
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <kl9n1u$7cl$1@ger.gmane.org>
References: <5177F35B.2060308@virginmedia.com> <5177FFC6.1090904@davea.name>
	<kl9ahg$2d6$1@ger.gmane.org>
	<CAHVvXxQ6kDbf14T1kAZeexULSB7oZRuPqYuPxYLhPKOmnks8Ow@mail.gmail.com>
	<kl9n1u$7cl$1@ger.gmane.org>
Message-ID: <CAHVvXxRqf5N=c2Qy05x04P-XWdD53EWnvTtW7ythYj3XbjGPxA@mail.gmail.com>

On 24 April 2013 23:41, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 24/04/13 20:32, Oscar Benjamin wrote:
>>
>> On 24 April 2013 20:07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>>>
>>> On 24/04/13 16:52, Dave Angel wrote:
>>>
>>>>> Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
>>>>>
>>>> As the others have said, that's exactly right, at least if
>>>> totalViruses[i] is immutable, like an int or a float.
>>>
>>> What difference does immutability make here?
>
>> The subtle distinction that Dave is referring to is about modifying an
>> object in place vs rebinding a name to a newly created object.
>
> Sure, the bejhaviour with regard to the objects after the opreation is
> slightly different. But it makes noi dsifference to the duality of
>
> x += n
> v
> x = x + n
>
> The mutability issues are identical.

Mutability of Python objects is a convention rather than any hard
property of the object itself. One part of that convention is whether
or not __iadd__ returns a new object or mutates in place.

>
>> Which behaviour occurs is entirely up to the author of the __iadd__
>> method of the class in question. This method can modify and return
>> self or it can return a different object.
>
> This does make a difference because iadd (etc) can make a difference and I
> had forgotten that there are a separate set of operator methods for the ixxx
> operations, I was assuming that ixxx called the standard xxx.

It does if __ixxx__ is not defined:

>>> class A(object):
...   def __add__(left, right):
...     print('Add called')
...     return 'whatever'
...
>>> a = A()
>>> a + 1
Add called
'whatever'
>>> b = a+1
Add called
>>> b
'whatever'
>>> a += 1  # Calls __add__
Add called
>>> a
'whatever'
>>> class B(object):
...   def __add__(left, right):
...     print('Add called')
...     return 'whatever'
...   def __iadd__(self, right):
...     print('iAdd called')
...     return 'something else'
...
>>> b = B()
>>> b + 1
Add called
'whatever'
>>> b += 1
iAdd called
>>> b
'something else'

> So in the
> special case of a user type implementing xxx differently to ixxx the
> behaviour might differ. But for all other cases I can think of the duality
> will still work? Apart from this exception
>
> x += y
>
> will yield the same result as
>
> x = x + y
>
> I think....

By convention mutable types always implement __ixxx__ differently from
__xxx__. For lists __iadd__ is the same as extend and mutates the
existing list. For numpy arrays __ixxx__ modifies elements in place so
that array+=val will add val to all elements of array in-place, rather
then creating a new array. This always makes a difference if there are
other references to the object (as in the example I gave).

And here's another example:
>>> c = ([],)
>>> c
([],)
>>> c[0] = c[0] + [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> c
([],)
>>> c[0] += [1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> c
([1],)


Oscar

From davea at davea.name  Thu Apr 25 01:08:46 2013
From: davea at davea.name (Dave Angel)
Date: Wed, 24 Apr 2013 19:08:46 -0400
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <CAHVvXxRqf5N=c2Qy05x04P-XWdD53EWnvTtW7ythYj3XbjGPxA@mail.gmail.com>
References: <5177F35B.2060308@virginmedia.com> <5177FFC6.1090904@davea.name>
	<kl9ahg$2d6$1@ger.gmane.org>
	<CAHVvXxQ6kDbf14T1kAZeexULSB7oZRuPqYuPxYLhPKOmnks8Ow@mail.gmail.com>
	<kl9n1u$7cl$1@ger.gmane.org>
	<CAHVvXxRqf5N=c2Qy05x04P-XWdD53EWnvTtW7ythYj3XbjGPxA@mail.gmail.com>
Message-ID: <517865FE.6080201@davea.name>

On 04/24/2013 06:58 PM, Oscar Benjamin wrote:
> On 24 April 2013 23:41, Alan Gauld <alan.gauld at btinternet.com> wrote:
>> On 24/04/13 20:32, Oscar Benjamin wrote:
>>>
>>> On 24 April 2013 20:07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>>>>
>>>> On 24/04/13 16:52, Dave Angel wrote:
>>>>
>>>>>> Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
>>>>>>
>>>>> As the others have said, that's exactly right, at least if
>>>>> totalViruses[i] is immutable, like an int or a float.
>>>>
>>>> What difference does immutability make here?
>>

Thanks for your help Oscar.  I was trying to keep it simple for a 
beginner.  So I deliberately did not elaborate on the exception.  But 
the one I had in mind was the behavior of a list, when += is used.

a = [1,2,3]
b = a
b += [4]     versus     b = b + [4]

The former would change a, while the latter would not.

If += were a literal substitution, like a macro, then this distinction 
could not happen.

So all I said was for immutables (and int and float are immutable), the 
statement was true.



-- 
DaveA

From amitsaha.in at gmail.com  Thu Apr 25 01:11:05 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Thu, 25 Apr 2013 09:11:05 +1000
Subject: [Tutor] Processing Linux command line output
In-Reply-To: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>
References: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>
Message-ID: <CANODV3kaNQvdqPq2-qba4eAsBF1-L6MNGqB3GqF4oRgY4q=RRA@mail.gmail.com>

Hi Gareth,

On Thu, Apr 25, 2013 at 8:03 AM, Gareth Allen <gallen at openworld.co.za> wrote:
> Hi all,
>
> I'm trying to get the output of a command and split it into a list that I
> can process.  What is the best way to go about doing this? In bash I would
> use tools like grep, sed awk etc.
>
> Here's an example:
>
> ifconfig
>
> lo        Link encap:Local Loopback
>           inet addr:127.0.0.1  Mask:255.0.0.0
>           inet6 addr: ::1/128 Scope:Host
>           UP LOOPBACK RUNNING  MTU:16436  Metric:1
>           RX packets:84253 errors:0 dropped:0 overruns:0 frame:0
>           TX packets:84253 errors:0 dropped:0 overruns:0 carrier:0
>           collisions:0 txqueuelen:0
>           RX bytes:11763964 (11.2 MiB)  TX bytes:11763964 (11.2 MiB)
>
> I would like to end up with something like this in a file:
>
> <unix timestamp>,lo,rx_errors=0,rx_dropped=0,rx_overruns=0,rx_frame=0

I think there are two parts to your question:

1. How to execute a command and get its output?
2. How to process that output to get the desired information using
text processing/etc?

I will start by first discussing (1). You will find one of the
functions in the 'subprocess' module useful for this. For example, the
subprocess.check_output() function [1] executes your command and
returns the output as a byte string.

Coming to your second questions, once you have the string, you can
then use string functions on it to extract the information you want.
Things like indexing, slicing, stripping and splitting becomes useful
then.

Let's see a simple example. 'who -b' command returns the system boot time:

$ who -b
         system boot  2013-04-13 09:00

Now, let's see how we can extract the date + time only from the above output.

First, we execute the command and store the output in 'output':

>>> output = subprocess.check_output(['who','-b'])

The result you get will be something like this:

>>> output
'         system boot  2013-04-13 09:00\n'

Note there are leading whitespaces and a trailing newline. So we will remove it:

>>> output = output.strip()
>>> output
'system boot  2013-04-13 09:00'

Now, we need to extract the date and time, leaving the string out.
Let's 'tokenize' it:

>>> output.split()
['system', 'boot', '2013-04-13', '09:00']

So, now you have a list of which the 3rd and 4th items are the date
and time respectively:

>>> output.split()[2:]
['2013-04-13', '09:00']


You can combine all the operations into:

>>> subprocess.check_output(['who','-b']).strip().split()[2:]
['2013-04-13', '09:00']


Well, that was a very simple example. A lot of things you will end up
doing will however involve operations such as above. You can also use
the 're' module to use regular expressions to retrieve information
perhaps more intelligently [2].

If you are interested for some related examples, I would like to point
you to couple of Python modules I was putting together [3]. In
readproc.py, I am extracting information from /proc and in pylinux.py
you will see a number of examples showing extracting information from
'subprocess.check_output()' calls.

I put together a list of resources to help someone who may be
interested in such tasks as yours for an article of mine. Here it is
[4].

[1] http://docs.python.org/2/library/subprocess.html#subprocess.check_output
[2] http://docs.python.org/2/library/re.html
[3] https://github.com/amitsaha/pylinux/tree/master/pylinux
[4] https://gist.github.com/amitsaha/4964491


Hope that helps.

Best,Amit.


--
http://amitsaha.github.com/

From ramit.prasad at jpmorgan.com  Thu Apr 25 01:02:54 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Wed, 24 Apr 2013 23:02:54 +0000
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <kl9n1u$7cl$1@ger.gmane.org>
References: <5177F35B.2060308@virginmedia.com> <5177FFC6.1090904@davea.name>
	<kl9ahg$2d6$1@ger.gmane.org>
	<CAHVvXxQ6kDbf14T1kAZeexULSB7oZRuPqYuPxYLhPKOmnks8Ow@mail.gmail.com>
	<kl9n1u$7cl$1@ger.gmane.org>
Message-ID: <5B80DD153D7D744689F57F4FB69AF47418348C42@SCACMX008.exchad.jpmchase.net>

Alan Gauld wrote:
> On 24/04/13 20:32, Oscar Benjamin wrote:
> > On 24 April 2013 20:07, Alan Gauld <alan.gauld at btinternet.com> wrote:
> >> On 24/04/13 16:52, Dave Angel wrote:
> >>
> >>>> Does it mean? ;  totalViruses[i] = totalViruses[i]/float(numTrials)
> >>>>
> >>> As the others have said, that's exactly right, at least if
> >>> totalViruses[i] is immutable, like an int or a float.
> >>
> >>
> >> What difference does immutability make here?
> 
> > The subtle distinction that Dave is referring to is about modifying an
> > object in place vs rebinding a name to a newly created object.
> 
> Sure, the bejhaviour with regard to the objects after the opreation is
> slightly different. But it makes noi dsifference to the duality of
> 
> x += n
> v
> x = x + n
> 
> The mutability issues are identical.
> 
> > Which behaviour occurs is entirely up to the author of the __iadd__
> > method of the class in question. This method can modify and return
> > self or it can return a different object.

Actually being able to return anything is true of even non iXXX 
methods like __div__. That's why without code, it is impossible
to say for sure, but probably it does what is expected.

>>> class Foo(object):
...     def __div__(self, num):
...         return 'shanana'*num # Bad!
...     
>>> z  = Foo()
>>> z /= 2
>>> z
'shananashanana'

> 
> This does make a difference because iadd (etc) can make a difference and
> I had forgotten that there are a separate set of operator methods for
> the ixxx operations, I was assuming that ixxx called the standard xxx.
> So in the special case of a user type implementing xxx differently to
> ixxx the behaviour might differ. But for all other cases I can think of
> the duality will still work? Apart from this exception
> 
> x += y
> 
> will yield the same result as
> 
> x = x + y
> 
> I think....

The only usecase (among built-ins) that I could find to contradict 
the statement, but I think it is a special case.

>>> a = [1,2,3] 
>>> b = (a,'c')
>>> b[0]+= [4]
TypeError: 'tuple' object does not support item assignment

>>> print b
([1, 2, 3, 4], 'c')
>>> b[0] = b[0] + [5]
TypeError: 'tuple' object does not support item assignment

>>> print b
([1, 2, 3, 4], 'c')


~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.  

From eryksun at gmail.com  Thu Apr 25 01:23:49 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 24 Apr 2013 19:23:49 -0400
Subject: [Tutor] Concatenating numeric data in Python 3.3
In-Reply-To: <5B80DD153D7D744689F57F4FB69AF47418348652@SCACMX008.exchad.jpmchase.net>
References: <CABeS=HbZ5vSMz9XfYrgZO0=PmcpZevz9C6CG4OOp_G3Dnym-hA@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741834821B@SCACMX008.exchad.jpmchase.net>
	<CABeS=HZ1az3TtU1ed6VG0wPK1oaSMMMXJnOe4N_EpGEOAP1TDg@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF474183483D3@SCACMX008.exchad.jpmchase.net>
	<CABeS=HY__rWzwdCk2V+ij-wxhT1V_kMwD0NaWOXxtcHhfwPGjQ@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF47418348652@SCACMX008.exchad.jpmchase.net>
Message-ID: <CACL+1avZ6Gy=MDZbJrS-QY8Z+oUhmUgd77ofd-Oh8ZdDpdoZdg@mail.gmail.com>

On Wed, Apr 24, 2013 at 4:21 PM, Prasad, Ramit
<ramit.prasad at jpmorgan.com> wrote:
> Your struct.pack() line seems fine, but you might want to specify
> endian-ness as the default value may vary by architecture.
> (See http://en.wikipedia.org/wiki/Endian )
>
>>>> struct.pack('>HBB', 1234,1,0 )
> '\x04\xd2\x01\x00' # note location of 4 and d2
>>>> struct.pack('<HBB', 1234,1,0 )
> '\xd2\x04\x01\x00' # note location of 4 and d2 are swapped

struct.pack returns bytes in 3.x, not a string as shown above.
Remember to use b''.join instead of ''.join if the groups are being
joined into a larger buffer.

From alan.gauld at btinternet.com  Thu Apr 25 01:29:14 2013
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Thu, 25 Apr 2013 00:29:14 +0100 (BST)
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <CAHVvXxRqf5N=c2Qy05x04P-XWdD53EWnvTtW7ythYj3XbjGPxA@mail.gmail.com>
References: <5177F35B.2060308@virginmedia.com> <5177FFC6.1090904@davea.name>
	<kl9ahg$2d6$1@ger.gmane.org>
	<CAHVvXxQ6kDbf14T1kAZeexULSB7oZRuPqYuPxYLhPKOmnks8Ow@mail.gmail.com>
	<kl9n1u$7cl$1@ger.gmane.org>
	<CAHVvXxRqf5N=c2Qy05x04P-XWdD53EWnvTtW7ythYj3XbjGPxA@mail.gmail.com>
Message-ID: <1366846154.44330.YahooMailNeo@web186002.mail.ir2.yahoo.com>


>By convention mutable types always implement __ixxx__ differently from
>__xxx__.?
>
>
>Really? That's a convention I've not come across before.
>
>
>And here's another example:
>
>>>> c = ([],)
>>>> c[0] += [1]
>
>Traceback (most recent call last):
>? File "<stdin>", line 1, in <module>
>TypeError: 'tuple' object does not support item assignment
>>>> c
>([1],)
>Good catch, I should have thought about that because I have seen it before.
Yes, that is an example where the duality breaks (although at least it warns?
you via the exception).

Thanks,

Alan G
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130425/b617591d/attachment-0001.html>

From bgailer at gmail.com  Thu Apr 25 01:49:43 2013
From: bgailer at gmail.com (bob gailer)
Date: Wed, 24 Apr 2013 19:49:43 -0400
Subject: [Tutor] Processing Linux command line output
In-Reply-To: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>
References: <CAOH=wyzv1uayBMjTg4XYi7CQWtJ4Hz_bwxi9fOMFY7d2+0ZFsQ@mail.gmail.com>
Message-ID: <51786F97.3000208@gmail.com>

On 4/24/2013 6:03 PM, Gareth Allen wrote:
> Hi all,
>
> I'm trying to get the output of a command and split it into a list 
> that I can process.  What is the best way to go about doing this? In 
> bash I would use tools like grep, sed awk etc.
Why do it in Python, given you already have a bash solution?

-- 
Bob Gailer
919-636-4239
Chapel Hill NC


From eryksun at gmail.com  Thu Apr 25 01:50:23 2013
From: eryksun at gmail.com (eryksun)
Date: Wed, 24 Apr 2013 19:50:23 -0400
Subject: [Tutor] totalViruses[i] /= float(numTrials),
In-Reply-To: <CAHVvXxRqf5N=c2Qy05x04P-XWdD53EWnvTtW7ythYj3XbjGPxA@mail.gmail.com>
References: <5177F35B.2060308@virginmedia.com> <5177FFC6.1090904@davea.name>
	<kl9ahg$2d6$1@ger.gmane.org>
	<CAHVvXxQ6kDbf14T1kAZeexULSB7oZRuPqYuPxYLhPKOmnks8Ow@mail.gmail.com>
	<kl9n1u$7cl$1@ger.gmane.org>
	<CAHVvXxRqf5N=c2Qy05x04P-XWdD53EWnvTtW7ythYj3XbjGPxA@mail.gmail.com>
Message-ID: <CACL+1auUU_quOSZQxj_4xd8mYNgC_+n8wH+=vUo7Z5Vpyb-P3A@mail.gmail.com>

On Wed, Apr 24, 2013 at 6:58 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> And here's another example:
>>>> c = ([],)
>>>> c
> ([],)
>>>> c[0] = c[0] + [1]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'tuple' object does not support item assignment
>>>> c
> ([],)
>>>> c[0] += [1]
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: 'tuple' object does not support item assignment
>>>> c
> ([1],)

The interpreter always uses a STORE operation after an in-place
operation because it doesn't know if the target object was mutated
in-place -- not with how it's currently implemented in ceval.c (in
principle it could). This leads to half-completed operations that
raise a TypeError like this when it tries to store the mutated object
back to an immutable container. This can happen with any object that
doesn't support assigning to subscripts or attributes, not just a
tuple.

From robertvstepp at gmail.com  Thu Apr 25 06:11:40 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Wed, 24 Apr 2013 23:11:40 -0500
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
Message-ID: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>

In my on again, off again studies of Python I am stumped on something
that ought to be trivial, but I am not seeing it. When I run  this
program (only the part up to where the error occurs is shown):

import random

numberToGuess = random.randint(1, 20)
numberOfGuesses = 0

print("Hello! What is your name?")
playerName = input()

...everything works fine from IDLE. However, in the Windows command prompt:


E:\Programs\Python\IYOCGwPy\Ch4>python -V
Python 3.3.1

E:\Programs\Python\IYOCGwPy\Ch4>guess.py
Hello! What is your name?
boB
Traceback (most recent call last):
  File "E:\Programs\Python\IYOCGwPy\Ch4\guess.py", line 13, in <module>
    playerName = input()
  File "<string>", line 1, in <module>
NameError: name 'boB' is not defined

E:\Programs\Python\IYOCGwPy\Ch4>

This has me totally puzzled. I thought it might have something to do
with the fact that I also have Python 2.7 installed, so I removed it
from the path variable and also did the check for version that you see
above.

Okay, the thought occurred to me to put my input in quotes: 'boB' ,
and I see this works. But why does the command prompt force me to put
my strings inside quotes? Perhaps I am too sleepy. It seems I should
understand why this is so from some other questions I have asked, but
I am not putting it together.

Thanks in advance!
boB

From steve at pearwood.info  Thu Apr 25 06:26:52 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Thu, 25 Apr 2013 14:26:52 +1000
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
Message-ID: <5178B08C.3040007@pearwood.info>

On 25/04/13 14:11, boB Stepp wrote:
> In my on again, off again studies of Python I am stumped on something
> that ought to be trivial, but I am not seeing it. When I run  this
> program (only the part up to where the error occurs is shown):
>
> import random
>
> numberToGuess = random.randint(1, 20)
> numberOfGuesses = 0
>
> print("Hello! What is your name?")
> playerName = input()
>
> ...everything works fine from IDLE. However, in the Windows command prompt:
>
>
> E:\Programs\Python\IYOCGwPy\Ch4>python -V
> Python 3.3.1

Here you are explicitly calling "python". Windows searches the path for the first version of Python it can find, and finds Python 3.3.1.


> E:\Programs\Python\IYOCGwPy\Ch4>guess.py


Here you are telling Windows to look up the file association for .py files. It locates some program, and runs it with guess.py as the argument. Looking at the result:


> Hello! What is your name?
> boB
> Traceback (most recent call last):
>    File "E:\Programs\Python\IYOCGwPy\Ch4\guess.py", line 13, in <module>
>      playerName = input()
>    File "<string>", line 1, in <module>
> NameError: name 'boB' is not defined


this is obviously Python 2.x rather than 3.3.1. You can check that by putting these two lines at the very beginning of the program:

import sys
print(sys.version)


My bet is that if you run it like this:


python guess.py


it will print "3.3.1" and the program will work, but when you run it like this:


guess.py


it will print 2.something and then fail.



> E:\Programs\Python\IYOCGwPy\Ch4>
>
> This has me totally puzzled. I thought it might have something to do
> with the fact that I also have Python 2.7 installed, so I removed it
> from the path variable and also did the check for version that you see
> above.

There's your bunny. Just because you remove it from the search path doesn't mean that Windows won't use it.

You might like to remove Python 2.7 altogether, or at least unassociate it from the .py file extension.



-- 
Steven

From eryksun at gmail.com  Thu Apr 25 06:36:40 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 25 Apr 2013 00:36:40 -0400
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
Message-ID: <CACL+1auCfym7f7Bf=FOxNYK6xDXswad3sRFF2iGxXHOr2MATpA@mail.gmail.com>

On Thu, Apr 25, 2013 at 12:11 AM, boB Stepp <robertvstepp at gmail.com> wrote:
> NameError: name 'boB' is not defined
>
> E:\Programs\Python\IYOCGwPy\Ch4>
>
> This has me totally puzzled. I thought it might have something to do
> with the fact that I also have Python 2.7 installed, so I removed it
> from the path variable and also did the check for version that you see
> above.

In 2.x the input() function evaluates the input string; typically
you'd use raw_input() instead.

.py files need to be associated with %windir%\py.exe. Additionally you
need a py.ini in %localappdata% if you want to set Python 3 as the
default.

    C:\>assoc .py
    .py=Python.File

    C:\>ftype Python.File
    Python.File="C:\Windows\py.exe" "%1" %*

    C:\>type "%localappdata%\py.ini"
    [defaults]
    python=3

    C:\>py -V
    Python 3.3.1

    C:\>py -2.7 -V
    Python 2.7.3

If .py files are set up to use py,.exe, then you can use a shebang on
the first line to set the interpreter a script should use:

    #!/usr/bin/env python3

or for the highest 2.x installed:

    #!/usr/bin/env python2

From dyoo at hashcollision.org  Thu Apr 25 06:51:24 2013
From: dyoo at hashcollision.org (Danny Yoo)
Date: Wed, 24 Apr 2013 22:51:24 -0600
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
Message-ID: <CAGZAPF4MMX95BVtN+eybKmAsg_RnTbPvZmi7fJ6ew3ASUasveg@mail.gmail.com>

On Wed, Apr 24, 2013 at 10:11 PM, boB Stepp <robertvstepp at gmail.com> wrote:
> In my on again, off again studies of Python I am stumped on something
> that ought to be trivial, but I am not seeing it. When I run  this
> program (only the part up to where the error occurs is shown):
>
> import random
>
> numberToGuess = random.randint(1, 20)
> numberOfGuesses = 0
>
> print("Hello! What is your name?")
> playerName = input()


Hi Bob,

[The following note is Python 2.0 specific.  In Python 3, input() is
semantically different, and safe.]

If you are using Python 2.0, don't use the input() function here to
read strings.  It is not safe: backing it is an implicit eval(), and
eval() is dangerous, especially for beginners who won't have the
background to understand the security implications.

Example: if you enter in the following strange-looking input:

    (lambda x: x(x))(lambda x:x(x))

then this will crash your program due to a stack overflow.  And this
is relatively safe compared to the other craziness you can enter into
input().  This is exactly why tutorials (and most Python programs in
general) should _not_ use input(): it's dangerous in the wrong hands.

Rather, use raw_input() instead.


In Python 3.0, unfortunately, there's going to be a lot of confusion
because input() in Python 3.0 has the behavior of Python 2.0's
raw_input().

From marc.tompkins at gmail.com  Thu Apr 25 09:41:21 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 25 Apr 2013 00:41:21 -0700
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <CACL+1auCfym7f7Bf=FOxNYK6xDXswad3sRFF2iGxXHOr2MATpA@mail.gmail.com>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
	<CACL+1auCfym7f7Bf=FOxNYK6xDXswad3sRFF2iGxXHOr2MATpA@mail.gmail.com>
Message-ID: <CAKK8jXZOzXMZTpS-wkN8-jGZM+5MLK=2XYTSgL1RbDeaT_gnNA@mail.gmail.com>

On Wed, Apr 24, 2013 at 9:36 PM, eryksun <eryksun at gmail.com> wrote:

> .py files need to be associated with %windir%\py.exe.


NO!

%windir% means "the directory where Windows is installed", usually (but not
always) C:\Windows.  You're saying that there needs to be a py.exe in the
Windows directory - this is absolutely not true.  You might have it set up
that way on your machine, but it's not standard and absolutely not
recommended.

To the original poster: please disregard.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130425/cbdb0994/attachment-0001.html>

From eryksun at gmail.com  Thu Apr 25 09:51:23 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 25 Apr 2013 03:51:23 -0400
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <CAKK8jXZOzXMZTpS-wkN8-jGZM+5MLK=2XYTSgL1RbDeaT_gnNA@mail.gmail.com>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
	<CACL+1auCfym7f7Bf=FOxNYK6xDXswad3sRFF2iGxXHOr2MATpA@mail.gmail.com>
	<CAKK8jXZOzXMZTpS-wkN8-jGZM+5MLK=2XYTSgL1RbDeaT_gnNA@mail.gmail.com>
Message-ID: <CACL+1as3X=pGPeppGc71nD1aa7wigZvF_5e44EQhHrdkxDTikA@mail.gmail.com>

On Thu, Apr 25, 2013 at 3:41 AM, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> On Wed, Apr 24, 2013 at 9:36 PM, eryksun <eryksun at gmail.com> wrote:
>>
>> .py files need to be associated with %windir%\py.exe.
>
>
> NO!
>
> %windir% means "the directory where Windows is installed", usually (but not
> always) C:\Windows.  You're saying that there needs to be a py.exe in the
> Windows directory - this is absolutely not true.  You might have it set up
> that way on your machine, but it's not standard and absolutely not
> recommended.
>
> To the original poster: please disregard.

boB has 3.3.1 installed. The official Windows installer for 3.3
installs the new pylauncher to %windir%. It doesn't give you an option
to do otherwise. Have you read PEP 397? Have you installed 3.3 on
Windows?

http://www.python.org/dev/peps/pep-0397

From marc.tompkins at gmail.com  Thu Apr 25 10:06:01 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 25 Apr 2013 01:06:01 -0700
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <CACL+1as3X=pGPeppGc71nD1aa7wigZvF_5e44EQhHrdkxDTikA@mail.gmail.com>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
	<CACL+1auCfym7f7Bf=FOxNYK6xDXswad3sRFF2iGxXHOr2MATpA@mail.gmail.com>
	<CAKK8jXZOzXMZTpS-wkN8-jGZM+5MLK=2XYTSgL1RbDeaT_gnNA@mail.gmail.com>
	<CACL+1as3X=pGPeppGc71nD1aa7wigZvF_5e44EQhHrdkxDTikA@mail.gmail.com>
Message-ID: <CAKK8jXbaVBufkc3kFUgrEeJRMFHUQAkj7H0r4_8NeSyEJ3yqcQ@mail.gmail.com>

On Thu, Apr 25, 2013 at 12:51 AM, eryksun <eryksun at gmail.com> wrote:

> On Thu, Apr 25, 2013 at 3:41 AM, Marc Tompkins <marc.tompkins at gmail.com>
> wrote:
> > On Wed, Apr 24, 2013 at 9:36 PM, eryksun <eryksun at gmail.com> wrote:
> >>
> >> .py files need to be associated with %windir%\py.exe.
> >
> >
> > NO!
> >
> > %windir% means "the directory where Windows is installed", usually (but
> not
> > always) C:\Windows.  You're saying that there needs to be a py.exe in the
> > Windows directory - this is absolutely not true.  You might have it set
> up
> > that way on your machine, but it's not standard and absolutely not
> > recommended.
> >
> > To the original poster: please disregard.
>
> boB has 3.3.1 installed. The official Windows installer for 3.3
> installs the new pylauncher to %windir%. It doesn't give you an option
> to do otherwise. Have you read PEP 397? Have you installed 3.3 on
> Windows?
>
> http://www.python.org/dev/peps/pep-0397
>

Only as a non-administrative user...

> The launcher is installed into the Windows directory (see discussion below) if installed by a privileged user. The stand-alone installer asks for an alternative location of the installer, and adds that location to the user's PATH.
>
> I had not read the PEP, and I apologize for my previous outburst.  Now
that I _have_ read it, I gotta say: this is stupid.  Third-party software
should NOT be installing stuff in the Windows folder - including Python, no
matter how much I love it.  How on earth did the discussion on this go, I
wonder?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130425/a376b7c2/attachment.html>

From robertvstepp at gmail.com  Thu Apr 25 14:29:04 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 25 Apr 2013 07:29:04 -0500
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <CAGZAPF4MMX95BVtN+eybKmAsg_RnTbPvZmi7fJ6ew3ASUasveg@mail.gmail.com>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
	<CAGZAPF4MMX95BVtN+eybKmAsg_RnTbPvZmi7fJ6ew3ASUasveg@mail.gmail.com>
Message-ID: <CANDiX9Lnc4Km4=174paBFJ+1_oDs9CdiKGSjS4vtVYXeCQKfQA@mail.gmail.com>

Hi Danny,

>
> [The following note is Python 2.0 specific.  In Python 3, input() is
> semantically different, and safe.]
>
> If you are using Python 2.0, don't use the input() function here to
> read strings.  It is not safe: backing it is an implicit eval(), and
> eval() is dangerous, especially for beginners who won't have the
> background to understand the security implications.
>
> Example: if you enter in the following strange-looking input:
>
>     (lambda x: x(x))(lambda x:x(x))
>
> then this will crash your program due to a stack overflow.  And this
> is relatively safe compared to the other craziness you can enter into
> input().  This is exactly why tutorials (and most Python programs in
> general) should _not_ use input(): it's dangerous in the wrong hands.
>
> Rather, use raw_input() instead.
>
My intent is to use Python 3.3. I was aware that if I were using 2.x,
that I should be using raw_input(); however, I was not aware of any
security implications. Thank you for that info!

boB

From robertvstepp at gmail.com  Thu Apr 25 14:40:21 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 25 Apr 2013 07:40:21 -0500
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <5178B08C.3040007@pearwood.info>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
	<5178B08C.3040007@pearwood.info>
Message-ID: <CANDiX9LHQhg_-PTi7XbS_2fUDoHeMqT6i7VRYEaPKcVLqM8wXg@mail.gmail.com>

Hi Steve,

>
>> E:\Programs\Python\IYOCGwPy\Ch4>guess.py
>
> Here you are telling Windows to look up the file association for .py files.
> It locates some program, and runs it with guess.py as the argument. Looking
> at the result:
>
>> Hello! What is your name?
>> boB
>> Traceback (most recent call last):
>>    File "E:\Programs\Python\IYOCGwPy\Ch4\guess.py", line 13, in <module>
>>      playerName = input()
>>    File "<string>", line 1, in <module>
>> NameError: name 'boB' is not defined
>
> this is obviously Python 2.x rather than 3.3.1. You can check that by
> putting these two lines at the very beginning of the program:

One thing that no one has addressed so far is why when I put quotes
around my input, as in 'boB', the program does run in the command
prompt.

>
> import sys
> print(sys.version)
>
>
> My bet is that if you run it like this:
>
>
> python guess.py
>
>
> it will print "3.3.1" and the program will work, but when you run it like
> this:
>
>
> guess.py
>
>
> it will print 2.something and then fail.

I am at work now and cannot do these checks. I suspect you are correct
in every particular!

>> E:\Programs\Python\IYOCGwPy\Ch4>
>>
>> This has me totally puzzled. I thought it might have something to do
>> with the fact that I also have Python 2.7 installed, so I removed it
>> from the path variable and also did the check for version that you see
>> above.
>
>
> There's your bunny. Just because you remove it from the search path doesn't
> mean that Windows won't use it.
>
> You might like to remove Python 2.7 altogether, or at least unassociate it
> from the .py file extension.
>
I am beginning to see that instead of "winging it" with installing
BOTH Python 2.7 and Python 3.3, that I should have done some research
first on how to have both Pythons coexist amicably, leaving Python 3.3
as my default for .py files. The reason that I want 2.7 is that at
work after our recent upgrades we have Python 2.4.6 installed on some
machines and 2.4.4 on others. My intention was to try out some Python
2.x stuff at home prior to start using it at work as a replacement for
the scripting I have been to date doing in Perl.

Thanks, Steve (and everyone else!)!
boB

From marc.tompkins at gmail.com  Thu Apr 25 15:45:09 2013
From: marc.tompkins at gmail.com (Marc Tompkins)
Date: Thu, 25 Apr 2013 06:45:09 -0700
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <CANDiX9LHQhg_-PTi7XbS_2fUDoHeMqT6i7VRYEaPKcVLqM8wXg@mail.gmail.com>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
	<5178B08C.3040007@pearwood.info>
	<CANDiX9LHQhg_-PTi7XbS_2fUDoHeMqT6i7VRYEaPKcVLqM8wXg@mail.gmail.com>
Message-ID: <CAKK8jXbEQp4PoUhvCPrpVpifNJKZ5PM80f=KUqMFd5e98iK7DA@mail.gmail.com>

On Thu, Apr 25, 2013 at 5:40 AM, boB Stepp <robertvstepp at gmail.com> wrote:

> One thing that no one has addressed so far is why when I put quotes
> around my input, as in 'boB', the program does run in the command
> prompt.
>

Remember that input(), in Python 2, executes what's passed to it.  If your
input is boB, then Python tries to execute the statement boB - and unless
you've previously defined boB, Python doesn't know what to do with it.

If you put quotes around your input, Python recognizes it as a string
literal.  Python "executes" string literals by simply printing them to
standard output - try it at a Python prompt sometime - which is probably
not the behavior you were expecting, but doesn't throw an error either.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130425/aee3701a/attachment.html>

From robertvstepp at gmail.com  Thu Apr 25 16:07:12 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Thu, 25 Apr 2013 09:07:12 -0500
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <CAKK8jXbEQp4PoUhvCPrpVpifNJKZ5PM80f=KUqMFd5e98iK7DA@mail.gmail.com>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
	<5178B08C.3040007@pearwood.info>
	<CANDiX9LHQhg_-PTi7XbS_2fUDoHeMqT6i7VRYEaPKcVLqM8wXg@mail.gmail.com>
	<CAKK8jXbEQp4PoUhvCPrpVpifNJKZ5PM80f=KUqMFd5e98iK7DA@mail.gmail.com>
Message-ID: <CANDiX9+tTUCnmrXnYbEEGjQTOQ2UUTNXRjcT43Bpbpcadczfjg@mail.gmail.com>

On Thu, Apr 25, 2013 at 8:45 AM, Marc Tompkins <marc.tompkins at gmail.com> wrote:
> On Thu, Apr 25, 2013 at 5:40 AM, boB Stepp <robertvstepp at gmail.com> wrote:

> Remember that input(), in Python 2, executes what's passed to it.  If your
> input is boB, then Python tries to execute the statement boB - and unless
> you've previously defined boB, Python doesn't know what to do with it.
>
Thanks, Marc. What little studying I have done to date has been
strictly Python 3.x based. I try to pay attention to what is discussed
in this forum and had absorbed that in 2.x I should use raw_input()
for what I am doing in my program. I did not recall absorbing any
discussion of how input() works in 2.x. Of course, I was only
beginning to suspect that the command prompt was running my .py files
in 2.7 when I sent my post late yesterday evening. What you say
combined with one of the earlier answers makes it much clearer to me
why using input() in 2.x can allow a user to do things that I would
not want him/her to do!

boB

From eryksun at gmail.com  Thu Apr 25 22:12:56 2013
From: eryksun at gmail.com (eryksun)
Date: Thu, 25 Apr 2013 16:12:56 -0400
Subject: [Tutor] Runs in IDLE with F5, but not in Windows Command Prompt
In-Reply-To: <CAKK8jXbEQp4PoUhvCPrpVpifNJKZ5PM80f=KUqMFd5e98iK7DA@mail.gmail.com>
References: <CANDiX9KGxty8wtG4hg26aP4=sNKN_AWOQ4Hnp=d1NrSMfET8wA@mail.gmail.com>
	<5178B08C.3040007@pearwood.info>
	<CANDiX9LHQhg_-PTi7XbS_2fUDoHeMqT6i7VRYEaPKcVLqM8wXg@mail.gmail.com>
	<CAKK8jXbEQp4PoUhvCPrpVpifNJKZ5PM80f=KUqMFd5e98iK7DA@mail.gmail.com>
Message-ID: <CACL+1aupMCTWp5DKfASsK9pFOrmwUpuagLZELX5KeR5-OQEW9g@mail.gmail.com>

On Thu, Apr 25, 2013 at 9:45 AM, Marc Tompkins <marc.tompkins at gmail.com> wrote:
>
> If you put quotes around your input, Python recognizes it as a string
> literal.  Python "executes" string literals by simply printing them to
> standard output - try it at a Python prompt sometime - which is probably not
> the behavior you were expecting, but doesn't throw an error either.

It's only printed in Python's interactive REPL (read-eval-print loop).

http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop

String literals, like all literals, are handled by the compiler.  The
instantiated string gets stored somewhere such as a __doc__ attribute,
a code object's constants, a function's defaults, etc.

In 2.x, built-in input() compiles and evaluates a temporary code
object (in CPython it uses PyRun_StringFlags) in the current globals
and locals. If the source string is just the literal, the compiled
bytecode is a LOAD followed by a RETURN:

    >>> code = compile('"boB"', '', 'eval')
    >>> dis.dis(code)
      1           0 LOAD_CONST               0 ('boB')
                   3 RETURN_VALUE

From wangyonguci2012 at gmail.com  Fri Apr 26 07:45:55 2013
From: wangyonguci2012 at gmail.com (wang yong)
Date: Thu, 25 Apr 2013 22:45:55 -0700
Subject: [Tutor] what is the meaning of variable e
Message-ID: <CAFe=K7_Hs7=fEmYHOM19yrmj87QEL-T=io8ZnkTtJP1wpmvAMw@mail.gmail.com>

Hi tutors,

I am a newb. Please bear with my simple question. Please refer to the code
as following. The question is: what is the special meaning of 'e' variable
in the class of 'Button'. The second one is how function 'dragEnterEvent'
and 'dropEvent' got executed with calling from class 'example'. Thanks a
lot for the help.

Best,

Yong

The code is here:
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PyQt4 tutorial

This is a simple drag and
drop example.

author: Jan Bodnar
website: zetcode.com
last edited: December 2010
"""

import sys
from PyQt4 import QtGui

class Button(QtGui.QPushButton):

    def __init__(self, title, parent):
        super(Button, self).__init__(title, parent)

        self.setAcceptDrops(True)

    def dragEnterEvent(self, e):

        if e.mimeData().hasFormat('text/plain'):
            e.accept()
        else:
            e.ignore()

    def dropEvent(self, e):
        self.setText(e.mimeData().text())


class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        edit = QtGui.QLineEdit('', self)
        edit.setDragEnabled(True)
        edit.move(30, 65)

        button = Button("Button", self)
        button.move(190, 65)

        self.setWindowTitle('Simple Drag & Drop')
        self.setGeometry(300, 300, 300, 150)


def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    app.exec_()


if __name__ == '__main__':
    main()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130425/92a2e57b/attachment-0001.html>

From steve at pearwood.info  Fri Apr 26 08:05:20 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Fri, 26 Apr 2013 16:05:20 +1000
Subject: [Tutor] what is the meaning of variable e
In-Reply-To: <CAFe=K7_Hs7=fEmYHOM19yrmj87QEL-T=io8ZnkTtJP1wpmvAMw@mail.gmail.com>
References: <CAFe=K7_Hs7=fEmYHOM19yrmj87QEL-T=io8ZnkTtJP1wpmvAMw@mail.gmail.com>
Message-ID: <517A1920.2020007@pearwood.info>

On 26/04/13 15:45, wang yong wrote:
> Hi tutors,
>
> I am a newb. Please bear with my simple question. Please refer to the code
> as following. The question is: what is the special meaning of 'e' variable
> in the class of 'Button'.


'e' is the argument to the dragEnterEvent and dropEvent methods. You will
need to read the PyQt4 documentation to find out what sort of argument
those two methods receive, but my guess is that they are GUI events.


> The second one is how function 'dragEnterEvent'
> and 'dropEvent' got executed with calling from class 'example'.

The PyQt4 library automatically calls them when the user drags something
onto the button with the mouse.




-- 
Steven

From davea at davea.name  Fri Apr 26 08:17:04 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 26 Apr 2013 02:17:04 -0400
Subject: [Tutor] what is the meaning of variable e
In-Reply-To: <CAFe=K7_Hs7=fEmYHOM19yrmj87QEL-T=io8ZnkTtJP1wpmvAMw@mail.gmail.com>
References: <CAFe=K7_Hs7=fEmYHOM19yrmj87QEL-T=io8ZnkTtJP1wpmvAMw@mail.gmail.com>
Message-ID: <517A1BE0.40109@davea.name>

On 04/26/2013 01:45 AM, wang yong wrote:
> Hi tutors,
>
> I am a newb. Please bear with my simple question.

If you're new to Python, then any GUI question isn't "simple."  But 
perhaps you're not new to Python, but only to PyQT.  I'll qualify my 
remarks with the statement that I'm not familiar with PyQt, but I am 
with GUI's in general.  So I hope I can help.

  Please refer to the code
> as following. The question is: what is the special meaning of 'e' variable
> in the class of 'Button'.

'e' is not special to the class at all.  It's just a parameter specified 
in two of the class methods.  So somebody makes a call something like:
     context =    --instance of some class that has a mimeData method--
     mybutton.dragEnterEvent(context)


The second one is how function 'dragEnterEvent'
> and 'dropEvent' got executed with calling from class 'example'. Thanks a
> lot for the help.

By making your Button class a child of  QtGui.QPushButton, you inherit a 
lot of behavior.  Apparently two pieces of that is the binding of these 
two methods to the button.  Whenever somebody calls a method on 
QtGui.QPushButton that you have also defined, they end up calling your 
version instead of the default one in the base class.

Apparently, when a user does a drag-drop targeting a QPushButton, it 
fires one or both of those events.

For more details, you need to ask someone who knows PyQt.  I don't see 
it discussed here very much, so you'd probably be better off with the 
docs, or on a PyQt forum.



-- 
DaveA

From arijit.ukil at tcs.com  Fri Apr 26 11:08:53 2013
From: arijit.ukil at tcs.com (Arijit Ukil)
Date: Fri, 26 Apr 2013 14:38:53 +0530
Subject: [Tutor] sha-256 without using hashlib
Message-ID: <OF85F06EF7.577D059C-ON65257B59.0031FA73-65257B59.003240CA@tcs.com>

I like to implement sha-256 without using implement. It is easy using 
hashlib as:

import hashlib
m = hashlib.sha256()
m.update("hi")
print m.hexdigest()

If anybody has pointer on sha-256 implemented without using hashlib 
library, please share.

Regards,
Arijit Ukil
Tata Consultancy Services
Mailto: arijit.ukil at tcs.com
Website: http://www.tcs.com
____________________________________________
Experience certainty.   IT Services
                        Business Solutions
                        Outsourcing
____________________________________________
=====-----=====-----=====
Notice: The information contained in this e-mail
message and/or attachments to it may contain 
confidential or privileged information. If you are 
not the intended recipient, any dissemination, use, 
review, distribution, printing or copying of the 
information contained in this e-mail message 
and/or attachments to it are strictly prohibited. If 
you have received this communication in error, 
please notify us by reply e-mail or telephone and 
immediately and permanently delete the message 
and any attachments. Thank you


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130426/cab84c66/attachment.html>

From davea at davea.name  Fri Apr 26 11:56:44 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 26 Apr 2013 05:56:44 -0400
Subject: [Tutor] sha-256 without using hashlib
In-Reply-To: <OF85F06EF7.577D059C-ON65257B59.0031FA73-65257B59.003240CA@tcs.com>
References: <OF85F06EF7.577D059C-ON65257B59.0031FA73-65257B59.003240CA@tcs.com>
Message-ID: <517A4F5C.6050204@davea.name>

On 04/26/2013 05:08 AM, Arijit Ukil wrote:
> I like to implement sha-256 without using implement. It is easy using
> hashlib as:
>
> import hashlib
> m = hashlib.sha256()
> m.update("hi")
> print m.hexdigest()
>
> If anybody has pointer on sha-256 implemented without using hashlib
> library, please share.
>

If you'd tell us WHY you don't want to use a stdlib, we might be able to 
help.

For example, perhaps you're supposed to code it for an assignment, and 
show that you understand the algorithms.  In that case, look up the 
algorithm on the net, and start from there.

    http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf

Or you could be assuming that you can do a better, faster or whatever 
job than the library.  In that case, consider using numpy, or Cython, or 
a C compiler.

Or perhaps you didn't realize you could get the sources to hashlib 
online.  I believe some are in Python, and some in C, so that might not 
help you if your goal is one of the previous ones.


-- 
DaveA

From mike at froward.org  Fri Apr 26 14:10:03 2013
From: mike at froward.org (mike)
Date: Fri, 26 Apr 2013 07:10:03 -0500
Subject: [Tutor] symlinking dirs with spaces
Message-ID: <517A6E9B.30601@froward.org>

Hi all,

I wrote a cli script for syncing my music to a USB mass storage device 
like a phone etc. all it does is it creates a symlink in a dir to 
whatever folder i pass as an argument via ./addsync DIR . My problem is 
i'm having trouble dealing with directories with spaces. when using 
os.symlink I get the error below and when using subprocess it creates 
individual directories for the words separated by white space. any help 
would be appreciated on how to approach this.thanks!

This is the script:

#!/usr/bin/env python
import os
from sys import argv
import subprocess
script, media = argv

# This is the directory you will sync the symbolic links from, to the 
device.
loadDir = "/opt/data/music/load/"

# This is the destination folder, whatever folder the device is mounted to.
destDir = "/media/MOT_"

# Get the current working directory
origDir = os.getcwd()

# Glob the current working directory and the "media" argument together
# to form a full file path
origFul = os.path.join('%s' % origDir, '%s' % media)

linkDir = "ln -s %s %s" % (origFul, loadDir)

# Command to sync if media == "push"
syncCom = "rsync -avzL %s %s" % (loadDir, destDir)

def link():
     print "Adding %s to %s..." % (origFul, loadDir)
     os.symlink('origFul', 'media')
#    subprocess.call(linkDir, shell=True)

def sync():
     print "Syncing the contents of %s to %s" % (loadDir, destDir)
     subprocess.call(syncCom, shell=True)

if media == "push":
     sync()
else:
     link()



rev at sheridan:~/code$ ./addsync SPACES\ TEST/
Adding /home/rev/code/SPACES TEST/ to /opt/data/music/load/...
Traceback (most recent call last):
   File "./addsync", line 37, in <module>
     link()
   File "./addsync", line 27, in link
     os.symlink('origFul', 'media')
OSError: [Errno 17] File exists
rev at sheridan:~/code$ ls -lh /opt/data/music/load/
total 4.0K
-rwxrwxr-x 1 rev rev 225 Apr 11 09:26 addsync
lrwxrwxrwx 1 rev rev  34 Oct 29 20:30 CCR - Best of CCR -> 
../classic_rock/CCR - Best of CCR/
rev at sheridan:~/code$


From losermeloser at yahoo.com  Fri Apr 26 14:45:24 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Fri, 26 Apr 2013 05:45:24 -0700 (PDT)
Subject: [Tutor] cant autoincrement
Message-ID: <1366980324.24663.YahooMailNeo@web121101.mail.ne1.yahoo.com>

I'm doing a test database with sqlite and have run into some problems. in my 1st table i have an id field:?
?
id INTERGER Primary Key
?
the database has a few more fields, but when i insert into it, i leave the id field empty as it should be done automatically, but sql complains with an error that i have left the field blank. If i manually put the ids in, everything works, but from my understanding this should be done automatically, aswell as it auto incrementing??
?
i have two tables 
table1 (id, field 2, field 3, field 4)
table2 (id, field 2, field 3, FOREIGN KEY (field 3) REFERENCES table1(id))
?
i initially had a problem as foreign keys is not enabled by default but as my auto increment isnt working, can i just ask what does sql insert into field 3 of table2 as its a foreign key. Does it automatically insert the correspond id of table1, or is it up to me to manually insert the correct data into table2 that match with the keys on table1? I ask only because i havent had a chance to try it myself as i still have a problem with the keys, and strangely enough if i put random text into the foreign key of table 2 that didnt reference any ids on table1, sqlite still inserts them with no errors when they clearly ignore the instructions given.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130426/f5d5a549/attachment.html>

From davea at davea.name  Fri Apr 26 15:06:35 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 26 Apr 2013 09:06:35 -0400
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517A6E9B.30601@froward.org>
References: <517A6E9B.30601@froward.org>
Message-ID: <517A7BDB.7050507@davea.name>

On 04/26/2013 08:10 AM, mike wrote:
> Hi all,
>
> I wrote a cli script for syncing my music to a USB mass storage device
> like a phone etc. all it does is it creates a symlink in a dir to
> whatever folder i pass as an argument via ./addsync DIR . My problem is
> i'm having trouble dealing with directories with spaces. when using
> os.symlink I get the error below and when using subprocess it creates
> individual directories for the words separated by white space. any help
> would be appreciated on how to approach this.thanks!
>
> This is the script:
>
> #!/usr/bin/env python
> import os
> from sys import argv
> import subprocess
> script, media = argv
>
> # This is the directory you will sync the symbolic links from, to the
> device.
> loadDir = "/opt/data/music/load/"
>
> # This is the destination folder, whatever folder the device is mounted to.
> destDir = "/media/MOT_"
>
> # Get the current working directory
> origDir = os.getcwd()
>
> # Glob the current working directory and the "media" argument together
> # to form a full file path
> origFul = os.path.join('%s' % origDir, '%s' % media)
>
> linkDir = "ln -s %s %s" % (origFul, loadDir)
>
> # Command to sync if media == "push"
> syncCom = "rsync -avzL %s %s" % (loadDir, destDir)
>
> def link():
>      print "Adding %s to %s..." % (origFul, loadDir)
>      os.symlink('origFul', 'media')
> #    subprocess.call(linkDir, shell=True)

By using shell=True, you're forcing your OS's shell to interpret the 
line.  If you insist on that approach, you'll need to escape any 
embedded spaces, same as you would in the terminal.

Easier and safer would be to pass the list of argument to 
subprocess.call, the way these docs show:

    http://docs.python.org/2/library/subprocess.html#subprocess.call

So instead of linkDir looking like "ln -s file 1 file2"  it should look 
like:
     ["ln", "-s", "file 1", "file2"]
and you'd use it like:
     subprocess.call(linkDir)

Avoiding the shell=True is faster, safer, and usually much easier.



-- 
DaveA

From fahraynk at gmail.com  Fri Apr 26 17:28:06 2013
From: fahraynk at gmail.com (Frank Schiro)
Date: Fri, 26 Apr 2013 11:28:06 -0400
Subject: [Tutor] does anyone know a good module for automation
In-Reply-To: <kkvbs4$ibo$1@ger.gmane.org>
References: <CA+QG++FWWArsjCFfcSr87RtAJbLgE9dgN5WR8pPXvev7YErAkg@mail.gmail.com>
	<kkvbs4$ibo$1@ger.gmane.org>
Message-ID: <CA+QG++FbKt0zZS0xQ25B8R3H2tGSuo5aYLeGOrgduD5MjQHmqA@mail.gmail.com>

Pywinauto is not working with this application that opens from the internet
via javascript. Its not in a browser, its a complete application thats not
installed on the computer just installed on the internet.

Pywinauto sees the window...but cant find any controls and does not
recognize menu items, neither does its helper program swapy. Does anyone
know how I could automate a program like this ? I guess something about it
is not the same as normal installed on your own computer programs... Also I
dont like sikuli, because I hate its interpreter.

On Sat, Apr 20, 2013 at 8:28 PM, Alan Gauld <alan.gauld at btinternet.com>wrote:

> On 20/04/13 23:07, Frank Schiro wrote:
>
>>
>> Unless you think pywinauto would work in a game envoirnment ? I think it
>> might but have not tried it because no games on my pc... I just know it
>> didnt work for internet explorer.
>>
>
> I don't know pywinauto but the lowest common denominator on Windows is the
> Win32 API and the Windows messages. You can use either ctypes or pythonwin
> to access those and/or create your own to simulate button presses and mouse
> clicks etc. Doing that you can automate anything in windows, but its a non
> trivial, error prone and frustrating exercise so its better to get a higher
> level library if you can.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
>
> ______________________________**_________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130426/c5fe50ab/attachment.html>

From alan.gauld at btinternet.com  Fri Apr 26 19:26:56 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 26 Apr 2013 18:26:56 +0100
Subject: [Tutor] does anyone know a good module for automation
In-Reply-To: <CA+QG++FbKt0zZS0xQ25B8R3H2tGSuo5aYLeGOrgduD5MjQHmqA@mail.gmail.com>
References: <CA+QG++FWWArsjCFfcSr87RtAJbLgE9dgN5WR8pPXvev7YErAkg@mail.gmail.com>
	<kkvbs4$ibo$1@ger.gmane.org>
	<CA+QG++FbKt0zZS0xQ25B8R3H2tGSuo5aYLeGOrgduD5MjQHmqA@mail.gmail.com>
Message-ID: <kledcs$dq7$1@ger.gmane.org>

On 26/04/13 16:28, Frank Schiro wrote:
> Pywinauto is not working with this application that opens from the
> internet via javascript. Its not in a browser, its a complete
> application thats not installed on the computer just installed on the
> internet.

That sounds very dodgy, it would be a huge gaping security
issue.

Are you sure its not running in a separate browser
window - possibly as a Java applet?

How does it appear in the Windows Task Manager? Is it a separate 
process? If so what is it called?

> Pywinauto sees the window...but cant find any controls and does not
> recognize menu items, neither does its helper program swapy. Does anyone
> know how I could automate a program like this ?

Not without a lot more detail about the runtime environment.

> Also I dont like sikuli, because I hate its interpreter.

Errr, where does sikuli fit in? I've never heard of it.

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


From bgailer at gmail.com  Fri Apr 26 19:10:34 2013
From: bgailer at gmail.com (bob gailer)
Date: Fri, 26 Apr 2013 13:10:34 -0400
Subject: [Tutor] cant autoincrement
In-Reply-To: <1366980324.24663.YahooMailNeo@web121101.mail.ne1.yahoo.com>
References: <1366980324.24663.YahooMailNeo@web121101.mail.ne1.yahoo.com>
Message-ID: <517AB50A.8070504@gmail.com>

On 4/26/2013 8:45 AM, Lolo Lolo wrote:
> I'm doing a test database with sqlite and have run into some problems. 
> in my 1st table i have an id field:
> id INTERGER Primary Key
> ... when i insert into it, i leave the id field empty
what does your insert statement look like? According to the 
documentation (http://www.sqlite.org/faq.html#q1):

  "whenever you insert a NULL into that column of the table, the NULL is 
automatically converted into (1 + the highest value)."

The insert statement should look like:

"INSERT INTO t1 VALUES(NULL,123);

I suggest you join 
http://sqlite.org:8080/cgi-bin/mailman/listinfo/sqlite-users - as this 
is the preferred place to ask sqlite questions.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130426/1eef21ea/attachment.html>

From losermeloser at yahoo.com  Fri Apr 26 21:28:46 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Fri, 26 Apr 2013 12:28:46 -0700 (PDT)
Subject: [Tutor] cant autoincrement
In-Reply-To: <517AB50A.8070504@gmail.com>
References: <1366980324.24663.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<517AB50A.8070504@gmail.com>
Message-ID: <1367004526.29070.YahooMailNeo@web121102.mail.ne1.yahoo.com>

what does your insert statement look like? According to the documentation (http://www.sqlite.org/faq.html#q1):

?"whenever you insert a NULL into that column of the table, the NULL
    is automatically converted into (1 + the highest value)." 

The insert statement should look like:
?
"INSERT INTO t1 VALUES(NULL,123);

?i included the null, my results are: 
??? 
cursor.execute("INSERT into person VALUES(NULL, arg1, arg2)")
?
my result is:
?
(None, value1, value2) #the key?being None?:(
?
also thanks for the link
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130426/f5d99075/attachment.html>

From eryksun at gmail.com  Fri Apr 26 22:52:34 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 26 Apr 2013 16:52:34 -0400
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517A6E9B.30601@froward.org>
References: <517A6E9B.30601@froward.org>
Message-ID: <CACL+1avga+14ZYy3MetK30kExJGO0USBu_jAwLH7TiY60n=8ig@mail.gmail.com>

On Fri, Apr 26, 2013 at 8:10 AM, mike <mike at froward.org> wrote:
>
> def link():
>     print "Adding %s to %s..." % (origFul, loadDir)
>     os.symlink('origFul', 'media')

Your arguments for symlink() are string literals. How about this?

    LOAD_DIR = "/opt/data/music/load"

    def link(media):
        src = os.path.abspath(media)
        dst = os.path.join(LOAD_DIR, os.path.basename(media))
        print "Adding %s to %s..." % (src, LOAD_DIR)
        os.symlink(src, dst)

From zac_vanessa1fan at yahoo.ca  Fri Apr 26 23:02:49 2013
From: zac_vanessa1fan at yahoo.ca (Mariel Jane Sanchez)
Date: Fri, 26 Apr 2013 14:02:49 -0700 (PDT)
Subject: [Tutor] Chapter 4 Help
Message-ID: <1367010169.74578.YahooMailNeo@web141006.mail.bf1.yahoo.com>

I was in Seattle for 4 days for our band trip so i miss some classes.
Chapter 4
Project 1
"Write a program that asks for a phrase, and then calculates and displays the number of vowels in the phrase, twice. The first time, your program should calculate the number of vowels in the phrase using a for loop. The second time, your program should use a while loop."
My code:?
phrase = raw_input("Please enter a phrase: ")
VOWELS = "aeiou"
new = ""
for letter in phrase:
? ? if VOWELS in phrase :
? ? ? ? print newv?
It keeps printing the phrase not the new string. How would you do this? And what am i doing wrong?
2. "Write a program that gets a message from the user and prints the message out backwards."
For this one, i honestly don't have any idea how to make a word print backwards, I only do it with numbers. Here's my attempt code:"
import random
message = raw_input("Please enter you message:")
raw_input("Please press the enter key to our message.")
high = (message(len(100)))
low = (message(len(0)))
new = random.randrange (high, low)
print new
So how do you put the words backwards?
3."Write a program that prints out a string representation of a random card from a deck of playing cards. The program should use either "A", "2","3","4","5","6","7","8","9","10","J","Q" or "K" for the value of the card and either "c","h","s" or "d" for the suit. So, if the program randomly selects the jack of clubs, it should display 'Jc.' Use one tuple to represent all of the possible card values and another tuple for the possible suits."

In the simplest way, how do you do this?
Thanks in advance
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130426/b0c92b61/attachment.html>

From alan.gauld at btinternet.com  Fri Apr 26 23:08:27 2013
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Fri, 26 Apr 2013 22:08:27 +0100 (BST)
Subject: [Tutor] Fw:  does anyone know a good module for automation
In-Reply-To: <CA+QG++HbC0NqV6uidM2B6NneB3wgdf0iqpyWwRNiPn8ikBzfrw@mail.gmail.com>
References: <CA+QG++FWWArsjCFfcSr87RtAJbLgE9dgN5WR8pPXvev7YErAkg@mail.gmail.com>
	<kkvbs4$ibo$1@ger.gmane.org>
	<CA+QG++FbKt0zZS0xQ25B8R3H2tGSuo5aYLeGOrgduD5MjQHmqA@mail.gmail.com>
	<kledcs$dq7$1@ger.gmane.org>
	<CA+QG++HbC0NqV6uidM2B6NneB3wgdf0iqpyWwRNiPn8ikBzfrw@mail.gmail.com>
Message-ID: <1367010507.18046.YahooMailNeo@web186004.mail.ir2.yahoo.com>

Forwarding to group for info, please use replyAll on replies.
?
Alan Gauld
Author of the Learn To Program website
http://www.alan-g.me.uk/


----- Forwarded Message -----
>From: Frank Schiro <fahraynk at gmail.com>
>To: Alan Gauld <alan.gauld at btinternet.com> 
>Sent: Friday, 26 April 2013, 19:17
>Subject: Re: [Tutor] does anyone know a good module for automation
> 
>
>
>
>
>
>On Fri, Apr 26, 2013 at 1:26 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
>On 26/04/13 16:28, Frank Schiro wrote:
>>
>>Pywinauto is not working with this application that opens from the
>>>internet via javascript. Its not in a browser, its a complete
>>>application thats not installed on the computer just installed on the
>>>internet.
>>>
>>That sounds very dodgy, it would be a huge gaping security
>>issue.
>>
>>Are you sure its not running in a separate browser
>>window - possibly as a Java applet?
>>
>>How does it appear in the Windows Task Manager? Is it a separate process? If so what is it called? 
>>
>>
>>
>>Pywinauto sees the window...but cant find any controls and does not
>>>recognize menu items, neither does its helper program swapy. Does anyone
>>>know how I could automate a program like this ?
>>>
>>Not without a lot more detail about the runtime environment. 
>>
>>
>>
>>Also I dont like sikuli, because I hate its interpreter.
>>>
>>Errr, where does sikuli fit in? I've never heard of it. 
>>
>>
>>-- 
>>Alan G
>>Author of the Learn to Program web site
>>http://www.alan-g.me.uk/
>>
>>_______________________________________________
>>Tutor maillist ?- ?Tutor at python.org
>>To unsubscribe or change subscription options:
>>http://mail.python.org/mailman/listinfo/tutor
>>
>
>?
>?
>It might be a java applet ? I see 2 processes called "java.exe" in processes tab, but applications tab says the application name, ACSR....
>sikuli is an automation?open source thing that uses print screen.
>?
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130426/3a13b207/attachment-0001.html>

From eryksun at gmail.com  Sat Apr 27 00:18:13 2013
From: eryksun at gmail.com (eryksun)
Date: Fri, 26 Apr 2013 18:18:13 -0400
Subject: [Tutor] cant autoincrement
In-Reply-To: <1366980324.24663.YahooMailNeo@web121101.mail.ne1.yahoo.com>
References: <1366980324.24663.YahooMailNeo@web121101.mail.ne1.yahoo.com>
Message-ID: <CACL+1aty8-Rj8MpWXykK9X9v3R_Lxba4kgM6rj7S4C9-LyzFYQ@mail.gmail.com>

On Fri, Apr 26, 2013 at 8:45 AM, Lolo Lolo <losermeloser at yahoo.com> wrote:
>
> id INTERGER Primary Key
>
> the database has a few more fields, but when i insert into it, i leave the
> id field empty as it should be done automatically, but sql complains with an
> error that i have left the field blank. If i manually put the ids in,
> everything works, but from my understanding this should be done
> automatically, aswell as it auto incrementing?

The id should be NULL.  For parameter substitution use None.

> i have two tables
> table1 (id, field 2, field 3, field 4)
> table2 (id, field 2, field 3, FOREIGN KEY (field 3) REFERENCES table1(id))

> keys, and strangely enough if i put random text into the foreign key of
> table 2 that didnt reference any ids on table1, sqlite still inserts them
> with no errors when they clearly ignore the instructions given.

The foreign keys constrain is initially disabled. There's a pragma to
enable it. Here's an example:

    import sqlite3
    con = sqlite3.connect(':memory:')
    cur = con.cursor()

    # enable foreign keys constraint
    cur = cur.execute('pragma foreign_keys=on')

    cur.execute('''
    create table table1(
      id integer primary key, field2, field3, field4)''')

    cur.execute('''
    create table table2(
      id integer primary key, field2, field3,
      foreign key(field3) references table1(id))''')

    cur.execute('insert into table1 values(?,?,?,?)', (None, 1, 2, 3))
    cur.execute('insert into table2 values(?,?,?)', (None, 4, 1))

    # this should raise
    # sqlite3.IntegrityError: foreign key constraint failed
    cur.execute('insert into table2 values(?,?,?)', (None, 5, 2))

From paradox at pobox.com  Sat Apr 27 00:44:32 2013
From: paradox at pobox.com (Paradox)
Date: Sat, 27 Apr 2013 06:44:32 +0800
Subject: [Tutor] Chapter 4 Help :p:
In-Reply-To: <1367010169.74578.YahooMailNeo@web141006.mail.bf1.yahoo.com>
References: <1367010169.74578.YahooMailNeo@web141006.mail.bf1.yahoo.com>
Message-ID: <517B0350.3020705@pobox.com>


On 04/27/2013 05:02 AM, Mariel Jane Sanchez wrote:
> I was in Seattle for 4 days for our band trip so i miss some classes.
> Chapter 4
> Project 1
> "Write a program that asks for a phrase, and then calculates and 
> displays the number of vowels in the phrase, twice. The first time, 
> your program should calculate the number of vowels in the phrase using 
> a for loop. The second time, your program should use a while loop."
> My code:
> phrase = raw_input("Please enter a phrase: ")
> VOWELS = "aeiou"
> new = ""
> for letter in phrase:
>     if VOWELS in phrase :
>         print newv
> It keeps printing the phrase not the new string. How would you do 
> this? And what am i doing wrong?
I'll take a crack at your first problem ...

Not sure what newv is - it doesn't seem to be defined anywhere but is 
called in the print statement.

In pseudocode aren't you doing something like this?

Get a phrase from the user.
Loop over the phrase looking for letters that match the letters in 
VOWELS string.
Print any matches you find.

Looks like you are getting the phrase OK, setting your vowels string OK, 
looping over the phrase OK then looking to see if the VOWELS string is 
part of the phrase - is that what you mean to do?

Keep at it, you are getting there!

thomas

From swain_rajlaxmi at yahoo.com  Sat Apr 27 00:57:40 2013
From: swain_rajlaxmi at yahoo.com (Rajlaxmi Swain)
Date: Fri, 26 Apr 2013 15:57:40 -0700 (PDT)
Subject: [Tutor] getting TypeError: float() argument must be a string or a
	number
Message-ID: <1367017060.77044.YahooMailNeo@web125602.mail.ne1.yahoo.com>

How can I fix this.

Thanks,
test
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130426/75dcdcb6/attachment.html>

From davea at davea.name  Sat Apr 27 01:50:35 2013
From: davea at davea.name (Dave Angel)
Date: Fri, 26 Apr 2013 19:50:35 -0400
Subject: [Tutor] getting TypeError: float() argument must be a string or
 a number
In-Reply-To: <1367017060.77044.YahooMailNeo@web125602.mail.ne1.yahoo.com>
References: <1367017060.77044.YahooMailNeo@web125602.mail.ne1.yahoo.com>
Message-ID: <517B12CB.2000601@davea.name>

On 04/26/2013 06:57 PM, Rajlaxmi Swain wrote:
> How can I fix this.
>
>
>
>

I don't see any antecedents for the pronoun.

Show us some code, tell us the situation, and show us the full traceback.

Otherwise we'd just be paraphrasing the error message.  Make sure the 
argument is a string, or an int, or a float, or ...


-- 
DaveA

From losermeloser at yahoo.com  Sat Apr 27 02:35:38 2013
From: losermeloser at yahoo.com (Lolo Lolo)
Date: Fri, 26 Apr 2013 17:35:38 -0700 (PDT)
Subject: [Tutor] cant autoincrement
In-Reply-To: <CACL+1aty8-Rj8MpWXykK9X9v3R_Lxba4kgM6rj7S4C9-LyzFYQ@mail.gmail.com>
References: <1366980324.24663.YahooMailNeo@web121101.mail.ne1.yahoo.com>
	<CACL+1aty8-Rj8MpWXykK9X9v3R_Lxba4kgM6rj7S4C9-LyzFYQ@mail.gmail.com>
Message-ID: <1367022938.27955.YahooMailNeo@web121103.mail.ne1.yahoo.com>


thanks so much for the code sample eryksun. its working perfectly now:)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130426/320907ce/attachment.html>

From alan.gauld at btinternet.com  Sat Apr 27 02:47:55 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 27 Apr 2013 01:47:55 +0100
Subject: [Tutor] Chapter 4 Help
In-Reply-To: <1367010169.74578.YahooMailNeo@web141006.mail.bf1.yahoo.com>
References: <1367010169.74578.YahooMailNeo@web141006.mail.bf1.yahoo.com>
Message-ID: <klf77n$b5q$1@ger.gmane.org>

On 26/04/13 22:02, Mariel Jane Sanchez wrote:

> program should calculate the number of vowels in the phrase using a for
> loop. The second time, your program should use a while loop."
> My code:

> phrase = raw_input("Please enter a phrase: ")
> VOWELS = "aeiou"
> new = ""
> for letter in phrase:
>      if VOWELS in phrase :
>          print newv

Please send the actual code, don;t retype it. The newv should be 
throwing an error so presumably you don;t have that in your
real code.

The real problem is in your 'if' test. Think about the logic there.

> It keeps printing the phrase not the new string.

Not according to the code you posted, but in the real code it
may be different. Please post the real code.

> How would you do this?

You are almost there. But you should be calculating the number of vowels 
not printing them... And for that you could look at the count() method 
of strings...

And the while loop should just be a conversion of the for loop to a 
while - it hardly seems worth having as an exercise (and could even
be said to be teaching you bad habits!).

> 2. "Write a program that gets a message from the user and prints the
> message out backwards."
> For this one, i honestly don't have any idea how to make a word print
> backwards, I only do it with numbers. Here's my attempt code:"

If you use a while loop here you start at the highest index in the 
string and decrement the index each time.

Using a for loop you could investigate string slicing.
Or you could convert the string to a list, reverse the list and convert 
back again to a string.
Or you could use a for loop and the range function with range set to 
count backwards.

Lots of options.


> import random
> message = raw_input("Please enter you message:")
> raw_input("Please press the enter key to our message.")
> high = (message(len(100)))
> low = (message(len(0)))

No idea what you think those lines do but I'm pretty sure its
not what they really do!

> new = random.randrange (high, low)
> print new

And even less idea what you think this might be doing.

Can you write down in English how you would do this using
pen and paper? That might help you to craft a program.

> 3."Write a program that prints out a string representation of a random
> card from a deck of playing cards.

OK, this is a whole different can of worms, lets get the looping and 
string issues sorted out first!
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/


From alan.gauld at btinternet.com  Sat Apr 27 02:50:01 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 27 Apr 2013 01:50:01 +0100
Subject: [Tutor] getting TypeError: float() argument must be a string or
	a number
In-Reply-To: <1367017060.77044.YahooMailNeo@web125602.mail.ne1.yahoo.com>
References: <1367017060.77044.YahooMailNeo@web125602.mail.ne1.yahoo.com>
Message-ID: <klf7bk$b5q$2@ger.gmane.org>

On 26/04/13 23:57, Rajlaxmi Swain wrote:
> How can I fix this.

Fix what?

you've sent (part of) the error message but not what caused it nor the 
full error text.

Don't make us guess, help us to help you.


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


From steve at pearwood.info  Sat Apr 27 04:27:06 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 27 Apr 2013 12:27:06 +1000
Subject: [Tutor] getting TypeError: float() argument must be a string or
 a number
In-Reply-To: <1367017060.77044.YahooMailNeo@web125602.mail.ne1.yahoo.com>
References: <1367017060.77044.YahooMailNeo@web125602.mail.ne1.yahoo.com>
Message-ID: <517B377A.7050509@pearwood.info>

On 27/04/13 08:57, Rajlaxmi Swain wrote:
> How can I fix this.

Don't call float(foo) when foo is not a string or number.


To debug this, you need to follow these steps:

1) Look at the error message. It will tell you the line number that fails.

2) Look at that line of code. What are you calling float() on?

3) What type of object is it? If you don't know, put a line just before the call to float and print the object and its type. E.g.:

     print(type(foo), foo)
     result = float(foo)


4) Think hard about why you are calling float() on something that is not a string or a number. This is the bug, you now just have to understand it. Is it a typo? Are you using the wrong variable? Maybe you haven't initialised it to a good value? Or there is a path through your code where the wrong value is used?

5) Write code to fix the bug.



Notice writing code is the *least* important part of debugging. First you investigate what causes the bug; then you think about how it happens; then and only then do you write code.


Also notice that *we cannot do any of this for you*. You don't show us the full error, or the code, or give us any context. There is no magic wand we can wave and say "do this and the bug will go away".


-- 
Steven

From bgailer at gmail.com  Sat Apr 27 02:05:48 2013
From: bgailer at gmail.com (bob gailer)
Date: Fri, 26 Apr 2013 20:05:48 -0400
Subject: [Tutor] getting TypeError: float() argument must be a string or
 a number
In-Reply-To: <1367017060.77044.YahooMailNeo@web125602.mail.ne1.yahoo.com>
References: <1367017060.77044.YahooMailNeo@web125602.mail.ne1.yahoo.com>
Message-ID: <517B165C.4080203@gmail.com>

On 4/26/2013 6:57 PM, Rajlaxmi Swain wrote:

Welcome to the tutor list. You appear to be a first-time visitor.

To help us help you:

- Tell us:

  - Which version of Python you are using

   - How you are entering and executing your program,

- Provide some of your program (all of it if not too long) as part of 
the email body.

- Include the entire traceback.

Example:

Running Python 3.3.1
Typing in the PyScripter interactive interpreter.

 >>> x = [123]
 >>> print(float(x))
Traceback (most recent call last):
   File "<string>", line 301, in runcode
   File "<interactive input>", line 1, in <module>
TypeError: float() argument must be a string or a number

> How can I fix this.
Examine the argument to float. Ensure it is a string or a number.

-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130426/ceb78949/attachment.html>

From malaclypse2 at gmail.com  Sat Apr 27 06:17:23 2013
From: malaclypse2 at gmail.com (Jerry Hill)
Date: Sat, 27 Apr 2013 00:17:23 -0400
Subject: [Tutor] getting TypeError: float() argument must be a string or
	a number
In-Reply-To: <517B165C.4080203@gmail.com>
References: <1367017060.77044.YahooMailNeo@web125602.mail.ne1.yahoo.com>
	<517B165C.4080203@gmail.com>
Message-ID: <CADwdpyYEx1cZv-wcqN5D5kOJmDgx++_9nOVZsHBk6XzDiqRikg@mail.gmail.com>

On Fri, Apr 26, 2013 at 8:05 PM, bob gailer <bgailer at gmail.com> wrote:

>  - Provide some of your program (all of it if not too long) as part of
> the email body.
>

?And if your program is too long to comfortably post in the body of an
email?, there's some great advice about how to trim large amounts of code
down to a sample that demonstrates your problem here: http://sscce.org/

In fact, I've often found this technique useful for general debugging --
trimming a large piece of misbehaving code down to the essentials will
often lead you to seeing your error once some of the surrounding complexity
is removed.

-- 
Jerry
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130427/dd3b9d8d/attachment.html>

From cybervigilante at gmail.com  Sat Apr 27 11:49:52 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 27 Apr 2013 02:49:52 -0700
Subject: [Tutor] changing list element in loop
Message-ID: <CALRAYNU_XvAWaU1_BWYNG3664aeHVdV0qLA0HDYpRbG+Mp3hHA@mail.gmail.com>

Why isn't 'e' changing to 'pP here when the vowel list is mutable:

vowelList = list('aeiouy')

for x in vowelList:
    if x == 'e':
        x = 'P'

print(vowelList)

#result: ['a', 'e', 'i', 'o', 'u', 'y']

--
Jim Mooney

From amitsaha.in at gmail.com  Sat Apr 27 11:55:58 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Sat, 27 Apr 2013 19:55:58 +1000
Subject: [Tutor] changing list element in loop
In-Reply-To: <CALRAYNU_XvAWaU1_BWYNG3664aeHVdV0qLA0HDYpRbG+Mp3hHA@mail.gmail.com>
References: <CALRAYNU_XvAWaU1_BWYNG3664aeHVdV0qLA0HDYpRbG+Mp3hHA@mail.gmail.com>
Message-ID: <CANODV3nLqNZS48e8McU9VRQ9_oXV2dfr9g8DWb4Z8PyfdTzPZQ@mail.gmail.com>

On Sat, Apr 27, 2013 at 7:49 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> Why isn't 'e' changing to 'pP here when the vowel list is mutable:
>
> vowelList = list('aeiouy')
>
> for x in vowelList:
>     if x == 'e':
>         x = 'P'

This is because x is really a label for the item in your list. It does
not represent a reference to the position of element as it occurs in
the list. For example:

>>> a= ['a','e','i']

In the above list, a[0] is 'a', a[1] is 'e' and so on. So, if you want
to change the character 'e' above to 'o', you will have to do:

>> a[1] = 'o'

>>> a
['a','o','i']

Hope that helps. You may find the enumerate() function useful in this
case: http://docs.python.org/2/library/functions.html#enumerate

Best,
Amit.






>
> print(vowelList)
>
> #result: ['a', 'e', 'i', 'o', 'u', 'y']
>
> --
> Jim Mooney
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor



--
http://echorand.me

From cybervigilante at gmail.com  Sat Apr 27 12:31:03 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 27 Apr 2013 03:31:03 -0700
Subject: [Tutor] changing list element in loop
In-Reply-To: <CANODV3nLqNZS48e8McU9VRQ9_oXV2dfr9g8DWb4Z8PyfdTzPZQ@mail.gmail.com>
References: <CALRAYNU_XvAWaU1_BWYNG3664aeHVdV0qLA0HDYpRbG+Mp3hHA@mail.gmail.com>
	<CANODV3nLqNZS48e8McU9VRQ9_oXV2dfr9g8DWb4Z8PyfdTzPZQ@mail.gmail.com>
Message-ID: <CALRAYNVsjwJOCOKGJQG=jb-6yeA7bEfQPMcLi6dX1M+mkVcphg@mail.gmail.com>

On 27 April 2013 02:55, Amit Saha <amitsaha.in at gmail.com> wrote:
> On Sat, Apr 27, 2013 at 7:49 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>> Why isn't 'e' changing to 'pP here when the vowel list is mutable:
>>
>> vowelList = list('aeiouy')
>>
>> for x in vowelList:
>>     if x == 'e':
>>         x = 'P'
>
> This is because x is really a label for the item in your list. It does
> not represent a reference to the position of element as it occurs in
> the list. For example:


Okay, I tried enumerate, but now I get an "immutable" error. So let's
turn this around since it's getting out of hand for a simple list
replacement ;')  What's the simplest way to go through a list, find
something, and replace it with something else?

vowels = 'aeiouy'
vlist  = enumerate(vowels)
for x in vlist:
    if x[1] == 'e':
        x[0] = 'P'

print(vowels)
#'tuple' object does not support item assignment

From amitsaha.in at gmail.com  Sat Apr 27 12:38:51 2013
From: amitsaha.in at gmail.com (Amit Saha)
Date: Sat, 27 Apr 2013 20:38:51 +1000
Subject: [Tutor] changing list element in loop
In-Reply-To: <CALRAYNVsjwJOCOKGJQG=jb-6yeA7bEfQPMcLi6dX1M+mkVcphg@mail.gmail.com>
References: <CALRAYNU_XvAWaU1_BWYNG3664aeHVdV0qLA0HDYpRbG+Mp3hHA@mail.gmail.com>
	<CANODV3nLqNZS48e8McU9VRQ9_oXV2dfr9g8DWb4Z8PyfdTzPZQ@mail.gmail.com>
	<CALRAYNVsjwJOCOKGJQG=jb-6yeA7bEfQPMcLi6dX1M+mkVcphg@mail.gmail.com>
Message-ID: <CANODV3nntTBedFXwSotn=mmwJxqw=ACaczvdqdY4Z48NL_sd=g@mail.gmail.com>

On Sat, Apr 27, 2013 at 8:31 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
> On 27 April 2013 02:55, Amit Saha <amitsaha.in at gmail.com> wrote:
>> On Sat, Apr 27, 2013 at 7:49 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>>> Why isn't 'e' changing to 'pP here when the vowel list is mutable:
>>>
>>> vowelList = list('aeiouy')
>>>
>>> for x in vowelList:
>>>     if x == 'e':
>>>         x = 'P'
>>
>> This is because x is really a label for the item in your list. It does
>> not represent a reference to the position of element as it occurs in
>> the list. For example:
>
>
> Okay, I tried enumerate, but now I get an "immutable" error. So let's
> turn this around since it's getting out of hand for a simple list
> replacement ;')  What's the simplest way to go through a list, find
> something, and replace it with something else?
>
> vowels = 'aeiouy'
> vlist  = enumerate(vowels)
> for x in vlist:
>     if x[1] == 'e':
>         x[0] = 'P'
>
> print(vowels)
> #'tuple' object does not support item assignment

The enumerate function returns you a tuple consisting of the 'index'
of the element and the element itself. So, you have to store the two
values individually. For example, here is what I did to achieve what
you want to:

>>> x=['a','e','i']
>>> for index, item in enumerate(x):
    if item == 'e':
        x[index]='P'


>>> x
['a', 'P', 'i']

In your attempt you were attempting to change the 'tuple' itself,
which is not what you want and which is not possible - tuples are
immutable.

I hope that makes things a little clearer?

Best,
Amit.



--
http://echorand.me

From steve at pearwood.info  Sat Apr 27 13:16:52 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 27 Apr 2013 21:16:52 +1000
Subject: [Tutor] changing list element in loop
In-Reply-To: <CALRAYNVsjwJOCOKGJQG=jb-6yeA7bEfQPMcLi6dX1M+mkVcphg@mail.gmail.com>
References: <CALRAYNU_XvAWaU1_BWYNG3664aeHVdV0qLA0HDYpRbG+Mp3hHA@mail.gmail.com>
	<CANODV3nLqNZS48e8McU9VRQ9_oXV2dfr9g8DWb4Z8PyfdTzPZQ@mail.gmail.com>
	<CALRAYNVsjwJOCOKGJQG=jb-6yeA7bEfQPMcLi6dX1M+mkVcphg@mail.gmail.com>
Message-ID: <517BB3A4.6060109@pearwood.info>

On 27/04/13 20:31, Jim Mooney wrote:

> Okay, I tried enumerate, but now I get an "immutable" error. So let's
> turn this around since it's getting out of hand for a simple list
> replacement ;')  What's the simplest way to go through a list, find
> something, and replace it with something else?
>
> vowels = 'aeiouy'
> vlist  = enumerate(vowels)

Let's see what that does:

py> print(vlist)
<enumerate object at 0xb7bcdb6c>

That's your first clue that something is wrong. There's no list! So when
you get your index later on, what do you change? You can't write back to
vowels, because that's a string and can't be modified.

Nevermind, let's keep going...


> for x in vlist:

So what's x? It's a tuple, and tuples are immutable. So you can't modify
that either.


>      if x[1] == 'e':
>          x[0] = 'P'

That can't work, and even if it did work, it won't modify vowels, because
that's a string.

The right way to do this is:


vowels = list('aeiouy')  # y is only sometimes a vowel
for index, char in enumerate(vowels):
     if char == 'e':
         vowels[index] = 'P'

print(vowels)  # still as a list
print(''.join(vowels))



-- 
Steven

From steve at pearwood.info  Sat Apr 27 13:20:37 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sat, 27 Apr 2013 21:20:37 +1000
Subject: [Tutor] changing list element in loop
In-Reply-To: <CALRAYNVsjwJOCOKGJQG=jb-6yeA7bEfQPMcLi6dX1M+mkVcphg@mail.gmail.com>
References: <CALRAYNU_XvAWaU1_BWYNG3664aeHVdV0qLA0HDYpRbG+Mp3hHA@mail.gmail.com>
	<CANODV3nLqNZS48e8McU9VRQ9_oXV2dfr9g8DWb4Z8PyfdTzPZQ@mail.gmail.com>
	<CALRAYNVsjwJOCOKGJQG=jb-6yeA7bEfQPMcLi6dX1M+mkVcphg@mail.gmail.com>
Message-ID: <517BB485.5070209@pearwood.info>

Oh, and another thing...

On 27/04/13 20:31, Jim Mooney wrote:

>What's the simplest way to go through a list, find
> something, and replace it with something else?

The simplest way is not to do it at all. Instead, create a new list:


vowels = 'aeiouy'
result = []
for char in vowels:
     if char == 'e':
         char = 'P'
     result.append(char)

result = ''.join(result)
print(result)


Of course, in this specific case, even faster and simpler is this:

result = vowels.replace('e', 'P')


but that's specifically a string method and doesn't generalise to
lists of arbitrary objects.




-- 
Steven

From alan.gauld at btinternet.com  Sat Apr 27 13:33:23 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 27 Apr 2013 12:33:23 +0100
Subject: [Tutor] changing list element in loop
In-Reply-To: <CALRAYNU_XvAWaU1_BWYNG3664aeHVdV0qLA0HDYpRbG+Mp3hHA@mail.gmail.com>
References: <CALRAYNU_XvAWaU1_BWYNG3664aeHVdV0qLA0HDYpRbG+Mp3hHA@mail.gmail.com>
Message-ID: <klgd1v$tgj$1@ger.gmane.org>

On 27/04/13 10:49, Jim Mooney wrote:
> Why isn't 'e' changing to 'pP here when the vowel list is mutable:
>
> vowelList = list('aeiouy')
>
> for x in vowelList:
>      if x == 'e':
>          x = 'P'


x is just a reference to the object in the list.
When you assign 'P' to x you are making x point at
a new object, you are not doing anything to the
original list.

The list itself is just a sequence of references
to objects. To change the item in the list you
need to change what that list reference is
pointing at.

The enumerate function helps do that by returning
the index as well as the item.

for index,item in enumerate(vowelList):
     if item == 'e':
        vowelLIst[index] = 'P'

Of course for strings there are easier way to do
substitutions using the string methods (replace)
but for general list processing thie above is the usual idiom.

You can also use a while loop obviously:

index = 0
while index < len(vowelList):
    if vowelList[index] == 'e':
       vowelList[index] = 'P'
    index += 1

But a for loop is usually the preferred mechanism.

For this specific use case you could also use a
map() or list comprehension to achieve the same
results:

def f(c): return c if c != 'e' else 'P'
vowelList = map(f,vowelList)   # using map OR...
vowelList = [f(c) for c in vowelList]   # using list comp


HTH

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


From fomcl at yahoo.com  Sat Apr 27 20:53:45 2013
From: fomcl at yahoo.com (fomcl at yahoo.com)
Date: Sat, 27 Apr 2013 11:53:45 -0700 (PDT)
Subject: [Tutor] symlinking dirs with spaces
Message-ID: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>



--- On Friday, April 26, 2013 9:53 PM, eryksun <eryksun at gmail.com> wrote:

On Fri, Apr 26, 2013 at 8:10 AM, mike <mike at froward.org> wrote:
>
> def link():
>     print "Adding %s to %s..." % (origFul, loadDir)
>     os.symlink('origFul', 'media')

Your arguments for symlink() are string literals. How about this?

    LOAD_DIR = "/opt/data/music/load"

    def link(media):
        src = os.path.abspath(media)
        dst = os.path.join(LOAD_DIR, os.path.basename(media))
        print "Adding %s to %s..." % (src, LOAD_DIR)
        os.symlink(src, dst)

IIRC, os.symlink is not present in Python on Windows, right? (I'm on vacation now so I can't check this). But aren't soft links and shortcuts linux and windows terms for the same thing? 

From steve at pearwood.info  Sun Apr 28 03:38:49 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 28 Apr 2013 11:38:49 +1000
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
Message-ID: <517C7DA9.4090301@pearwood.info>

On 28/04/13 04:53, fomcl at yahoo.com wrote:

> IIRC, os.symlink is not present in Python on Windows, right? (I'm on vacation now so I can't check this). But aren't soft links and shortcuts linux and windows terms for the same thing?

No, although they play similar roles.

Windows shortcuts are ordinary files with a .lnk extension. The content of the file points to another file on disk. Windows opens the file, looks inside to find out what target to look for, then looks for the target. That makes them somewhat like Mac OS aliases, only not as smart. (Mac aliases can actually keep tracking a file if you move it from location to location, even from disk to disk.)

Symbolic (soft links) links are file system features, which means that strictly speaking they depend on the file system, not the operating system. Unlike shortcuts or aliases, which are files, sym links exist in the file system metadata, which makes them smaller, faster to access, and more efficient.

Hard links are also file system features. Essentially, a hard link is a way to give a single file two names. If you think of the file system as a tree of file names pointing to storage locations on disk, hard links are two names pointing to a single location.

A little known fact: NTFS does support symbolic links, at least under Windows 7 and Vista. NTFS sym links have some limitations compared to POSIX (Unix, Mac, Linux, etc.) sym links, the biggest being that they don't work during boot-up.



-- 
Steven

From davea at davea.name  Sun Apr 28 03:51:30 2013
From: davea at davea.name (Dave Angel)
Date: Sat, 27 Apr 2013 21:51:30 -0400
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517C7DA9.4090301@pearwood.info>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info>
Message-ID: <517C80A2.5040100@davea.name>

On 04/27/2013 09:38 PM, Steven D'Aprano wrote:
> On 28/04/13 04:53, fomcl at yahoo.com wrote:
>
>> IIRC, os.symlink is not present in Python on Windows, right? (I'm on
>> vacation now so I can't check this). But aren't soft links and
>> shortcuts linux and windows terms for the same thing?
>
> No, although they play similar roles.
>
> Windows shortcuts are ordinary files with a .lnk extension. The content
> of the file points to another file on disk. Windows opens the file,
> looks inside to find out what target to look for, then looks for the
> target. That makes them somewhat like Mac OS aliases, only not as smart.
> (Mac aliases can actually keep tracking a file if you move it from
> location to location, even from disk to disk.)
>
> Symbolic (soft links) links are file system features, which means that
> strictly speaking they depend on the file system, not the operating
> system. Unlike shortcuts or aliases, which are files, sym links exist in
> the file system metadata, which makes them smaller, faster to access,
> and more efficient.
>
> Hard links are also file system features. Essentially, a hard link is a
> way to give a single file two names. If you think of the file system as
> a tree of file names pointing to storage locations on disk, hard links
> are two names pointing to a single location.
>
> A little known fact: NTFS does support symbolic links, at least under
> Windows 7 and Vista. NTFS sym links have some limitations compared to
> POSIX (Unix, Mac, Linux, etc.) sym links, the biggest being that they
> don't work during boot-up.
>
>
>

And another little-known fact -- NTFS supports hard links, or at least 
it did in 1995, on NT 3.5  As I recall, there wasn't support at the cmd 
prompt, but you could create them with system calls.


-- 
DaveA

From eryksun at gmail.com  Sun Apr 28 04:13:32 2013
From: eryksun at gmail.com (eryksun)
Date: Sat, 27 Apr 2013 22:13:32 -0400
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
Message-ID: <CACL+1asZFmbU-GfR7xHTKKBdOa6ARA+cQJdDndAiuPE_=K4VOg@mail.gmail.com>

On Sat, Apr 27, 2013 at 2:53 PM,  <fomcl at yahoo.com> wrote:
> --- On Friday, April 26, 2013 9:53 PM, eryksun <eryksun at gmail.com> wrote:
>> Your arguments for symlink() are string literals. How about this?
>>
>>     LOAD_DIR = "/opt/data/music/load"
>>
>>     def link(media):
>>         src = os.path.abspath(media)
>>         dst = os.path.join(LOAD_DIR, os.path.basename(media))
>>         print "Adding %s to %s..." % (src, LOAD_DIR)
>>         os.symlink(src, dst)
>
> IIRC, os.symlink is not present in Python on Windows, right? (I'm on vacation
> now so I can't check this). But aren't soft links and shortcuts linux and windows
> terms for the same thing?

Windows shortcuts (.lnk) are roughly equivalent to XDG .desktop files.

Python 3.2+  supports os.link() for files on NT.  It also supports
os.symlink() on NT 6+ (Vista and later). Creating a symbolic link will
fail if the process lacks the required privilege.

Background:

Win32 CreateHardLink was added in NT 5 (XP). Win32 CreateSymbolicLink
was added in NT 6 (Vista; Windows 7 is NT 6.1), which also added
"mklink" to the cmd shell. Creating symlinks requires
SeCreateSymbolicLinkPrivilege. The default security settings enable
this for administrators only.

NT also has directory junctions (NTFS reparse points), which work
transparently even if you're connected remotely. In contrast symlinks
are resolved on the client, which means symlinks can work with UNC
network paths (e.g. mklink /d mylink \\server\path). Maybe the
stricter security for symlinks was added because they work across the
network.

From cybervigilante at gmail.com  Sun Apr 28 04:21:46 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sat, 27 Apr 2013 19:21:46 -0700
Subject: [Tutor] Why isn't iteritems() working when items() does?
Message-ID: <CALRAYNUaxQJsDEsxCfX=FyBHLxMa7wvQzVK+3yP6LyBXoEaDng@mail.gmail.com>

#Changing a dictionary into a 2-tuple list with the items method
works, as per the
#first example. But using iteritems returns an error - using Py33

dick = {'villain': 'Roderigo', 'hero': 'Othello', 'friend': 'Cassio',
'beauty':'Desdemona'}

dickList = dick.items()
for role, name in dickList:
    print(role, name)

#The above works, but using iteritems() in place of items doesn't

dickList2 = dick.iteritems()
for role, name in dickList2:
    print(role, name)

#error: builtins.AttributeError: 'dict' object has no attribute 'iteritems'

-- 
Jim Mooney

Texting a program as he drove, John inadvertently dereferenced a null
pointer, and a huge crash ensued.

The good thing about crocodile farts is few of us feel the need to get
that close to a crocodile.

From msirenef at lightbird.net  Sun Apr 28 04:29:08 2013
From: msirenef at lightbird.net (Mitya Sirenef)
Date: Sat, 27 Apr 2013 22:29:08 -0400
Subject: [Tutor] Why isn't iteritems() working when items() does?
In-Reply-To: <CALRAYNUaxQJsDEsxCfX=FyBHLxMa7wvQzVK+3yP6LyBXoEaDng@mail.gmail.com>
References: <CALRAYNUaxQJsDEsxCfX=FyBHLxMa7wvQzVK+3yP6LyBXoEaDng@mail.gmail.com>
Message-ID: <517C8974.5040107@lightbird.net>

On 04/27/2013 10:21 PM, Jim Mooney wrote:
> #Changing a dictionary into a 2-tuple list with the items method
> works, as per the
> #first example. But using iteritems returns an error - using Py33
>
> dick = {'villain': 'Roderigo', 'hero': 'Othello', 'friend': 'Cassio',
> 'beauty':'Desdemona'}
>
> dickList = dick.items()
> for role, name in dickList:
>      print(role, name)
>
> #The above works, but using iteritems() in place of items doesn't
>
> dickList2 = dick.iteritems()
> for role, name in dickList2:
>      print(role, name)
>
> #error: builtins.AttributeError: 'dict' object has no attribute 'iteritems'
>


In py3.x, iteritems was replaced by .items()

  -m

-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/


From steve at pearwood.info  Sun Apr 28 04:49:50 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Sun, 28 Apr 2013 12:49:50 +1000
Subject: [Tutor] Why isn't iteritems() working when items() does?
In-Reply-To: <CALRAYNUaxQJsDEsxCfX=FyBHLxMa7wvQzVK+3yP6LyBXoEaDng@mail.gmail.com>
References: <CALRAYNUaxQJsDEsxCfX=FyBHLxMa7wvQzVK+3yP6LyBXoEaDng@mail.gmail.com>
Message-ID: <517C8E4E.3060205@pearwood.info>

On 28/04/13 12:21, Jim Mooney wrote:
> #Changing a dictionary into a 2-tuple list with the items method
> works, as per the
> #first example. But using iteritems returns an error - using Py33

Dicts no longer have three distinct methods for retrieving keys and values, as they did in Python 2.x. In Python 2, you had:


keys, iterkeys, viewkeys
values, itervalues, viewvalues
items, iteritems, viewitems

In Python 3, those nine methods have been reduced to three:

keys
values
items


Why did Python 2 have so many methods?

Way back in the dawn of time, Python dicts only had three such methods, keys, values and items. All three returned a list of the keys etc. The disadvantage of returning a list is that for large dicts, this can be very expensive, especially if you only need to look at one key at a time. And so were born the iter* versions, which lazily produced the keys etc. one at a time without needing to construct a full list first.

A few versions on, and dict *views* were invented. Views are described in the PEP (Python Enhancement Proposal) that introduced them:

http://www.python.org/dev/peps/pep-3106/

Come Python 3, and backward compatibility is allowed to be broken. So the dict methods that return lists and iterators were dropped, and the viewkeys, viewvalues and viewitems methods were renamed to just play old keys, values and items.

And that is where we stand today.


By the way, you can see what methods and attributes are available on an object using the dir() built-in function, and read some documentation about it using the help() function. At the interactive interpreter:

dir({}) will give a list of dict methods.

help({}) will drop you into the help system.



-- 
Steven

From eryksun at gmail.com  Sun Apr 28 19:43:09 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 28 Apr 2013 13:43:09 -0400
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517C80A2.5040100@davea.name>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
Message-ID: <CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>

On Sat, Apr 27, 2013 at 9:51 PM, Dave Angel <davea at davea.name> wrote:
>
> And another little-known fact -- NTFS supports hard links, or at least it
> did in 1995, on NT 3.5  As I recall, there wasn't support at the cmd prompt,
> but you could create them with system calls.

NTFS has always supported hard links as additional $FILE_NAME
attributes in the MFT file record, but it was primarily meant for the
POSIX subsystem. I did find a Win32 solution for NT 3.x, which may be
what you're recalling. It requires 3 calls to BackupWrite in order to
write a link (i.e. a $FILE_NAME attribute) to an existing file record.
Apparently this was documented by Microsoft circa '96, but the
original article no longer exists online. For an example see
CreateHardLinkNt4() here:

http://cpansearch.perl.org/src/AUDREYT/Win32-Hardlink-0.11/lnw.cpp

From robertvstepp at gmail.com  Sun Apr 28 21:03:27 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 28 Apr 2013 14:03:27 -0500
Subject: [Tutor] Helpful little book
Message-ID: <CANDiX9JeEY1YrR_qtxbv3oNnOmJ5wv6zCx5ZtUEvwy8j5BGEOQ@mail.gmail.com>

I have found the following book quite helpful and keep it handy:

"Python Pocket Reference" by Mark Lutz, 4th ed., c. 2010.

It was released at the time that 3.0 and 2.6 were the current Python
versions, but tries to include what was intended for the 2.x and 3.x
future releases as he knew them then.

HTH,
boB

From robertvstepp at gmail.com  Sun Apr 28 22:05:52 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 28 Apr 2013 15:05:52 -0500
Subject: [Tutor] Long post: How to design a Python program to generate GUI
 elements in a proprietary scripting language.
Message-ID: <CANDiX9JOOyqDy6BnkQfhKM5caT4YNf22m1MZn5s2Spgib66dXQ@mail.gmail.com>

At work I use a commercial program for radiation therapy planning.
This program has an extensive built-in, proprietary scripting language
that is accessible to the user. The scripting files are all
text-based. The OS that we are running the commercial software on is
Solaris 10. The scripting language has commands to execute commands
external to the software such as shell scripts, Perl scripts, Python
scripts, etc. However, in order to make anything happen within the
planning software, one must in the end be running a file from within
the software that contains only the proprietary scripting commands.

The proprietary scripting language has significant limitations; for
instance, it has no provision for looping constructs, text
manipulation, function creation, subprograms, etc. To date I have been
using external Perl scripts to generate text files that have the
needed proprietary scripting commands to force the planning software
to do the useful things I desire. Recently I have discovered it is
possible to use the proprietary scripting language to generate GUI's
that allow for user interaction. However, to do so one must
laboriously create the desired window in top-down fashion. Every
widget must be hand-coded and placed using appropriate coordinates. My
latest effort at entering the GUI world in this planning software
required six files, four of which were ~ 4000 lines of code each, most
of which was to create the elements of the window that was created.
However, the end result is quite useful and user friendly for my
colleagues and saves them a lot of work. Previously I had been using a
built-in interface that is not very user friendly when I required user
interaction with my scripts. However, if every time I have to generate
thousands of lines of code by hand to just get a window that is
friendly for the user, then I am not inclined to do this very often.

So I finally am coming to the Python point: I would like to write a
program in Python to more easily build these windows and their
elements. Whenever I need to construct a windowed interface, I want to
be able to call this program and have it generate the needed
proprietary scripting commands in a text file that I can run from
within the planning software. I have Python 2.4.6 and 2.4.4 available
to me, both running on Solaris 10.

The way these windows are formed are 1) There must be a top-level
construct, TempWindow; 2) Next there must be a FORM or DrawingArea
element; 3) Then a variety of GUI elements can be added such as
buttons, labels, scrolled windows, etc.

I can almost visualize how I might do this, but am currently stumped
on how to automatically generate the various parent-child naming
relationships that must exist between these elements. For instance if
my top level construct is TempWindow, in which everything is placed,
my next level might be DrawingArea, whose ParentName would be
TempWindow. But if I added two scrolled windows to DrawingArea, then
ScrolledWindow1 and ScrolledWindow2 would have a ParentName of
DrawingArea. Et cetera. A further difficulty is that as these things
get added, some of them have attachment commands, such as AttachTop,
AttachRight, etc. But some don't. And all elements have (x,y)
positioning coordinates as well as heights and widths. BTW, the (x,y)
coordinates are relative to the type of parent containing them. For
instance, ScrolledWindow1 and ScrolledWindow2 would have coordinates
relative to within TempWindow, but TempWindow would have coordinates
placing it on the monitor display. Elements within ScrolledWindow1
would have coordinates relative to the top left corner of
ScrolledWindow1.

What I am currently visualizing is ProprietaryScript calls external
PythonScript. This Python script is doing lots of things, but along
the way it will need to generate an overall window and then place
various widgets inside that window. It order to do these things it
would import PythonWindowModule, enabling PythonScript to use various
methods to generate the needed window elements. PythonScript would
pass needed information (such as x,y coordinates) to the appropriate
method in PythonWindowModule and PythonWindowModule would write the
appropriate proprietary scripting commands to the end of a designated
text file, that would later be run from within the planning software
to do what I need.

So, thinking about this I cannot see how to handle this parent-child
naming relationships between the different levels of GUI elements and
I do not see how to handle the attachment points when they are needed.
I have not delved into the OOP aspects of Python yet, but from my
current general understanding of OOP I am hopeful that it can handle
these issues. And, yes, I realize that I am jumping into the deep end
of the pool before even knowing how to swim, but this approach has
yielded many valuable Perl scripts at work, so I am willing to take
this plunge willy-nilly!

Any thoughts on how to approach this will, as always, be greatly appreciated!

Cheers!
boB

From alan.gauld at btinternet.com  Sun Apr 28 23:25:09 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sun, 28 Apr 2013 22:25:09 +0100
Subject: [Tutor] Long post: How to design a Python program to generate
 GUI elements in a proprietary scripting language.
In-Reply-To: <CANDiX9JOOyqDy6BnkQfhKM5caT4YNf22m1MZn5s2Spgib66dXQ@mail.gmail.com>
References: <CANDiX9JOOyqDy6BnkQfhKM5caT4YNf22m1MZn5s2Spgib66dXQ@mail.gmail.com>
Message-ID: <klk43h$ntq$1@ger.gmane.org>

On 28/04/13 21:05, boB Stepp wrote:

> to do the useful things I desire. Recently I have discovered it is
> possible to use the proprietary scripting language to generate GUI's
> that allow for user interaction. However, to do so one must
> laboriously create the desired window in top-down fashion. Every
> widget must be hand-coded and placed using appropriate coordinates.
 > ...
> So I finally am coming to the Python point: I would like to write a
> program in Python to more easily build these windows and their
> elements. Whenever I need to construct a windowed interface, I want to
> be able to call this program and have it generate the needed
> proprietary scripting commands in a text file that I can run from
> within the planning software.

You could build a full GUI builder in Python but that will be a lot of 
work. Is there room for a half way house?

I'd suggest building a Python program that reads a resource file (maybe 
using the configparser module and data format? Each section of config 
parser would specify the  unique elements of a window (or sub window).
Python then uses that data to generate boilerplate code in your 
scripting language which you then manually tweak to add behaviour etc.

It should be possible to define most widgets and colours etc in the data 
file relatively easily and have Python build the code for that.

Later on you could build a Python GUI that generated the data file
from a GUI builder type app. Then call the python script to generate the 
scripting code from there... Getting close to a full GUI builder then. 
But do it in stages.

> The way these windows are formed are 1) There must be a top-level
> construct, TempWindow; 2) Next there must be a FORM or DrawingArea
> element; 3) Then a variety of GUI elements can be added such as
> buttons, labels, scrolled windows, etc.

The common stuff can be a standard template within Python.
In fact you could probably put that in a file too in case
it changes in the future.

The important bit to put in the config file is the data
unique to a widget/panel. Name/Label/colour/location etc.
You don;t say how the widgets are bound to actions
(I assume they are) but you could maybe cover that too,
although its hard without a function concept - I assume
it has GOTO? But i suspect that may be the bit you have
to hand craft after the boilerplate is created.

> I can almost visualize how I might do this, but am currently stumped
> on how to automatically generate the various parent-child naming
> relationships that must exist between these elements. For instance if
> my top level construct is TempWindow, in which everything is placed,
> my next level might be DrawingArea, whose ParentName would be
> TempWindow.

Parent would be a data attribute in the config file...

> But if I added two scrolled windows to DrawingArea, then
> ScrolledWindow1 and ScrolledWindow2 would have a ParentName of
> DrawingArea. Et cetera.

You need to build the parent tree in your Ptython code.
So long as each widget definition tells you the parent
it should work ok.

> A further difficulty is that as these things
> get added, some of them have attachment commands, such as AttachTop,
> AttachRight, etc. But some don't.

Not really sure what that means... But again maybe an anchor attribute 
is needed?

>  And all elements have (x,y)
> positioning coordinates as well as heights and widths. BTW, the (x,y)
> coordinates are relative to the type of parent containing them. For
> instance, ScrolledWindow1 and ScrolledWindow2 would have coordinates
> relative to within TempWindow, but TempWindow would have coordinates
> placing it on the monitor display. Elements within ScrolledWindow1
> would have coordinates relative to the top left corner of
> ScrolledWindow1.

Thats not an issue in the config file, you just need to use
some squared paper (graph paper?) to draw your UI and plot
the relative coordinates before reating the data file.

> What I am currently visualizing is ProprietaryScript calls external
> PythonScript.

I think that creating the GUI at runtime is probably going to be
clunky and slow. I'd suggest you just write a Python pre-processor
that creates the proprietary GUI code.

> I have not delved into the OOP aspects of Python yet, but from my
> current general understanding of OOP I am hopeful that it can handle
> these issues.

OOP will help but its not magic, you will need to define and build the 
classes. But there are lots of OOP GUI frameworks to use as a starter 
for your heirarchy...

FWIW What I've suggested is quite similar to how the earliest Windows 
programs were built with a data resource file defining the look and a 
code file defining the actions and a compilation step linking the two. 
In this case you use Python to do the linkage plus a wee bit of hand 
coding to finish it off...

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


From cybervigilante at gmail.com  Mon Apr 29 00:31:45 2013
From: cybervigilante at gmail.com (Jim Mooney)
Date: Sun, 28 Apr 2013 15:31:45 -0700
Subject: [Tutor] Tutor Digest, Vol 110, Issue 117
In-Reply-To: <mailman.9.1367143201.19870.tutor@python.org>
References: <mailman.9.1367143201.19870.tutor@python.org>
Message-ID: <CALRAYNVxyeGM=NYsEbMsYQ7v387PrDdhV30=rnTULLFQs_5=_g@mail.gmail.com>

> In py3.x, iteritems was replaced by .items()

Interesting, since iteritems was in my book, which was "updated" for
Py33. I guess the moral is you shouldn't trust an author 100% ;')  I
must admit, iteritems did seem awkward and annoying so I'm glad it's
dropped.

Jim

From steve at pearwood.info  Mon Apr 29 01:14:18 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 29 Apr 2013 09:14:18 +1000
Subject: [Tutor] Helpful little book
In-Reply-To: <CANDiX9JeEY1YrR_qtxbv3oNnOmJ5wv6zCx5ZtUEvwy8j5BGEOQ@mail.gmail.com>
References: <CANDiX9JeEY1YrR_qtxbv3oNnOmJ5wv6zCx5ZtUEvwy8j5BGEOQ@mail.gmail.com>
Message-ID: <517DAD4A.4070308@pearwood.info>

On 29/04/13 05:03, boB Stepp wrote:
> I have found the following book quite helpful and keep it handy:
>
> "Python Pocket Reference" by Mark Lutz, 4th ed., c. 2010.
>
> It was released at the time that 3.0 and 2.6 were the current Python
> versions, but tries to include what was intended for the 2.x and 3.x
> future releases as he knew them then.


I concur, it's a fantastic little book. I have the 1st edition, which
was current for Python 1.5. I keep it handy for looking up regular
expression metacharacters :-)



-- 
Steven

From mike at froward.org  Mon Apr 29 02:17:11 2013
From: mike at froward.org (mike)
Date: Sun, 28 Apr 2013 19:17:11 -0500
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
	<CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
Message-ID: <517DBC07.1060600@froward.org>

On 04/28/2013 12:43 PM, eryksun wrote:
> On Sat, Apr 27, 2013 at 9:51 PM, Dave Angel <davea at davea.name> wrote:
>>
>> And another little-known fact -- NTFS supports hard links, or at least it
>> did in 1995, on NT 3.5  As I recall, there wasn't support at the cmd prompt,
>> but you could create them with system calls.
>
> NTFS has always supported hard links as additional $FILE_NAME
> attributes in the MFT file record, but it was primarily meant for the
> POSIX subsystem. I did find a Win32 solution for NT 3.x, which may be
> what you're recalling. It requires 3 calls to BackupWrite in order to
> write a link (i.e. a $FILE_NAME attribute) to an existing file record.
> Apparently this was documented by Microsoft circa '96, but the
> original article no longer exists online. For an example see
> CreateHardLinkNt4() here:
>
> http://cpansearch.perl.org/src/AUDREYT/Win32-Hardlink-0.11/lnw.cpp
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

My apologies for not responding, Dave's insight resolved my problem 
instantly. I am now having problems with a function I've made that is 
supposed to run a find on the media root dir and symlink anything that 
was downloaded within a specific amount of days, here is the code:

#!/usr/bin/env python
import os
from sys import argv
import subprocess
script, media = argv

# This is the directory you will sync the symbolic links from, to the 
device.
loadDir = "/opt/data/music/load/"

# Root dir of the media
musicDir = "/opt/data/music"

# This is the destination folder, whatever folder the device is mounted to.
destDir = "/media/rev/MOT"

# Get the current working directory
origDir = os.getcwd()

# Glob the current working directory and the "media" argument together
# to form a full file path
origFul = os.path.join('%s' % origDir, '%s' % media)

linkDir = ['ln', '-s', '%s' % origFul, '%s' % loadDir]



# Command to sync if media == "push"
syncCom = "rsync -avzL %s %s" % (loadDir, destDir)

def sync_new():
     durFind = raw_input("Enter the duration of time in days you want to 
link")
     durFind = int(durFind)
     fileExcl = "*torrent*"
     linkNew = ['find', '%s' % musicDir, '-maxdepth 2', '-mtime %s' % 
durFind, '-not', '-name', '%s' % fileExcl, '-exec addsync {} \;']
     subprocess.call(linkNew)

def link():
     print "Adding %s to %s..." % (origFul, loadDir)
     subprocess.call(linkDir)

def sync():
     print "Syncing the contents of %s to %s" % (loadDir, destDir)
     subprocess.call(syncCom, shell=True)

if media == "push":
     sync()
elif media == "pushnew":
     sync_new()
else:
     link()


Running the script with the pushnew argument results in the following 
error from find:

find: unknown predicate `-maxdepth 2'

I'm thinking this is also related to my usage of subprocess? I just 
started carving this out right now so I'm still debugging but if anyone 
sees anything obvious I would appreciate it.

From davea at davea.name  Mon Apr 29 02:37:33 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 28 Apr 2013 20:37:33 -0400
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517DBC07.1060600@froward.org>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
	<CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
	<517DBC07.1060600@froward.org>
Message-ID: <517DC0CD.7090409@davea.name>

On 04/28/2013 08:17 PM, mike wrote:
>
>>     <SNIP>
>>>
>
> def sync_new():
>      durFind = raw_input("Enter the duration of time in days you want to
> link")
>      durFind = int(durFind)
>      fileExcl = "*torrent*"
>      linkNew = ['find', '%s' % musicDir, '-maxdepth 2', '-mtime %s' %
> durFind, '-not', '-name', '%s' % fileExcl, '-exec addsync {} \;']
>      subprocess.call(linkNew)
>
        <SNIP>
>
> Running the script with the pushnew argument results in the following
> error from find:
>
> find: unknown predicate `-maxdepth 2'
>
> I'm thinking this is also related to my usage of subprocess? I just
> started carving this out right now so I'm still debugging but if anyone
> sees anything obvious I would appreciate it.
>

Your linkNew list doesn't have separate items for each argument to find. 
  The first example is that "-maxdepth" and "2" should be separate list 
items.  The only other spot I notice is the -exec item, which should be 
distinct from the following.

I don't understand why you have things like '%s' % musicDir, when 
musicDir is already a string.  That list item should be just musicDir, 
which would read much better.


-- 
DaveA

From steve at pearwood.info  Mon Apr 29 02:47:24 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 29 Apr 2013 10:47:24 +1000
Subject: [Tutor] Long post: How to design a Python program to generate
 GUI elements in a proprietary scripting language.
In-Reply-To: <CANDiX9JOOyqDy6BnkQfhKM5caT4YNf22m1MZn5s2Spgib66dXQ@mail.gmail.com>
References: <CANDiX9JOOyqDy6BnkQfhKM5caT4YNf22m1MZn5s2Spgib66dXQ@mail.gmail.com>
Message-ID: <517DC31C.1030800@pearwood.info>

On 29/04/13 06:05, boB Stepp wrote:
> At work I use a commercial program for radiation therapy planning.
> This program has an extensive built-in, proprietary scripting language
> that is accessible to the user.

Does this have a name? It's a bit clumsy to refer to "proprietary
scripting language" each time. I expect your program's documentation
refers to the scripting language by name.

Also, knowing the name would allow people to google for it. Who knows,
perhaps someone has already written something that solves your problem.

For lack of a better name, I'm going to call this GammaScript, since
it's involved in radiation therapy.

A full-blown GUI designer written in Python would be a lot of work, but
you might find that most of your GUIs follow a standard pattern, say:

1 window
1 heading
1 text field
OK and Cancel buttons
3-5 radio buttons
3-7 checkboxes
1-2 pop-up menus


in which case you can take such a script and turn it into a template.
Start off with a working GammaScript GUI script. I have no idea what that
looks like, so I'll just make something up:


create new window "Main Window"
add field "Label" to window "Main Window" at 20, 20
set the text of field "Label" to "Heading"
add field "Text" to window "Main Window" at 20, 40
set the size of field "Text" to 300, 400
set the scrollbar of field "Text" to true
add button "OK" to window "Main Window" at 270, 420
etc.


You can turn that into a template:


create new window $WINDOW_NAME
add field $LABEL_NAME to window $WINDOW_NAME at 20, 40
set the text of field $LABEL_NAME to $LABEL
add field $TEXT_NAME to window $WINDOW_NAME at 20, 20
...


Save it as a plain text file, call it "template.txt". Then have your
Python script read template.txt, query the user in some fashion for
the substitution values, and save the result as a GammaScript file.

Querying the user need not be interactive. You could take a
combination of approaches:

- read from a config file
- accept values from the command line
- interactively ask the user for values
- all of the above


The final step is for the user to hand-edit the generated GammaScript
file, before running it and seeing what breaks :-)

(Hopefully not anyone's radiation therapy...)


I recommend the string template safe_substitute method rather than
%s or {} formatting, since that will leave unused $TEMPLATES in the
file where you can see them and edit them by hand if needed.


If that works well, it might solve your problem. If not, you can
then take a few steps closer to a full-blown GUI builder by using
a custom mini-language to describe the GUI you want. E.g. you might
have something like this:


win = window("Main Window")
label = field(win, "Label", x=20, y=20, text="Heading")
text = field(win, "Text", x=20, y=40, size=(300, 400), scrollbar=True)
ok = button(win, x=text.right - 40, y=text.bottom + 30)
win.generate("mygammascript.gs")

which then generates the GammaScript code shown above. Because it's
Python, you can use normal Python constructs like for-loops:

for name in ("Alpha", "Beta", "Gamma"):
     x = checkbox(win, x=..., y=..., state=False)


A text interface like this is still a lot of work, but it's much less
work than a graphical interface, and nearly as useful.


But don't underestimate how much work this will be. This is a big
project.



-- 
Steven

From mike at froward.org  Mon Apr 29 02:54:10 2013
From: mike at froward.org (mike)
Date: Sun, 28 Apr 2013 19:54:10 -0500
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517DC0CD.7090409@davea.name>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
	<CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
	<517DBC07.1060600@froward.org> <517DC0CD.7090409@davea.name>
Message-ID: <517DC4B2.5000707@froward.org>

On 04/28/2013 07:37 PM, Dave Angel wrote:
> On 04/28/2013 08:17 PM, mike wrote:
>>
>>>     <SNIP>
>>>>
>>
>> def sync_new():
>>      durFind = raw_input("Enter the duration of time in days you want to
>> link")
>>      durFind = int(durFind)
>>      fileExcl = "*torrent*"
>>      linkNew = ['find', '%s' % musicDir, '-maxdepth 2', '-mtime %s' %
>> durFind, '-not', '-name', '%s' % fileExcl, '-exec addsync {} \;']
>>      subprocess.call(linkNew)
>>
>         <SNIP>
>>
>> Running the script with the pushnew argument results in the following
>> error from find:
>>
>> find: unknown predicate `-maxdepth 2'
>>
>> I'm thinking this is also related to my usage of subprocess? I just
>> started carving this out right now so I'm still debugging but if anyone
>> sees anything obvious I would appreciate it.
>>
>
> Your linkNew list doesn't have separate items for each argument to find.
>   The first example is that "-maxdepth" and "2" should be separate list
> items.  The only other spot I notice is the -exec item, which should be
> distinct from the following.
>
> I don't understand why you have things like '%s' % musicDir, when
> musicDir is already a string.  That list item should be just musicDir,
> which would read much better.
>
>
I separated the maxdepth argument with '-maxdepth', '2', seems and now 
it is focusing on the exec portion which i'm trying to figure out how to 
separate and make it sane as far as single/double quotes go.

Can you elaborate on what you mean regarding the musicDir variable? I 
have a loadDir which specifies where the symlinks reside but the actual 
root of the media directory is /opt/data/music and it's organized via 
directories based on genres which is why I am specifying musicDir 
instead of loadDir for this function



From steve at pearwood.info  Mon Apr 29 03:12:29 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Mon, 29 Apr 2013 11:12:29 +1000
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517DC4B2.5000707@froward.org>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
	<CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
	<517DBC07.1060600@froward.org> <517DC0CD.7090409@davea.name>
	<517DC4B2.5000707@froward.org>
Message-ID: <517DC8FD.6080101@pearwood.info>

On 29/04/13 10:54, mike wrote:

> Can you elaborate on what you mean regarding the musicDir variable? I have a loadDir which specifies where the symlinks reside but the actual root of the media directory is /opt/data/music and it's organized via directories based on genres which is why I am specifying musicDir instead of loadDir for this function

Your command, in part, looks like this:

linkNew = ['find', '%s' % musicDir, ...]

The first item is "find", the name of the command. The second item takes a variable which is already a string, musicDir, and turns it into a string using '%s' % musicDir. But it's already a string, so that's just double-handling. Instead, write this:

linkNew = ['find', musicDir, ...]



-- 
Steven

From davea at davea.name  Mon Apr 29 03:58:44 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 28 Apr 2013 21:58:44 -0400
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517DC4B2.5000707@froward.org>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
	<CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
	<517DBC07.1060600@froward.org> <517DC0CD.7090409@davea.name>
	<517DC4B2.5000707@froward.org>
Message-ID: <517DD3D4.6040500@davea.name>

On 04/28/2013 08:54 PM, mike wrote:
> On 04/28/2013 07:37 PM, Dave Angel wrote:
>> On 04/28/2013 08:17 PM, mike wrote:
>>>
>>>>     <SNIP>
>>>>>
>>>
>>> def sync_new():
>>>      durFind = raw_input("Enter the duration of time in days you want to
>>> link")
>>>      durFind = int(durFind)
>>>      fileExcl = "*torrent*"
>>>      linkNew = ['find', '%s' % musicDir, '-maxdepth 2', '-mtime %s' %
>>> durFind, '-not', '-name', '%s' % fileExcl, '-exec addsync {} \;']
>>>      subprocess.call(linkNew)
>>>
>>         <SNIP>
>>>
>>> Running the script with the pushnew argument results in the following
>>> error from find:
>>>
>>> find: unknown predicate `-maxdepth 2'
>>>
>>> I'm thinking this is also related to my usage of subprocess? I just
>>> started carving this out right now so I'm still debugging but if anyone
>>> sees anything obvious I would appreciate it.
>>>
>>
>> Your linkNew list doesn't have separate items for each argument to find.
>>   The first example is that "-maxdepth" and "2" should be separate list
>> items.  The only other spot I notice is the -exec item, which should be
>> distinct from the following.
>>
>> I don't understand why you have things like '%s' % musicDir, when
>> musicDir is already a string.  That list item should be just musicDir,
>> which would read much better.
>>
>>
> I separated the maxdepth argument with '-maxdepth', '2', seems and now
> it is focusing on the exec portion which i'm trying to figure out how to
> separate and make it sane as far as single/double quotes go.

If I were sure enough about the syntax to find (I only use -exec about 
once a year, and have to look it up each time), I could be explicit.

But if you want   -exec addsync {}
you should be using 3 different list items.

I don't think the \; means anything useful since you're not using the 
shell.  But if find needs a semicolon there somehow, I might try just ";"

Could you show us exactly what the find command would look like if you 
were executing it at the bash shell prompt?


>
> Can you elaborate on what you mean regarding the musicDir variable? I
> have a loadDir which specifies where the symlinks reside but the actual
> root of the media directory is /opt/data/music and it's organized via
> directories based on genres which is why I am specifying musicDir
> instead of loadDir for this function
>

Simple.  Since musicDir is a string,
     "%s" % musicDir
is a verbose way of saying
      musicDir

Likewise for fileexecl.  Neither is an error, just confusing.


-- 
DaveA

From davea at davea.name  Mon Apr 29 03:59:06 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 28 Apr 2013 21:59:06 -0400
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517DC4B2.5000707@froward.org>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
	<CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
	<517DBC07.1060600@froward.org> <517DC0CD.7090409@davea.name>
	<517DC4B2.5000707@froward.org>
Message-ID: <517DD3EA.90703@davea.name>

On 04/28/2013 08:54 PM, mike wrote:
> On 04/28/2013 07:37 PM, Dave Angel wrote:
>> On 04/28/2013 08:17 PM, mike wrote:
>>>
>>>>     <SNIP>
>>>>>
>>>
>>> def sync_new():
>>>      durFind = raw_input("Enter the duration of time in days you want to
>>> link")
>>>      durFind = int(durFind)
>>>      fileExcl = "*torrent*"
>>>      linkNew = ['find', '%s' % musicDir, '-maxdepth 2', '-mtime %s' %
>>> durFind, '-not', '-name', '%s' % fileExcl, '-exec addsync {} \;']
>>>      subprocess.call(linkNew)
>>>
>>         <SNIP>
>>>
>>> Running the script with the pushnew argument results in the following
>>> error from find:
>>>
>>> find: unknown predicate `-maxdepth 2'
>>>
>>> I'm thinking this is also related to my usage of subprocess? I just
>>> started carving this out right now so I'm still debugging but if anyone
>>> sees anything obvious I would appreciate it.
>>>
>>
>> Your linkNew list doesn't have separate items for each argument to find.
>>   The first example is that "-maxdepth" and "2" should be separate list
>> items.  The only other spot I notice is the -exec item, which should be
>> distinct from the following.
>>
>> I don't understand why you have things like '%s' % musicDir, when
>> musicDir is already a string.  That list item should be just musicDir,
>> which would read much better.
>>
>>
> I separated the maxdepth argument with '-maxdepth', '2', seems and now
> it is focusing on the exec portion which i'm trying to figure out how to
> separate and make it sane as far as single/double quotes go.

If I were sure enough about the syntax to find (I only use -exec about 
once a year, and have to look it up each time), I could be explicit.

But if you want   -exec addsync {}
you should be using 3 different list items.

I don't think the \; means anything useful since you're not using the 
shell.  But if find needs a semicolon there somehow, I might try just ";"

Could you show us exactly what the find command would look like if you 
were executing it at the bash shell prompt?


>
> Can you elaborate on what you mean regarding the musicDir variable? I
> have a loadDir which specifies where the symlinks reside but the actual
> root of the media directory is /opt/data/music and it's organized via
> directories based on genres which is why I am specifying musicDir
> instead of loadDir for this function
>

Simple.  Since musicDir is a string,
     "%s" % musicDir
is a verbose way of saying
      musicDir

Likewise for fileexecl.  Neither is an error, just confusing.


-- 
DaveA

From mike at froward.org  Mon Apr 29 04:00:05 2013
From: mike at froward.org (mike)
Date: Sun, 28 Apr 2013 21:00:05 -0500
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517DC8FD.6080101@pearwood.info>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
	<CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
	<517DBC07.1060600@froward.org> <517DC0CD.7090409@davea.name>
	<517DC4B2.5000707@froward.org> <517DC8FD.6080101@pearwood.info>
Message-ID: <517DD425.9050600@froward.org>

On 04/28/2013 08:12 PM, Steven D'Aprano wrote:
> On 29/04/13 10:54, mike wrote:
>
>> Can you elaborate on what you mean regarding the musicDir variable? I
>> have a loadDir which specifies where the symlinks reside but the
>> actual root of the media directory is /opt/data/music and it's
>> organized via directories based on genres which is why I am specifying
>> musicDir instead of loadDir for this function
>
> Your command, in part, looks like this:
>
> linkNew = ['find', '%s' % musicDir, ...]
>
> The first item is "find", the name of the command. The second item takes
> a variable which is already a string, musicDir, and turns it into a
> string using '%s' % musicDir. But it's already a string, so that's just
> double-handling. Instead, write this:
>
> linkNew = ['find', musicDir, ...]
>
>
>


Ahhh I see the redundancy now, the function seems satisfied with the 
linkNew list with the exception of how how I'm using '-exec ...'

I get the following when executing:

rev at sheridan:~/code$ ./addsync pushnew
Enter the duration of time in days you want to link
-5
find: missing argument to `-exec'
rev at sheridan:~/code$

this is the currently working list:

     linkNew = ['find', 'musicDir', '-maxdepth', '2', '-mtime', '%s' % 
durFind, '-not', '-name', '%s' % fileExcl, '-exec', 'addsync {} \;']


Is this an example where I want to be calling this while emulating a shell?


From mike at froward.org  Mon Apr 29 04:04:44 2013
From: mike at froward.org (mike)
Date: Sun, 28 Apr 2013 21:04:44 -0500
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517DD3EA.90703@davea.name>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
	<CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
	<517DBC07.1060600@froward.org> <517DC0CD.7090409@davea.name>
	<517DC4B2.5000707@froward.org> <517DD3EA.90703@davea.name>
Message-ID: <517DD53C.4030404@froward.org>

On 04/28/2013 08:59 PM, Dave Angel wrote:
> On 04/28/2013 08:54 PM, mike wrote:
>> On 04/28/2013 07:37 PM, Dave Angel wrote:
>>> On 04/28/2013 08:17 PM, mike wrote:
>>>>
>>>>>     <SNIP>
>>>>>>
>>>>
>>>> def sync_new():
>>>>      durFind = raw_input("Enter the duration of time in days you
>>>> want to
>>>> link")
>>>>      durFind = int(durFind)
>>>>      fileExcl = "*torrent*"
>>>>      linkNew = ['find', '%s' % musicDir, '-maxdepth 2', '-mtime %s' %
>>>> durFind, '-not', '-name', '%s' % fileExcl, '-exec addsync {} \;']
>>>>      subprocess.call(linkNew)
>>>>
>>>         <SNIP>
>>>>
>>>> Running the script with the pushnew argument results in the following
>>>> error from find:
>>>>
>>>> find: unknown predicate `-maxdepth 2'
>>>>
>>>> I'm thinking this is also related to my usage of subprocess? I just
>>>> started carving this out right now so I'm still debugging but if anyone
>>>> sees anything obvious I would appreciate it.
>>>>
>>>
>>> Your linkNew list doesn't have separate items for each argument to find.
>>>   The first example is that "-maxdepth" and "2" should be separate list
>>> items.  The only other spot I notice is the -exec item, which should be
>>> distinct from the following.
>>>
>>> I don't understand why you have things like '%s' % musicDir, when
>>> musicDir is already a string.  That list item should be just musicDir,
>>> which would read much better.
>>>
>>>
>> I separated the maxdepth argument with '-maxdepth', '2', seems and now
>> it is focusing on the exec portion which i'm trying to figure out how to
>> separate and make it sane as far as single/double quotes go.
>
> If I were sure enough about the syntax to find (I only use -exec about
> once a year, and have to look it up each time), I could be explicit.
>
> But if you want   -exec addsync {}
> you should be using 3 different list items.
>
> I don't think the \; means anything useful since you're not using the
> shell.  But if find needs a semicolon there somehow, I might try just ";"
>
> Could you show us exactly what the find command would look like if you
> were executing it at the bash shell prompt?
>
>
>>
>> Can you elaborate on what you mean regarding the musicDir variable? I
>> have a loadDir which specifies where the symlinks reside but the actual
>> root of the media directory is /opt/data/music and it's organized via
>> directories based on genres which is why I am specifying musicDir
>> instead of loadDir for this function
>>
>
> Simple.  Since musicDir is a string,
>      "%s" % musicDir
> is a verbose way of saying
>       musicDir
>
> Likewise for fileexecl.  Neither is an error, just confusing.
>
>

I didn't see your response dave, this would be the full syntax:



find /opt/data/music -maxdepth 2 -mtime -5 -not -name "*torrent*" -exec 
addsync {} \;



From robertvstepp at gmail.com  Mon Apr 29 04:23:44 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 28 Apr 2013 21:23:44 -0500
Subject: [Tutor] Long post: How to design a Python program to generate
 GUI elements in a proprietary scripting language.
In-Reply-To: <517DC31C.1030800@pearwood.info>
References: <CANDiX9JOOyqDy6BnkQfhKM5caT4YNf22m1MZn5s2Spgib66dXQ@mail.gmail.com>
	<517DC31C.1030800@pearwood.info>
Message-ID: <CANDiX9JYVoc6GMbaCzpj_B+K+Ba36EdZ0AgGUhBUJguQOS8Rdg@mail.gmail.com>

On Sun, Apr 28, 2013 at 7:47 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> On 29/04/13 06:05, boB Stepp wrote:
>>
>> At work I use a commercial program for radiation therapy planning.
>> This program has an extensive built-in, proprietary scripting language
>> that is accessible to the user.
>
>
> Does this have a name? It's a bit clumsy to refer to "proprietary
> scripting language" each time. I expect your program's documentation
> refers to the scripting language by name.
>
It felt clumsy as I was writing my post! But I did not think that
anyone would care about which specific software we use. The planning
software is "Pinnacle3" [The 3 is supposed to be a superscript]. It is
made by Philips. As far as I know the scripting language does not have
an identifying name. They call the scripts, "HotScripts", and people
that discuss the process of creating these call it (You guessed it.)
"HotScripting". The scripting as presented "officially" is meant to be
a macro recording facility, but users long ago figured out that they
could create their own custom script files to do more than mere macro
recording could accomplish. There is a users' group for the Pinnacle
software which I subscribe to, but to the best of my knowledge no one
has attempted what I am thinking about trying. The frustrating thing
about writing these custom scripts is that Pinnacle refuses to share
information about their scripting syntax unless you are an official
Pinnacle testing partner. The software was originally created and
owned by ADAC. In those days they had a class once a year that one
could go to to learn more about the scripting, or so I have been told.
Now on the Pinnacle list server people share what they have figured
out. This is what has led me to even trying to do GUI development work
within Pinnacle.

> A full-blown GUI designer written in Python would be a lot of work, but
> you might find that most of your GUIs follow a standard pattern, say:
>
> 1 window
> 1 heading
> 1 text field
> OK and Cancel buttons
> 3-5 radio buttons
> 3-7 checkboxes
> 1-2 pop-up menus
>
>
> in which case you can take such a script and turn it into a template.

I have only attempted three such GUI projects so far. The first one
was a HotScript organizer, which is a small window mostly made up of
buttons that either run a HotScript or take one to a new window with a
different category of scripts. The second one was a radio button
window that allows one to select which ROIs (Regions Of Interest)
should be generated for contouring by the dosimetrist (The person who
creates the treatment plans, which is what I am career-wise.). Both of
these were rather brief scripts and no problem. However, the third one
which I was referring to in my OP, is much more complex. It generates
a large window with potentially many fields which give numerical
information relevant to the current treatment plan. In fact how many
fields that the window might contain is unknown by the programmer
(me). It varies from patient to patient, dosimetrist to dosimetrist
and doctor to doctor. So I had to be very flexible. It compares the
plan's results with one of four tables of data to see if the plan
satisfies the clinical requirements of the appropriate table. If it
satisfies that requirement then the field containing the plan datum
will be color-coded green; if a minor deviation from the table yellow;
major deviation, red. The only possible user interaction with the
window is a dismiss button. So I do not see how a template approach
would be helpful, but I may be dense and/or unimaginative.

> You can turn that into a template:
>
>
> create new window $WINDOW_NAME
> add field $LABEL_NAME to window $WINDOW_NAME at 20, 40
> set the text of field $LABEL_NAME to $LABEL
> add field $TEXT_NAME to window $WINDOW_NAME at 20, 20
> ...

My thought was for the GUI module to use variables such as these to
which the calling program would pass this information to these
variables. But sometimes I might need radio buttons or label fields or
drop-down list boxes or  ... or any portion or combination of these,
depending on the new programming project, which is always customized
to specific planning needs.

>
> If that works well, it might solve your problem. If not, you can
> then take a few steps closer to a full-blown GUI builder by using
> a custom mini-language to describe the GUI you want. E.g. you might
> have something like this:
>
>
> win = window("Main Window")
> label = field(win, "Label", x=20, y=20, text="Heading")
> text = field(win, "Text", x=20, y=40, size=(300, 400), scrollbar=True)
> ok = button(win, x=text.right - 40, y=text.bottom + 30)
> win.generate("mygammascript.gs")
>

This is more like what I was considering.

> which then generates the GammaScript code shown above. Because it's
> Python, you can use normal Python constructs like for-loops:
>
> for name in ("Alpha", "Beta", "Gamma"):
>     x = checkbox(win, x=..., y=..., state=False)
>
>
> A text interface like this is still a lot of work, but it's much less
> work than a graphical interface, and nearly as useful.

The main difference with what I need is that the values for at least
some of these GUI elements would need to be generated dynamically
based on a combination of what is already in the plan along with any
needed user input. It could vary significantly plan to plan.

>
> But don't underestimate how much work this will be. This is a big
> project.
>
I already gathered that it would be a big project! But I would rather
do a multi-thousand line project once if it would save me doing a
similar amount of work multiple times in the future.

boB

From davea at davea.name  Mon Apr 29 04:35:06 2013
From: davea at davea.name (Dave Angel)
Date: Sun, 28 Apr 2013 22:35:06 -0400
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517DD53C.4030404@froward.org>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
	<CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
	<517DBC07.1060600@froward.org> <517DC0CD.7090409@davea.name>
	<517DC4B2.5000707@froward.org> <517DD3EA.90703@davea.name>
	<517DD53C.4030404@froward.org>
Message-ID: <517DDC5A.7080207@davea.name>

On 04/28/2013 10:04 PM, mike wrote:
> On 04/28/2013 08:59 PM, Dave Angel wrote:
>> On 04/28/2013 08:54 PM, mike wrote:
>>> On 04/28/2013 07:37 PM, Dave Angel wrote:
>>>> On 04/28/2013 08:17 PM, mike wrote:
>>>>>
>>>>>>     <SNIP>
>>>>>>>
>>>>>
>>>>> def sync_new():
>>>>>      durFind = raw_input("Enter the duration of time in days you
>>>>> want to
>>>>> link")
>>>>>      durFind = int(durFind)
>>>>>      fileExcl = "*torrent*"
>>>>>      linkNew = ['find', '%s' % musicDir, '-maxdepth 2', '-mtime %s' %
>>>>> durFind, '-not', '-name', '%s' % fileExcl, '-exec addsync {} \;']
>>>>>      subprocess.call(linkNew)
>>>>>
>>>>         <SNIP>
>>>>>
>>>>> Running the script with the pushnew argument results in the following
>>>>> error from find:
>>>>>
>>>>> find: unknown predicate `-maxdepth 2'
>>>>>
>>>>> I'm thinking this is also related to my usage of subprocess? I just
>>>>> started carving this out right now so I'm still debugging but if
>>>>> anyone
>>>>> sees anything obvious I would appreciate it.
>>>>>
>>>>
>>>> Your linkNew list doesn't have separate items for each argument to
>>>> find.
>>>>   The first example is that "-maxdepth" and "2" should be separate list
>>>> items.  The only other spot I notice is the -exec item, which should be
>>>> distinct from the following.
>>>>
>>>> I don't understand why you have things like '%s' % musicDir, when
>>>> musicDir is already a string.  That list item should be just musicDir,
>>>> which would read much better.
>>>>
>>>>
>>> I separated the maxdepth argument with '-maxdepth', '2', seems and now
>>> it is focusing on the exec portion which i'm trying to figure out how to
>>> separate and make it sane as far as single/double quotes go.
>>
>> If I were sure enough about the syntax to find (I only use -exec about
>> once a year, and have to look it up each time), I could be explicit.
>>
>> But if you want   -exec addsync {}
>> you should be using 3 different list items.
>>
>> I don't think the \; means anything useful since you're not using the
>> shell.  But if find needs a semicolon there somehow, I might try just ";"
>>
>> Could you show us exactly what the find command would look like if you
>> were executing it at the bash shell prompt?
>>
>>
>>>
>>> Can you elaborate on what you mean regarding the musicDir variable? I
>>> have a loadDir which specifies where the symlinks reside but the actual
>>> root of the media directory is /opt/data/music and it's organized via
>>> directories based on genres which is why I am specifying musicDir
>>> instead of loadDir for this function
>>>
>>
>> Simple.  Since musicDir is a string,
>>      "%s" % musicDir
>> is a verbose way of saying
>>       musicDir
>>
>> Likewise for fileexecl.  Neither is an error, just confusing.
>>
>>
>
> I didn't see your response dave, this would be the full syntax:
>
>
>
> find /opt/data/music -maxdepth 2 -mtime -5 -not -name "*torrent*" -exec
> addsync {} \;
>
>

Then I think you should change:
      '-exec', 'addsync {} \;']

to
      '-exec', 'addsync", "{}" ";"]



-- 
DaveA

From robertvstepp at gmail.com  Mon Apr 29 04:57:55 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Sun, 28 Apr 2013 21:57:55 -0500
Subject: [Tutor] Long post: How to design a Python program to generate
 GUI elements in a proprietary scripting language.
In-Reply-To: <klk43h$ntq$1@ger.gmane.org>
References: <CANDiX9JOOyqDy6BnkQfhKM5caT4YNf22m1MZn5s2Spgib66dXQ@mail.gmail.com>
	<klk43h$ntq$1@ger.gmane.org>
Message-ID: <CANDiX9+KJy=BsYYd2_rmDBpzuR32ksJMeEFcCu4MyOsbwz4qjQ@mail.gmail.com>

On Sun, Apr 28, 2013 at 4:25 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:

>
> You could build a full GUI builder in Python but that will be a lot of work.
> Is there room for a half way house?
>

I sure hope so!

> I'd suggest building a Python program that reads a resource file (maybe
> using the configparser module and data format? Each section of config parser
> would specify the  unique elements of a window (or sub window).
> Python then uses that data to generate boilerplate code in your scripting
> language which you then manually tweak to add behaviour etc.
>

I am not familiar with this module. I will have to look up its
documentation. Does it exist in Python 2.4? But for this to work for
my situations, it would have to result in the proper window generation
with no tweaking. And the desired behavior at times would depend on
how a particular field's value compares to different ranges of
possible values. This would be unique to each patient's plan.

> It should be possible to define most widgets and colours etc in the data
> file relatively easily and have Python build the code for that.
>

Sounds potentially promising...

>
> The important bit to put in the config file is the data
> unique to a widget/panel. Name/Label/colour/location etc.
> You don;t say how the widgets are bound to actions
> (I assume they are) but you could maybe cover that too,
> although its hard without a function concept - I assume
> it has GOTO? But i suspect that may be the bit you have
> to hand craft after the boilerplate is created.
>

Alas, there is no GOTO within a script capability. The best that can
be done is to conditionally run another script file and then return to
the calling script.

>> I can almost visualize how I might do this, but am currently stumped
>> on how to automatically generate the various parent-child naming
>> relationships that must exist between these elements. For instance if
>> my top level construct is TempWindow, in which everything is placed,
>> my next level might be DrawingArea, whose ParentName would be
>> TempWindow.
>
>
> Parent would be a data attribute in the config file...
>
>
>> But if I added two scrolled windows to DrawingArea, then
>> ScrolledWindow1 and ScrolledWindow2 would have a ParentName of
>> DrawingArea. Et cetera.
>
>
> You need to build the parent tree in your Ptython code.
> So long as each widget definition tells you the parent
> it should work ok.
>

I am not 100% sure I am following what you mean here. I will have to
give this some thought.

>> A further difficulty is that as these things
>> get added, some of them have attachment commands, such as AttachTop,
>> AttachRight, etc. But some don't.
>
>
> Not really sure what that means... But again maybe an anchor attribute is
> needed?
>

Say I had DrawingArea, ScrolledWindow1 (within DrawingArea) and
ScrolledWindow2 (also within DrawingArea). ScrolledWindow1 would have
to be specified as: AttachTop = DrawingArea; AttachRight =
DrawingArea; AttachLeft = DrawingArea; and AttachBottom = "--".
ScrolledWindow2, which is to be below ScrolledWindow1 would be:
AttachTop = ScrolledWindow1; AttachRight = DrawingArea; AttachLeft =
DrawingArea; and AttachBottom = DrawingArea. These would give a window
where the two scrolled windows would entirely filled the available
DrawingArea and give their spatial relationships in the window to each
other and other elements of the window.

>
>> What I am currently visualizing is ProprietaryScript calls external
>> PythonScript.
>
>
> I think that creating the GUI at runtime is probably going to be
> clunky and slow. I'd suggest you just write a Python pre-processor
> that creates the proprietary GUI code.
>

Unfortunately in most instances the window would have to be generated
at runtime. And any fields in it would be filled in depending on what
the plan's values were at runtime. But you are correct. I have been
giving some thought as to how to speed up the performance of the
program I have just written. It takes about 30 seconds, plus or minus,
to populate all of the fields in the displayed window and make the
necessary comparisons. But for the planning dosimetrist to manually
generate this data and do the comparisons manually can take most of 30
minutes at times, while wondering if he had made any mistakes.

>> I have not delved into the OOP aspects of Python yet, but from my
>> current general understanding of OOP I am hopeful that it can handle
>> these issues.
>
>
> OOP will help but its not magic, you will need to define and build the
> classes. But there are lots of OOP GUI frameworks to use as a starter for
> your heirarchy...
>
> FWIW What I've suggested is quite similar to how the earliest Windows
> programs were built with a data resource file defining the look and a code
> file defining the actions and a compilation step linking the two. In this
> case you use Python to do the linkage plus a wee bit of hand coding to
> finish it off...

Thanks for the food for thought!
boB

From eryksun at gmail.com  Mon Apr 29 05:44:16 2013
From: eryksun at gmail.com (eryksun)
Date: Sun, 28 Apr 2013 23:44:16 -0400
Subject: [Tutor] symlinking dirs with spaces
In-Reply-To: <517DDC5A.7080207@davea.name>
References: <1367088825.90983.ymail_j2me@web163804.mail.gq1.yahoo.com>
	<517C7DA9.4090301@pearwood.info> <517C80A2.5040100@davea.name>
	<CACL+1avGdO5oQDbkeEQT=TD1fjQ4OTtzay6FFpaN7q8wqGx0HA@mail.gmail.com>
	<517DBC07.1060600@froward.org> <517DC0CD.7090409@davea.name>
	<517DC4B2.5000707@froward.org> <517DD3EA.90703@davea.name>
	<517DD53C.4030404@froward.org> <517DDC5A.7080207@davea.name>
Message-ID: <CACL+1atmYxpdZ2DjPOgATgOy+kqD_cEAOVjbuwcbdh7jVd8M5g@mail.gmail.com>

On Sun, Apr 28, 2013 at 10:35 PM, Dave Angel <davea at davea.name> wrote:
> Then I think you should change:
>      '-exec', 'addsync {} \;']
>
> to
>      '-exec', 'addsync", "{}" ";"]

This has a mismatched quote and a missing comma. It should be like this:

    '-exec', 'addsync', '{}', ';']

"find" expects the command to be split as the shell would. Note, the \
is only used to escape the semicolon in the shell. It shouldn't be
used in the argument list.

From peter at pelican.ucsd.edu  Fri Apr 26 22:50:40 2013
From: peter at pelican.ucsd.edu (Peter Rowat)
Date: Fri, 26 Apr 2013 13:50:40 -0700 (PDT)
Subject: [Tutor] How to zoom in matplotlib without a mouse ?
Message-ID: <201304262050.r3QKoead007933@pelican.ucsd.edu>

To "zoom" a matplotlib graph, the matplotlib docs all say "use R mouse button".

But my laptop has no mouse, only a touchpad (running OSX Mountain Lion).
I've tried lots of  "click plus key" combinations, no luck yet.

Any ideas?

Thanks,
Peter R

From rsbrooks at alaska.edu  Sun Apr 28 12:01:51 2013
From: rsbrooks at alaska.edu (Ramy Brooks)
Date: Sun, 28 Apr 2013 02:01:51 -0800
Subject: [Tutor] point distance analysis
Message-ID: <CANZJrJwwU7BpeUmUTW=sO10fD1DDWXyGevo3H4zOSW2dQmpzmw@mail.gmail.com>

Hi I am looking for suggestions to fix my script to add an additional field.

Here is the script that I used and it calculates the distances that I was
trying to get, but I need to create an additional field in my table that
identifies the classification of the near_field ID so that I can use the
various distances to do a spatial analysis by summing the inverse square of
the distance for each unique classification to get a weighted probability
to classify the unclassified points.

Thank you

R. Brooks

import arcpy
arcpy.env.workspace =
r"G:\GEOS_458\ARDF_Project\CS_MOD_Map\ARDF_reclass.gdb"
# set variables
in_features= "csm_dict1b"
near_features= "csm_dict1b"
out_table ="pt_pt_dis2"
search_radius = "100 miles"


try:
    # find distances within a 100 mile radius

arcpy.PointDistance_analysis(in_features,near_features,out_table,search_radius)
    print arcpy.GetMessages(0)

except arcpy.ExecuteError:
    print arcpy.GetMessages(2)

except Exception as ex:
    print ex.args(0)

def main():
    pass

if __name__ == '__main__':
    main()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130428/bf16e30f/attachment-0001.html>

From eryksun at gmail.com  Mon Apr 29 11:07:36 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 29 Apr 2013 05:07:36 -0400
Subject: [Tutor] How to zoom in matplotlib without a mouse ?
In-Reply-To: <201304262050.r3QKoead007933@pelican.ucsd.edu>
References: <201304262050.r3QKoead007933@pelican.ucsd.edu>
Message-ID: <CACL+1asiE79zceyfk5Q-L=84tws860+JPdZv8jFHNp3moZwZvw@mail.gmail.com>

On Fri, Apr 26, 2013 at 4:50 PM, Peter Rowat <peter at pelican.ucsd.edu> wrote:
> To "zoom" a matplotlib graph, the matplotlib docs all say "use R mouse button".
>
> But my laptop has no mouse, only a touchpad (running OSX Mountain Lion).
> I've tried lots of  "click plus key" combinations, no luck yet.
>
> Any ideas?

I'm not a Mac user. A right-mouse click is often called a "secondary"
click, which is possibly a "two finger" click on your Mac.

With the "pan/zoom" tool, you zoom the axes by moving the pointer
while holding the secondary button. I don't know how easy that will be
with your touchpad. I usually use the "zoom rect" tool; you drag a
rectangular outline over the area you want to zoom. You could also use
ion() to switch to interactive mode. Then use axis([xmin, xmax, ymin,
ymax]) to programmatically zoom the graph.

From alan.gauld at btinternet.com  Mon Apr 29 11:08:37 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 29 Apr 2013 10:08:37 +0100
Subject: [Tutor] Long post: How to design a Python program to generate
 GUI elements in a proprietary scripting language.
In-Reply-To: <CANDiX9+KJy=BsYYd2_rmDBpzuR32ksJMeEFcCu4MyOsbwz4qjQ@mail.gmail.com>
References: <CANDiX9JOOyqDy6BnkQfhKM5caT4YNf22m1MZn5s2Spgib66dXQ@mail.gmail.com>
	<klk43h$ntq$1@ger.gmane.org>
	<CANDiX9+KJy=BsYYd2_rmDBpzuR32ksJMeEFcCu4MyOsbwz4qjQ@mail.gmail.com>
Message-ID: <klldag$riv$1@ger.gmane.org>

On 29/04/13 03:57, boB Stepp wrote:

>> I'd suggest building a Python program that reads a resource file (maybe
>> using the configparser module and data format?
>
> I am not familiar with this module. I will have to look up its
> documentation. Does it exist in Python 2.4?

Yes, the format is essentially that used in Windows config files

[section1]
label1=value
label2=value2

[section2]
label3=value

etc

> my situations, it would have to result in the proper window generation
> with no tweaking.

Thats going to be really hard given the limits of your Proprietary 
Scripting Language(PSL). How do you link actions to widgets? For example 
when you create a button how do you define what that button does? A 
short example of that would be helpful to understand the limits.

> And the desired behavior at times would depend on
> how a particular field's value compares to different ranges of
> possible values. This would be unique to each patient's plan.

OK, So now we need to map the plan data to a set of widgets and the 
widgets to a set of template code. Provided we can identify the widget 
type from the plan data then it can still be done with a config file

[PlanWidgets]
monthly=slider
oneoff=button
choice=radiobutton
etc...

[slider]
geometry=landscape
position=$LOCATION
label=$TEXT
name=$NAME
action=$SCRIPT

[button]
position=$LOCATION
label=$NAME
etc...

where $XXX is data obtained at runtime from your script or from a second 
config file that is project specific. (Or even a database!)

> Alas, there is no GOTO within a script capability. The best that can
> be done is to conditionally run another script file and then return to
> the calling script.

OK  So we can name a script as the action to be executed.
Can you retrieve the results of the called script?(via a file maybe?)

> AttachTop = ScrolledWindow1; AttachRight = DrawingArea; AttachLeft =
> DrawingArea; and AttachBottom = DrawingArea. These would give a window
> where the two scrolled windows would entirely filled the available
> DrawingArea and give their spatial relationships in the window to each
> other and other elements of the window.

OK, Thats what I suspected, its a form of anchor specification.

> Unfortunately in most instances the window would have to be generated
> at runtime.

The whole window? Or just a panel within it?
If its only for display could you use formatted text to display the plan 
data? Or is there user interaction with the dynamic data?
Formatting text is a lot easier than dynamically building a
GUI in a crippled scripting language! But only if you aren't interacting 
with it!

> program I have just written. It takes about 30 seconds, plus or minus,
> to populate all of the fields in the displayed window and make the
> necessary comparisons. But for the planning dosimetrist to manually
> generate this data and do the comparisons manually can take most of 30
> minutes at times, while wondering if he had made any mistakes.

Yes, but once they get used to your program they will forget that and 
just notice how long they have to wait for the GUI! Its the nature of 
users...

I think you need to maximise commonality here. Try to define a common 
structure for the GUIs and isolate the dynamic areas to a minimal area - 
preferably a single panel within the GUI. You can then statically create 
the outer framework using the kind of config template idea I first 
suggested then insert into the output of that the dynamic elements
just where they are needed.

But at this point we go beyond abstractions and need real use cases and 
data samples and work flows to be able to give any more sensible advice.


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


From alan.gauld at btinternet.com  Mon Apr 29 11:16:19 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 29 Apr 2013 10:16:19 +0100
Subject: [Tutor] Helpful little book
In-Reply-To: <CANDiX9JeEY1YrR_qtxbv3oNnOmJ5wv6zCx5ZtUEvwy8j5BGEOQ@mail.gmail.com>
References: <CANDiX9JeEY1YrR_qtxbv3oNnOmJ5wv6zCx5ZtUEvwy8j5BGEOQ@mail.gmail.com>
Message-ID: <klldou$pc$1@ger.gmane.org>

On 28/04/13 20:03, boB Stepp wrote:
> I have found the following book quite helpful and keep it handy:
>
> "Python Pocket Reference" by Mark Lutz, 4th ed., c. 2010.
>

I have an earlier version but yes these pocket books byy O'reilly are 
generally useful once you know what to look for. The don't have indexes 
which is my biggest complaint! But I have a dozen or so of them.

They aren't tutorials though (apart from the JQuery one which kind of 
is!) but they are useful crib sheets.

Also they often sell for silly money (as in less than a dollar :) in the 
Amazon marketplace...

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


From eryksun at gmail.com  Mon Apr 29 11:26:08 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 29 Apr 2013 05:26:08 -0400
Subject: [Tutor] point distance analysis
In-Reply-To: <CANZJrJwwU7BpeUmUTW=sO10fD1DDWXyGevo3H4zOSW2dQmpzmw@mail.gmail.com>
References: <CANZJrJwwU7BpeUmUTW=sO10fD1DDWXyGevo3H4zOSW2dQmpzmw@mail.gmail.com>
Message-ID: <CACL+1auTd6C152yRUOub49VH8FkXOnKoUMYpqsXHgGWiqJqn-w@mail.gmail.com>

On Sun, Apr 28, 2013 at 6:01 AM, Ramy Brooks <rsbrooks at alaska.edu> wrote:
>
> Here is the script that I used and it calculates the distances that I was
> trying to get, but I need to create an additional field in my table
[....]
> import arcpy

Try asking on the GIS Stack Exchange. Best of luck.

http://gis.stackexchange.com/questions/tagged/arcpy

From davea at davea.name  Mon Apr 29 13:20:16 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 29 Apr 2013 07:20:16 -0400
Subject: [Tutor] How to zoom in matplotlib without a mouse ?
In-Reply-To: <CACL+1asiE79zceyfk5Q-L=84tws860+JPdZv8jFHNp3moZwZvw@mail.gmail.com>
References: <201304262050.r3QKoead007933@pelican.ucsd.edu>
	<CACL+1asiE79zceyfk5Q-L=84tws860+JPdZv8jFHNp3moZwZvw@mail.gmail.com>
Message-ID: <517E5770.8040101@davea.name>

On 04/29/2013 05:07 AM, eryksun wrote:
> On Fri, Apr 26, 2013 at 4:50 PM, Peter Rowat <peter at pelican.ucsd.edu> wrote:
>> To "zoom" a matplotlib graph, the matplotlib docs all say "use R mouse button".
>>
>> But my laptop has no mouse, only a touchpad (running OSX Mountain Lion).
>> I've tried lots of  "click plus key" combinations, no luck yet.
>>
>> Any ideas?
>
> I'm not a Mac user. A right-mouse click is often called a "secondary"
> click, which is possibly a "two finger" click on your Mac.
>
> With the "pan/zoom" tool, you zoom the axes by moving the pointer
> while holding the secondary button. I don't know how easy that will be
> with your touchpad. I usually use the "zoom rect" tool; you drag a
> rectangular outline over the area you want to zoom. You could also use
> ion() to switch to interactive mode. Then use axis([xmin, xmax, ymin,
> ymax]) to programmatically zoom the graph.
>

I'm not a Mac user either.  But doing a quick DuckDuckGo search using 
the keywords:
     osx right mouse click

I find that ctrl-click is supposed to emulate a right-click.  Seems to 
me that ought to work with the touchpad as well as with the mouse.

Alternatively, the following quote:

     http://www.macinstruct.com/node/66
If you own a Macbook or Macbook Pro, you can configure your trackpad for 
right-clicking. (Some older iBooks and Powerbooks also provide this 
feature.) Simply open the Trackpad options in System Preferences and 
make sure the Place two fingers on trackpad and click button for 
secondary click button is checked.

or

     http://osxdaily.com/2011/05/24/enable-right-click-mac/
Open System Preferences
Click on Trackpad
Under the ?One Finger? section, select the checkbox next to ?Secondary 
Click? and select ?Bottom Right Corner?
Adjust the standard Mac OS X secondary click behavior with a two 
fingered click as you see fit
I would suggest keeping things foolproof and having both options enabled.




-- 
DaveA

From alan.gauld at btinternet.com  Mon Apr 29 15:27:01 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 29 Apr 2013 14:27:01 +0100
Subject: [Tutor] point distance analysis
In-Reply-To: <CANZJrJwwU7BpeUmUTW=sO10fD1DDWXyGevo3H4zOSW2dQmpzmw@mail.gmail.com>
References: <CANZJrJwwU7BpeUmUTW=sO10fD1DDWXyGevo3H4zOSW2dQmpzmw@mail.gmail.com>
Message-ID: <kllsf0$1ho$1@ger.gmane.org>

On 28/04/13 11:01, Ramy Brooks wrote:
> Hi I am looking for suggestions to fix my script to add an additional field.
>

This looks like is more of an arcpy question than a Python one. I 
suggest you try the arcpy support fora. Meantime a quick comment on your 
code...


>
> def main():
>      pass
>
> if __name__ == '__main__':
>      main()

This code is pointless, it just calls a function that does nothing.
It would make some sense if you had the code within your 'try' section 
inside the main() function but as it stands you might as well just 
delete it.


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


From robertvstepp at gmail.com  Mon Apr 29 15:38:34 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 29 Apr 2013 08:38:34 -0500
Subject: [Tutor] Helpful little book
In-Reply-To: <klldou$pc$1@ger.gmane.org>
References: <CANDiX9JeEY1YrR_qtxbv3oNnOmJ5wv6zCx5ZtUEvwy8j5BGEOQ@mail.gmail.com>
	<klldou$pc$1@ger.gmane.org>
Message-ID: <CANDiX9+RJYPxq-GNxruetVdM-f_S6PvmDoEZonD+rP8_==3O_w@mail.gmail.com>

On Mon, Apr 29, 2013 at 4:16 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 28/04/13 20:03, boB Stepp wrote:
>>
>> I have found the following book quite helpful and keep it handy:
>>
>> "Python Pocket Reference" by Mark Lutz, 4th ed., c. 2010.
>>
>
> I have an earlier version but yes these pocket books byy O'reilly are
> generally useful once you know what to look for. The don't have indexes
> which is my biggest complaint! But I have a dozen or so of them.
>
Apparently they have added an index. At least for the 4th edition that
I have for Python it contains a full index, which I go to all of the
time.

boB

From alan.gauld at btinternet.com  Mon Apr 29 16:18:44 2013
From: alan.gauld at btinternet.com (ALAN GAULD)
Date: Mon, 29 Apr 2013 15:18:44 +0100 (BST)
Subject: [Tutor] Helpful little book
In-Reply-To: <CANDiX9+RJYPxq-GNxruetVdM-f_S6PvmDoEZonD+rP8_==3O_w@mail.gmail.com>
References: <CANDiX9JeEY1YrR_qtxbv3oNnOmJ5wv6zCx5ZtUEvwy8j5BGEOQ@mail.gmail.com>
	<klldou$pc$1@ger.gmane.org>
	<CANDiX9+RJYPxq-GNxruetVdM-f_S6PvmDoEZonD+rP8_==3O_w@mail.gmail.com>
Message-ID: <1367245124.99449.YahooMailNeo@web186005.mail.ir2.yahoo.com>



Apparently they have added an index. At least for the 4th edition that
>I have for Python it contains a full index, which I go to all of the
>time.You're right! I don't know why I thought they didn't have an index...?
how odd. I just checked 4 of them and they all have indexes.

Senility beckons! :-(

Alan g.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130429/dc289e0a/attachment.html>

From sparkle.plenty12481632 at gmail.com  Mon Apr 29 16:28:15 2013
From: sparkle.plenty12481632 at gmail.com (sparkle Plenty)
Date: Mon, 29 Apr 2013 10:28:15 -0400
Subject: [Tutor] Associate decimal values with an integer range
Message-ID: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>

Hi, I need some hints on where to start solving this problem.
I have to interpret a one-byte floating point number as a range between 0
and 240.  This is for a gui that controls an amplifier.  I am getting a
value such as 0.8367 from a fader control, and my Python is interpreting it
as either a 0 or 1.  I need to define this number to Python as an integer
value between 0 and 240.  I know that in hex I have the potential for
numbers from 0 to 255 within my one byte of available space, and the value
will be sent from gui to amp and back as a packed one-byte number.  I have
looked at the math module and so far, I am still stuck.

Alas, business calc was a long time ago, and I never studied logarithms.  I
expect the answer would be easier to find if I had more math.

I welcome all assistance.

Thank you.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130429/743da49c/attachment.html>

From robertvstepp at gmail.com  Mon Apr 29 16:49:40 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 29 Apr 2013 09:49:40 -0500
Subject: [Tutor] Long post: How to design a Python program to generate
 GUI elements in a proprietary scripting language.
In-Reply-To: <klldag$riv$1@ger.gmane.org>
References: <CANDiX9JOOyqDy6BnkQfhKM5caT4YNf22m1MZn5s2Spgib66dXQ@mail.gmail.com>
	<klk43h$ntq$1@ger.gmane.org>
	<CANDiX9+KJy=BsYYd2_rmDBpzuR32ksJMeEFcCu4MyOsbwz4qjQ@mail.gmail.com>
	<klldag$riv$1@ger.gmane.org>
Message-ID: <CANDiX9Lyiva0ovGnJ3xEVFCqt8xYarA8tCa4BdCO0S9E6JnN0w@mail.gmail.com>

Alan,

I am at work now, so I will try to reply to those things I can answer
quickly. Today is a full planning day, not a programming day!

On Mon, Apr 29, 2013 at 4:08 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:

>> my situations, it would have to result in the proper window generation
>> with no tweaking.
>
>
> Thats going to be really hard given the limits of your Proprietary Scripting
> Language(PSL). How do you link actions to widgets? For example when you
> create a button how do you define what that button does? A short example of
> that would be helpful to understand the limits.
>

The following is a typical example. Note that the Pinnacle scripting
language uses the "Store" for user defined variables. They can hold
any kind of object, whether a number or a window, etc.:

Store.At.TempWindow.AddChild = "";
Store.At.TempWindow.WidgetList.Last = {
   ParentName = "ParallelTissueScrolledArea;
   Name = "ActualVolumeLungs_Minus_PTV1350ValueLabel";
   WidgetClass = "Label";
   X = 660;
   Y = 20;
   Width = 75;
   Height = 10;
   UseQueryForLabel = 1;   # Turns on the ability to pull information
from the plan and stuff it into this label field.
   QueryValueKey = "Store.At.Lungs_Minus_PTV1350.Value";    # Makes
the label field display the value of this variable.
   QueryColorKey = "Store.At.Lungs_Minus_PTV1350Color.String";    #
Changes the color of the label field to the stored value resulting
from an earlier comparison check.
   AddBorder = 1;
};

If one wants to click a button and cause an action to occur, here is
an example from a different script:

Store.At.SBRT_Window.AddChild = "";
Store.At.SBRT_Window.WidgetList.Last = {
   WidgetClass = "PushButton";
   ParentName = "ButtonArea";
   Name = "DismissButton";
   AddAction = "";
   ReplaceCurrentAction = "Store.At.SBRT_Window.Unrealize";    #
Closes the window.
   Label = "Dismiss";
   AddAction = "";
   ReplaceCurrentAction = "Store.FreeAt.SBRT_Window";   # Clears the
contents of the variable holding the window object.
};

The above is pretty much the pattern Pinnacle scripting uses for GUI
element creation. Of course many don't have actions or queries
associated with them, so those would be omitted.

There are only two data types that I can use: floating point and
string. There is an integer function, but it only truncates the
decimal places that always exist. Further, I can use any variable as
either a string or a float by using ".String" or ".Value" on the end
of the variable name. If I wanted to execute


>> Alas, there is no GOTO within a script capability. The best that can
>> be done is to conditionally run another script file and then return to
>> the calling script.
>
>
> OK  So we can name a script as the action to be executed.
> Can you retrieve the results of the called script?(via a file maybe?)
>

In the Pinnacle environment all variables are global for the opened
plan that first started running a HotScript. So if we had the
variable, "Store.At.TempVariable.String", then it would maintain the
most recent value for the most recently run script until
"Store.FreeAt.TempVariable" is run to clear it.

I will have to look at the rest later. Hope this helps make things a
bit more understandable.

boB

From jparkton at gmail.com  Mon Apr 29 17:15:26 2013
From: jparkton at gmail.com (Joseph Parkton)
Date: Mon, 29 Apr 2013 09:15:26 -0600
Subject: [Tutor] Codeacademy Problem
Message-ID: <CAGRB3imvfjqdntxpTe0HH344eOUNeKaEHf4m-X4x+2H4dW0G8g@mail.gmail.com>

I am working on a codeacademy problem and I am stuck. The instructions are
as follows:

INSTRUCTIONS

Below your existing code, write a function called trip_cost that takes two
inputs, city and days. cityshould be the city that you are going to visit
and days should be the number of days that you are staying.

Have your function return the *sum* of the rental_car_cost, hotel_cost, and
plane_ride_cost functions with their respective inputs.


my code so far looks like this:

def hotel_cost(nights):

    nights = nights * 140

    return nights



def plane_ride_cost(city):

    if city == 'Charlotte':

        return 183

    if city == 'Tampa':

        return 220

    if city == 'Pittsburgh':

        return 222

    if city == 'Los Angeles':

        return 475


def rental_car_cost(days):

    dailyCost = 40

    dailyCost = dailyCost * days

    if days >= 3:

        dailyCost = dailyCost - 20

    if days >= 7:

        dailyCost = dailyCost - 30

    return dailyCost



def trip_cost(city, days):

    totalCost = plane_trip_cost(city) + hotel_cost(nights) +
rental_car_cost(days)

    #And here is where I am stuck...


It is probably a simple answer but I don't know how to accomplish it. Any
help is appreciated.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130429/04389843/attachment.html>

From kwpolska at gmail.com  Mon Apr 29 17:20:08 2013
From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=)
Date: Mon, 29 Apr 2013 17:20:08 +0200
Subject: [Tutor] Codeacademy Problem
In-Reply-To: <CAGRB3imvfjqdntxpTe0HH344eOUNeKaEHf4m-X4x+2H4dW0G8g@mail.gmail.com>
References: <CAGRB3imvfjqdntxpTe0HH344eOUNeKaEHf4m-X4x+2H4dW0G8g@mail.gmail.com>
Message-ID: <CAMw+j7KFhe_6oyZ0kRu9nS3SrMFmDXHxy3xBJLfZCZA1fCJ_dw@mail.gmail.com>

On Mon, Apr 29, 2013 at 5:15 PM, Joseph Parkton <jparkton at gmail.com> wrote:
> I am working on a codeacademy problem and I am stuck. The instructions are
> as follows:
>
> INSTRUCTIONS
>
> Below your existing code, write a function called trip_cost that takes two
> inputs, city and days. cityshould be the city that you are going to visit
> and days should be the number of days that you are staying.
>
> Have your function return the sum of the rental_car_cost, hotel_cost, and
> plane_ride_cost functions with their respective inputs.
>
>
> my code so far looks like this:
>
> def hotel_cost(nights):
>
>     nights = nights * 140
>
>     return nights
>
>
>
> def plane_ride_cost(city):
>
>     if city == 'Charlotte':
>
>         return 183
>
>     if city == 'Tampa':
>
>         return 220
>
>     if city == 'Pittsburgh':
>
>         return 222
>
>     if city == 'Los Angeles':
>
>         return 475
>
>
> def rental_car_cost(days):
>
>     dailyCost = 40
>
>     dailyCost = dailyCost * days
>
>     if days >= 3:
>
>         dailyCost = dailyCost - 20
>
>     if days >= 7:
>
>         dailyCost = dailyCost - 30
>
>     return dailyCost
>
>
>
> def trip_cost(city, days):
>
>     totalCost = plane_trip_cost(city) + hotel_cost(nights) +
> rental_car_cost(days)
>
>     #And here is where I am stuck...
>
>
> It is probably a simple answer but I don't know how to accomplish it. Any
> help is appreciated.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>

Two options:
(a) replace `totalCost =` with `return`
-OR-
(b) add `return totalCost` under the equation.

You already used return before, so why didn?t you do it there?  Or was
this code auto-added by codecademy?
--
Kwpolska <http://kwpolska.tk> | GPG KEY: 5EAAEA16
stop html mail                | always bottom-post
http://asciiribbon.org        | http://caliburn.nl/topposting.html

From sacharook at gmail.com  Mon Apr 29 17:24:46 2013
From: sacharook at gmail.com (Sacha Rook)
Date: Mon, 29 Apr 2013 16:24:46 +0100
Subject: [Tutor] Codeacademy Problem
In-Reply-To: <CAGRB3imvfjqdntxpTe0HH344eOUNeKaEHf4m-X4x+2H4dW0G8g@mail.gmail.com>
References: <CAGRB3imvfjqdntxpTe0HH344eOUNeKaEHf4m-X4x+2H4dW0G8g@mail.gmail.com>
Message-ID: <CAE5dmQuEGVg0-mUSGUsRPzO6mgD_fnUoc=1SZV7bt-H7rOop8Q@mail.gmail.com>

Hi
Do you need to;

return totalCost in the function trip_cost

so when you call trip_cost(city, days) it gives you something back?

Hope it helps

S


On 29 April 2013 16:15, Joseph Parkton <jparkton at gmail.com> wrote:

> I am working on a codeacademy problem and I am stuck. The instructions are
> as follows:
>
> INSTRUCTIONS
>
> Below your existing code, write a function called trip_cost that takes
> two inputs, city and days. cityshould be the city that you are going to
> visit and days should be the number of days that you are staying.
>
> Have your function return the *sum* of the rental_car_cost, hotel_cost,
> and plane_ride_cost functions with their respective inputs.
>
>
> my code so far looks like this:
>
> def hotel_cost(nights):
>
>     nights = nights * 140
>
>     return nights
>
>
>
> def plane_ride_cost(city):
>
>     if city == 'Charlotte':
>
>         return 183
>
>     if city == 'Tampa':
>
>         return 220
>
>     if city == 'Pittsburgh':
>
>         return 222
>
>     if city == 'Los Angeles':
>
>         return 475
>
>
> def rental_car_cost(days):
>
>     dailyCost = 40
>
>     dailyCost = dailyCost * days
>
>     if days >= 3:
>
>         dailyCost = dailyCost - 20
>
>     if days >= 7:
>
>         dailyCost = dailyCost - 30
>
>     return dailyCost
>
>
>
> def trip_cost(city, days):
>
>     totalCost = plane_trip_cost(city) + hotel_cost(nights) +
> rental_car_cost(days)
>
>     #And here is where I am stuck...
>
>
> It is probably a simple answer but I don't know how to accomplish it. Any
> help is appreciated.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130429/743b8523/attachment-0001.html>

From oscar.j.benjamin at gmail.com  Mon Apr 29 17:27:50 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Mon, 29 Apr 2013 16:27:50 +0100
Subject: [Tutor] Associate decimal values with an integer range
In-Reply-To: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
References: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
Message-ID: <CAHVvXxS+0ZHJfcJGPQ7=J6aSr50UySL7NyzbyzX5m4=Wn6mOOw@mail.gmail.com>

On 29 April 2013 15:28, sparkle Plenty <sparkle.plenty12481632 at gmail.com> wrote:
> Hi, I need some hints on where to start solving this problem.
> I have to interpret a one-byte floating point number as a range between 0
> and 240.  This is for a gui that controls an amplifier.  I am getting a
> value such as 0.8367 from a fader control, and my Python is interpreting it
> as either a 0 or 1.  I need to define this number to Python as an integer
> value between 0 and 240.  I know that in hex I have the potential for
> numbers from 0 to 255 within my one byte of available space, and the value
> will be sent from gui to amp and back as a packed one-byte number.  I have
> looked at the math module and so far, I am still stuck.

You need to define the range of values that you will accept. If you
want the floating point numbers to map linearly to integers you can
then use:

byte = int(241 * float_value / max_float_value)

This will give a value between 0 and 240 inclusive for any positive
float_value that is less than max_float_value. The integer values will
be approximately proportional to the float values.

You may also want to check for overflow:

byte = min(byte, 240)

> Alas, business calc was a long time ago, and I never studied logarithms.  I
> expect the answer would be easier to find if I had more math.

Logarithms would be useful for a different (non-linear) type of
scaling. I can't tell you whether or not you want logarithmic scaling
since I'm not sure what the byte integer is needed for. If you did
want to use logarithmic scaling then you could do something like:

byte = int((241 / math.log(2)) * math.log(1 + float_value / max_float_value))


Oscar

From jparkton at gmail.com  Mon Apr 29 17:28:54 2013
From: jparkton at gmail.com (Joseph Parkton)
Date: Mon, 29 Apr 2013 09:28:54 -0600
Subject: [Tutor] Codeacademy Problem
In-Reply-To: <CAE5dmQuEGVg0-mUSGUsRPzO6mgD_fnUoc=1SZV7bt-H7rOop8Q@mail.gmail.com>
References: <CAGRB3imvfjqdntxpTe0HH344eOUNeKaEHf4m-X4x+2H4dW0G8g@mail.gmail.com>
	<CAE5dmQuEGVg0-mUSGUsRPzO6mgD_fnUoc=1SZV7bt-H7rOop8Q@mail.gmail.com>
Message-ID: <CAGRB3im8PeSH1iURMkQpt94fT9G5VV54bZVN69-dB_TjzeZR2w@mail.gmail.com>

I tried both suggestions from Chris and I get Oops, try again! Did you
create a function called trip_cost? Not really sure why



On Mon, Apr 29, 2013 at 9:24 AM, Sacha Rook <sacharook at gmail.com> wrote:

> Hi
> Do you need to;
>
> return totalCost in the function trip_cost
>
> so when you call trip_cost(city, days) it gives you something back?
>
> Hope it helps
>
> S
>
>
> On 29 April 2013 16:15, Joseph Parkton <jparkton at gmail.com> wrote:
>
>> I am working on a codeacademy problem and I am stuck. The instructions
>> are as follows:
>>
>> INSTRUCTIONS
>>
>> Below your existing code, write a function called trip_cost that takes
>> two inputs, city and days. cityshould be the city that you are going to
>> visit and days should be the number of days that you are staying.
>>
>> Have your function return the *sum* of the rental_car_cost, hotel_cost,
>> and plane_ride_cost functions with their respective inputs.
>>
>>
>> my code so far looks like this:
>>
>> def hotel_cost(nights):
>>
>>     nights = nights * 140
>>
>>     return nights
>>
>>
>>
>> def plane_ride_cost(city):
>>
>>     if city == 'Charlotte':
>>
>>         return 183
>>
>>     if city == 'Tampa':
>>
>>         return 220
>>
>>     if city == 'Pittsburgh':
>>
>>         return 222
>>
>>     if city == 'Los Angeles':
>>
>>         return 475
>>
>>
>> def rental_car_cost(days):
>>
>>     dailyCost = 40
>>
>>     dailyCost = dailyCost * days
>>
>>     if days >= 3:
>>
>>         dailyCost = dailyCost - 20
>>
>>     if days >= 7:
>>
>>         dailyCost = dailyCost - 30
>>
>>     return dailyCost
>>
>>
>>
>> def trip_cost(city, days):
>>
>>     totalCost = plane_trip_cost(city) + hotel_cost(nights) +
>> rental_car_cost(days)
>>
>>     #And here is where I am stuck...
>>
>>
>> It is probably a simple answer but I don't know how to accomplish it. Any
>> help is appreciated.
>>
>>
>> _______________________________________________
>> Tutor maillist  -  Tutor at python.org
>> To unsubscribe or change subscription options:
>> http://mail.python.org/mailman/listinfo/tutor
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130429/077346cb/attachment.html>

From steve at pearwood.info  Mon Apr 29 17:54:09 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 30 Apr 2013 01:54:09 +1000
Subject: [Tutor] Associate decimal values with an integer range
In-Reply-To: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
References: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
Message-ID: <517E97A1.3000402@pearwood.info>

On 30/04/13 00:28, sparkle Plenty wrote:
> Hi, I need some hints on where to start solving this problem.
> I have to interpret a one-byte floating point number as a range between 0
> and 240.  This is for a gui that controls an amplifier.  I am getting a
> value such as 0.8367 from a fader control, and my Python is interpreting it
> as either a 0 or 1.

You're going to need to be a bit more specific than that. In what way are you getting this value? What is happening that you think that Python is interpreting it as 0 or 1?

> I need to define this number to Python as an integer
> value between 0 and 240.


There are at least two ways of interpreting the numbers you quote, and both are equally plausible (or implausible, if you prefer).

A single byte can take 256 different values, starting with 0x00 and going to 0xFF in hexadecimal. If 0x00 -> 0.0, and 0xFF -> 240.0, then the smallest non-zero value is 0x01 -> 240/255 = 0.9411 (approx). So 0.8367 is an impossible value.

On the other hand, if we allow that 0x00 -> 0.0, and 0xFF -> 1.0, then 0.8367 is still an impossible value. The closest values would be either 0.8352 (0xD5) or 0.8392 (0xD6), both values also being approximate.

I'm going to guess that the second case is more likely, and if that's wrong, please say so.

My guess is that your fader control generates a number between 0.0 and 1.0 as a single byte. That means that there are 256 possible bytes, giving 256 possible floats:

0x00 -> 0/255 = 0.0
0x01 -> 1/255 = 0.00392156862745098
0x02 -> 2/255 = 0.00784313725490196
...
0xFE -> 254/255 = 0.996078431372549
0xFF -> 255/255 = 1.0


Whatever you use to get the value into Python, it comes in as a *byte*, not a float, so you see it as an integer between 0 and 255 inclusive. You want to scale that into an integer value between 0 and 240. So you convert the byte into a mini-float, then the mini-float into an int. Mathematically, you would use:

byte/255 * 240

But if you are using Python 2, you need to convince Python to use *floating point division* rather than integer division. (An unfortunate historical mistake, corrected in Python 3.)

So write this:

byte/255.0*240  # make sure you use 255.0 and not just 255

The result you get will not be an exact integer value, so you have to drop the fractional part some how. You have two choices, either truncating, or rounding. I think rounding is better in this situation, so do this:

int(round(byte/255.0*240))


which should give you a nice exact integer between 0 and 240 inclusive for every byte between 0 and 255.



Does this help?




-- 
Steven

From kwpolska at gmail.com  Mon Apr 29 18:01:09 2013
From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=)
Date: Mon, 29 Apr 2013 18:01:09 +0200
Subject: [Tutor] Codeacademy Problem
In-Reply-To: <CAGRB3im8PeSH1iURMkQpt94fT9G5VV54bZVN69-dB_TjzeZR2w@mail.gmail.com>
References: <CAGRB3imvfjqdntxpTe0HH344eOUNeKaEHf4m-X4x+2H4dW0G8g@mail.gmail.com>
	<CAE5dmQuEGVg0-mUSGUsRPzO6mgD_fnUoc=1SZV7bt-H7rOop8Q@mail.gmail.com>
	<CAGRB3im8PeSH1iURMkQpt94fT9G5VV54bZVN69-dB_TjzeZR2w@mail.gmail.com>
Message-ID: <CAMw+j7KSkv1a+8L4xHe+Lsr9tShw-YkUwK4jqa8w7A5+AejxtQ@mail.gmail.com>

On Mon, Apr 29, 2013 at 5:28 PM, Joseph Parkton <jparkton at gmail.com> wrote:
> I tried both suggestions from Chris and I get Oops, try again! Did you
> create a function called trip_cost? Not really sure why

Your problem is: codecademy is dumb and its errors are, too.

>>> def trip_cost(city, days):
...     totalCost = plane_trip_cost(city) + hotel_cost(nights) +
rental_car_cost(days)

There isn?t a ?nights? parameter in your function, and you try to use
it for hotel_cost().  Replace it with days.  And perform one of the
variants, ending up with:

def trip_cost(city, days):
    return plane_trip_cost(city) + hotel_cost(days) + rental_car_cost(days)

--
Kwpolska <http://kwpolska.tk> | GPG KEY: 5EAAEA16
stop html mail                | always bottom-post
http://asciiribbon.org        | http://caliburn.nl/topposting.html

From alan.gauld at btinternet.com  Mon Apr 29 18:16:58 2013
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 29 Apr 2013 17:16:58 +0100
Subject: [Tutor] Associate decimal values with an integer range
In-Reply-To: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
References: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
Message-ID: <klm6dm$s2p$1@ger.gmane.org>

On 29/04/13 15:28, sparkle Plenty wrote:
> Hi, I need some hints on where to start solving this problem.
> I have to interpret a one-byte floating point number

I'm curious, what does a one byte floating point number look like?
I've never come across such a beast, the smallest FP representation I've 
come across is 16 bits or two bytes. But that wasn't in
Python...

> a value such as 0.8367 from a fader control, and my Python is
> interpreting it as either a 0 or 1.

It would help if we could see your python, otherwise we
have to guess...

> for numbers from 0 to 255 within my one byte
> ...and the value will be sent from gui to amp and back as
 > a packed one-byte number.

What does 'packed' mean in this context?
Are you using the struct module or something else or are you meaning 
that you will somehow apply a compression technique? If so, what?

A bit confused...

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


From jparkton at gmail.com  Mon Apr 29 18:31:19 2013
From: jparkton at gmail.com (Joseph Parkton)
Date: Mon, 29 Apr 2013 10:31:19 -0600
Subject: [Tutor] Codeacademy Problem
In-Reply-To: <CAMw+j7KSkv1a+8L4xHe+Lsr9tShw-YkUwK4jqa8w7A5+AejxtQ@mail.gmail.com>
References: <CAGRB3imvfjqdntxpTe0HH344eOUNeKaEHf4m-X4x+2H4dW0G8g@mail.gmail.com>
	<CAE5dmQuEGVg0-mUSGUsRPzO6mgD_fnUoc=1SZV7bt-H7rOop8Q@mail.gmail.com>
	<CAGRB3im8PeSH1iURMkQpt94fT9G5VV54bZVN69-dB_TjzeZR2w@mail.gmail.com>
	<CAMw+j7KSkv1a+8L4xHe+Lsr9tShw-YkUwK4jqa8w7A5+AejxtQ@mail.gmail.com>
Message-ID: <CAGRB3ikTaS_XuUhXwb3zjU2DVg17ngiSgRn8DoOqDCONPAOyow@mail.gmail.com>

Yupp I totally agree on the errors. I finally had to change the

    def hotel_cost(nights):
        nights = nights * 140
        return nights

to

    def hotel_cost(nights):
    return hotel_cost(nights) * 140

for it to work. Strange errors but decent exercises for beginners.


On Mon, Apr 29, 2013 at 10:01 AM, Chris ?Kwpolska? Warrick <
kwpolska at gmail.com> wrote:

> On Mon, Apr 29, 2013 at 5:28 PM, Joseph Parkton <jparkton at gmail.com>
> wrote:
> > I tried both suggestions from Chris and I get Oops, try again! Did you
> > create a function called trip_cost? Not really sure why
>
> Your problem is: codecademy is dumb and its errors are, too.
>
> >>> def trip_cost(city, days):
> ...     totalCost = plane_trip_cost(city) + hotel_cost(nights) +
> rental_car_cost(days)
>
> There isn?t a ?nights? parameter in your function, and you try to use
> it for hotel_cost().  Replace it with days.  And perform one of the
> variants, ending up with:
>
> def trip_cost(city, days):
>     return plane_trip_cost(city) + hotel_cost(days) + rental_car_cost(days)
>
> --
> Kwpolska <http://kwpolska.tk> | GPG KEY: 5EAAEA16
> stop html mail                | always bottom-post
> http://asciiribbon.org        | http://caliburn.nl/topposting.html
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130429/c661cbd9/attachment.html>

From robertvstepp at gmail.com  Mon Apr 29 20:04:33 2013
From: robertvstepp at gmail.com (boB Stepp)
Date: Mon, 29 Apr 2013 13:04:33 -0500
Subject: [Tutor] Long post: How to design a Python program to generate
 GUI elements in a proprietary scripting language.
In-Reply-To: <klldag$riv$1@ger.gmane.org>
References: <CANDiX9JOOyqDy6BnkQfhKM5caT4YNf22m1MZn5s2Spgib66dXQ@mail.gmail.com>
	<klk43h$ntq$1@ger.gmane.org>
	<CANDiX9+KJy=BsYYd2_rmDBpzuR32ksJMeEFcCu4MyOsbwz4qjQ@mail.gmail.com>
	<klldag$riv$1@ger.gmane.org>
Message-ID: <CANDiX9+bU95MUv=+QYrE7tSbsY2d13CYD0UvN84txnArD4bscg@mail.gmail.com>

On Mon, Apr 29, 2013 at 4:08 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
> On 29/04/13 03:57, boB Stepp wrote:
>

[Major snip]

>
>> Unfortunately in most instances the window would have to be generated
>> at runtime.
>
>
> The whole window? Or just a panel within it?
> If its only for display could you use formatted text to display the plan
> data? Or is there user interaction with the dynamic data?
> Formatting text is a lot easier than dynamically building a
> GUI in a crippled scripting language! But only if you aren't interacting
> with it!
>

The first time such a script would be run, the entire window would
have to be generated. But if the user wished to rerun certain scripts,
it might be possible to do what you suggest. But this would not work
with all of them.

Alan, bear in mind that each script that I write tends to be rather
unique and rather dissimilar to earlier scripting. And as I learn more
of the hidden syntax of the Pinnacle HotScripting language and
learn/remember better programming practices, my scripting evolves
(There is no documentation other than what some ambitious users have
cobbled together.) As a dosimetrist, I typically imagine a way that
would make my planning life much easier and save me lots of time.
Also, I am constantly on the look for ways to automate common planning
processes in order to increase standardization and reduce the chances
of an uncaught error. When my work allows me time for programming,
then I attempt to implement my ideas.
Once my colleagues hear about something they like then I adapt these
scripts to their individual needs. Normally no one asks me to script
anything, though that has very recently started to change. I am mostly
self-directed in these endeavors. You'd think I would make things
easier on myself!
>
>> program I have just written. It takes about 30 seconds, plus or minus,
>> to populate all of the fields in the displayed window and make the
>> necessary comparisons. But for the planning dosimetrist to manually
>> generate this data and do the comparisons manually can take most of 30
>> minutes at times, while wondering if he had made any mistakes.
>
>
> Yes, but once they get used to your program they will forget that and just
> notice how long they have to wait for the GUI! Its the nature of users...
>

How true! If nothing else, it annoys me, so I will eventually figure
out ways to improve performance.

> I think you need to maximise commonality here. Try to define a common
> structure for the GUIs and isolate the dynamic areas to a minimal area -
> preferably a single panel within the GUI. You can then statically create the
> outer framework using the kind of config template idea I first suggested
> then insert into the output of that the dynamic elements
> just where they are needed.
>

This is surely doable for the outer framework.

For the dynamically generated areas if the script would be run more
than once, there is a possibility that I just now recalled. The
Pinnacle scripting language allows for the creation of dependencies.
For instance, if I were storing in one of the window's fields the
maximum dose that a particular region of interest receives, say the
heart, then if I successfully created such a dependency it should
update that field in my window. In these types of scripts I could
theoretically leave the window open (maximized or minimized) and any
data fields that I create dependencies for should refresh to the new
values upon the planner changing his plan.

> But at this point we go beyond abstractions and need real use cases and data
> samples and work flows to be able to give any more sensible advice.

For sure. You and Steven have given much helpful information. I now
need to determine how to best apply these thoughts to my particular
programming problems. I especially need to improve my last script that
led to my OP. I have been asked if it would be too much trouble to add
more tabular data to make comparisons to and add it to the window. And
another of our centers has hinted that they would like their
customized version of the program. Unfortunately they use almost
totally different terminology for their ROIs. And the most unfortunate
thing of all is that I was so focused on making the GUI that I did not
give any thought to maintaining and updating my code! Horrors!! So I
am wanting to totally redesign this program anyway. So if I can
separate the GUI stuff and the tabular data from the bulk of the code,
this would be greatly beneficial to my future happiness!

And I do want to start making the switch to Python from Perl at work
now that it is finally available to me due to the recent hardware and
software upgrades. So I am sure that more questions will develop!

Thanks!
boB

From davea at davea.name  Mon Apr 29 20:32:42 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 29 Apr 2013 14:32:42 -0400
Subject: [Tutor] Codeacademy Problem
In-Reply-To: <CAGRB3ikTaS_XuUhXwb3zjU2DVg17ngiSgRn8DoOqDCONPAOyow@mail.gmail.com>
References: <CAGRB3imvfjqdntxpTe0HH344eOUNeKaEHf4m-X4x+2H4dW0G8g@mail.gmail.com>
	<CAE5dmQuEGVg0-mUSGUsRPzO6mgD_fnUoc=1SZV7bt-H7rOop8Q@mail.gmail.com>
	<CAGRB3im8PeSH1iURMkQpt94fT9G5VV54bZVN69-dB_TjzeZR2w@mail.gmail.com>
	<CAMw+j7KSkv1a+8L4xHe+Lsr9tShw-YkUwK4jqa8w7A5+AejxtQ@mail.gmail.com>
	<CAGRB3ikTaS_XuUhXwb3zjU2DVg17ngiSgRn8DoOqDCONPAOyow@mail.gmail.com>
Message-ID: <517EBCCA.5070603@davea.name>

On 04/29/2013 12:31 PM, Joseph Parkton wrote:
> Yupp I totally agree on the errors. I finally had to change the
>
>      def hotel_cost(nights):
>          nights = nights * 140
>          return nights
>
> to
>
>      def hotel_cost(nights):
>      return hotel_cost(nights) * 140
>
> for it to work. Strange errors but decent exercises for beginners.
>

That certainly doesn't work.  Either you get an indentation error, or 
once you fix that, you get infinite recursion.

Have you ever tried running this code on your own machine, or are you 
stuck only with the strange error messages of codeacademy?

-- 
DaveA

From emile at fenx.com  Mon Apr 29 21:33:52 2013
From: emile at fenx.com (Emile van Sebille)
Date: Mon, 29 Apr 2013 12:33:52 -0700
Subject: [Tutor] does anyone know a good module for automation
In-Reply-To: <CA+QG++FbKt0zZS0xQ25B8R3H2tGSuo5aYLeGOrgduD5MjQHmqA@mail.gmail.com>
References: <CA+QG++FWWArsjCFfcSr87RtAJbLgE9dgN5WR8pPXvev7YErAkg@mail.gmail.com>
	<kkvbs4$ibo$1@ger.gmane.org>
	<CA+QG++FbKt0zZS0xQ25B8R3H2tGSuo5aYLeGOrgduD5MjQHmqA@mail.gmail.com>
Message-ID: <klmhuq$4vm$1@ger.gmane.org>

I recently automated a scheduled task to retrieve content from an https 
site that uses javascript for site interaction using iMacros, ahk and 
the related firefox extension.  Not a python solution, but it got the 
job done.

Emile


On 4/26/2013 8:28 AM, Frank Schiro wrote:
> Pywinauto is not working with this application that opens from the
> internet via javascript. Its not in a browser, its a complete
> application thats not installed on the computer just installed on the
> internet.
> Pywinauto sees the window...but cant find any controls and does not
> recognize menu items, neither does its helper program swapy. Does anyone
> know how I could automate a program like this ? I guess something about
> it is not the same as normal installed on your own computer programs...
> Also I dont like sikuli, because I hate its interpreter.
>
> On Sat, Apr 20, 2013 at 8:28 PM, Alan Gauld <alan.gauld at btinternet.com
> <mailto:alan.gauld at btinternet.com>> wrote:
>
>     On 20/04/13 23:07, Frank Schiro wrote:
>
>
>         Unless you think pywinauto would work in a game envoirnment ? I
>         think it
>         might but have not tried it because no games on my pc... I just
>         know it
>         didnt work for internet explorer.
>
>
>     I don't know pywinauto but the lowest common denominator on Windows
>     is the Win32 API and the Windows messages. You can use either ctypes
>     or pythonwin to access those and/or create your own to simulate
>     button presses and mouse clicks etc. Doing that you can automate
>     anything in windows, but its a non trivial, error prone and
>     frustrating exercise so its better to get a higher level library if
>     you can.
>
>
>     --
>     Alan G
>     Author of the Learn to Program web site
>     http://www.alan-g.me.uk/
>
>     _________________________________________________
>     Tutor maillist  - Tutor at python.org <mailto:Tutor at python.org>
>     To unsubscribe or change subscription options:
>     http://mail.python.org/__mailman/listinfo/tutor
>     <http://mail.python.org/mailman/listinfo/tutor>
>
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>



From eryksun at gmail.com  Mon Apr 29 23:03:07 2013
From: eryksun at gmail.com (eryksun)
Date: Mon, 29 Apr 2013 17:03:07 -0400
Subject: [Tutor] Associate decimal values with an integer range
In-Reply-To: <klm6dm$s2p$1@ger.gmane.org>
References: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
	<klm6dm$s2p$1@ger.gmane.org>
Message-ID: <CACL+1au9rGSmryjvMVoZZgk8_CBCLPsTMgndEk5Kcmv-8_xsWg@mail.gmail.com>

On Mon, Apr 29, 2013 at 12:16 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>> I have to interpret a one-byte floating point number
>
> I'm curious, what does a one byte floating point number look like?
> I've never come across such a beast, the smallest FP representation I've
> come across is 16 bits or two bytes. But that wasn't in Python...

For a maximum value of 240.0, an 8-bit floating point (as opposed to
fixed point) format could use 1 sign bit, 4 exponent bits, and 3
significand bits (plus 1 implicit bit). Emax is 7, so the maximum
positive normal would be (2 - 2**-3) * 2**7 == 240.0. Emin is -6, so
the minimum positive normal would be 2**-6. There's approximately 1
decimal digit of precision, i.e. floor(log10(2**4)).

There are 224 normal values in the range [-240.0, 240.0]. Of those, 96
have a magnitude less than 1.0, and 128 have a magnitude in the range
[1.0, 240.0]. There's also +/- zero, +/- infinity, 14 subnormal
values, and 14 NaN (quiet and signaling) values:

      +0: 0 0000 000
      -0: 1 0000 000
    +inf: 0 1111 000
    -inf: 1 1111 000
     sub: x 0000 non-zero
     nan: x 1111 non-zero

From davea at davea.name  Tue Apr 30 00:00:20 2013
From: davea at davea.name (Dave Angel)
Date: Mon, 29 Apr 2013 18:00:20 -0400
Subject: [Tutor] Associate decimal values with an integer range
In-Reply-To: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
References: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
Message-ID: <517EED74.5070009@davea.name>

On 04/29/2013 10:28 AM, sparkle Plenty wrote:
> Hi, I need some hints on where to start solving this problem.
> I have to interpret a one-byte floating point number as a range between 0
> and 240.  This is for a gui that controls an amplifier.  I am getting a
> value such as 0.8367 from a fader control, and my Python is interpreting it
> as either a 0 or 1.  I need to define this number to Python as an integer
> value between 0 and 240.  I know that in hex I have the potential for
> numbers from 0 to 255 within my one byte of available space, and the value
> will be sent from gui to amp and back as a packed one-byte number.  I have
> looked at the math module and so far, I am still stuck.
>

Are you serious?  There are so many ambiguities and contradictions in 
your paragraph that each reply so far is entirely different.

Do you have one device that you're sending to and receiving from?  Is 
that device called both an amp and a fader?  Is it designed already, and 
does it already have an interface that talks to your machine?  Do specs 
exist for that interface?  If so, be more specific.

At the other end, you have a GUI that's displaying something, and 
interacting somehow with a user.  Perhaps that's not written yet, but do 
you have plans for it?  Are you going to mimic the fader on the amp with 
a slider on the GUI?  Or what?

One byte floating point?  Nonsense.  While it can be defined (see 
eryksun's response, which tracks the IEEE standard quite well), it 
wouldn't store enough precision to be used for anything but a toy.

Shall we continue making up possibilities, or is there a spec you can 
tell us about?  Do you get a one-byte unsigned int value from the 
device, and some library you implied ("Python is interpreting it as...") 
is converting it to a float?  Is that float value meaningful, or are you 
trying to fix its misinterpretation?

When you mention logarithms, are you vaguely implying that you are 
converting from DB scale (to be used in the GUI) to a linear scale (to 
send as one byte value)?  That would be a lousy spec (see second 
paragraph above).

Draw a better picture, and you'll get more meaningful responses.

-- 
DaveA

From oscar.j.benjamin at gmail.com  Tue Apr 30 01:33:15 2013
From: oscar.j.benjamin at gmail.com (Oscar Benjamin)
Date: Tue, 30 Apr 2013 00:33:15 +0100
Subject: [Tutor] Associate decimal values with an integer range
In-Reply-To: <CACL+1au9rGSmryjvMVoZZgk8_CBCLPsTMgndEk5Kcmv-8_xsWg@mail.gmail.com>
References: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
	<klm6dm$s2p$1@ger.gmane.org>
	<CACL+1au9rGSmryjvMVoZZgk8_CBCLPsTMgndEk5Kcmv-8_xsWg@mail.gmail.com>
Message-ID: <CAHVvXxTWKmyzyQZ9zCRQE5gdnUyuE0xdrSQUS-e0JhRj-qee-Q@mail.gmail.com>

On 29 April 2013 22:03, eryksun <eryksun at gmail.com> wrote:
> On Mon, Apr 29, 2013 at 12:16 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>>> I have to interpret a one-byte floating point number
>>
>> I'm curious, what does a one byte floating point number look like?
>> I've never come across such a beast, the smallest FP representation I've
>> come across is 16 bits or two bytes. But that wasn't in Python...
>
> For a maximum value of 240.0, an 8-bit floating point (as opposed to
> fixed point) format could use 1 sign bit, 4 exponent bits, and 3
> significand bits (plus 1 implicit bit). Emax is 7, so the maximum
> positive normal would be (2 - 2**-3) * 2**7 == 240.0. Emin is -6, so
> the minimum positive normal would be 2**-6. There's approximately 1
> decimal digit of precision, i.e. floor(log10(2**4)).
>
> There are 224 normal values in the range [-240.0, 240.0]. Of those, 96
> have a magnitude less than 1.0, and 128 have a magnitude in the range
> [1.0, 240.0]. There's also +/- zero, +/- infinity, 14 subnormal
> values, and 14 NaN (quiet and signaling) values:
>
>       +0: 0 0000 000
>       -0: 1 0000 000
>     +inf: 0 1111 000
>     -inf: 1 1111 000
>      sub: x 0000 non-zero
>      nan: x 1111 non-zero

Brilliant. I thought you were just making this up but here
http://mrob.com/pub/math/floatformats.html
I find that 8 bit floating point with values up to 240 is listed as a
floating point format. The link describes it as "Used in university
courses" so I guess it's not intended to be a practical format.


Oscar

From steve at pearwood.info  Tue Apr 30 04:05:48 2013
From: steve at pearwood.info (Steven D'Aprano)
Date: Tue, 30 Apr 2013 12:05:48 +1000
Subject: [Tutor] Associate decimal values with an integer range
In-Reply-To: <517EED74.5070009@davea.name>
References: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
	<517EED74.5070009@davea.name>
Message-ID: <517F26FC.4050403@pearwood.info>

On 30/04/13 08:00, Dave Angel wrote:

> One byte floating point?  Nonsense.  While it can be defined (see eryksun's response, which tracks the IEEE standard quite well), it wouldn't store enough precision to be used for anything but a toy.

Minifloats have their uses. Probably the best use is teaching.

http://en.wikipedia.org/wiki/Minifloat

Oh, by the way, my earlier reply missed the point, since it described a one-byte FIXED point number, not floating point. Sorry about that.



-- 
Steven

From ajin25 at gmail.com  Tue Apr 30 09:20:02 2013
From: ajin25 at gmail.com (Ajin Abraham)
Date: Tue, 30 Apr 2013 12:50:02 +0530
Subject: [Tutor] Loop not executing.
Message-ID: <CAKHNSoxfh7OtAg3JE8dX+bctHajHOQF+hi3VmDY4LPGQTcEqoA@mail.gmail.com>

Hi,
   I am using a python snippet that will send some data after the data
length reaches a particular length. So it is supposed to loop and
periodically sends the data to an email. i am using smtplib to send
mail. i will attach the code snippet.

def email():
    global data
    if len(data)>50:
        ts = datetime.datetime.now()
        SERVER = "smtp.gmail.com" #Specify Server Here
        PORT = "587" #Specify Port Here
        USER="ajin at gmail.com"#Specify Username Here
        PASS="mypassword"#Specify Password Here
        FROM = USER#From address is taken from username
        TO = ["ajin at gmail.com"] #Specify to address.Use comma if more
than one to address is needed.
        SUBJECT = " Data at: "+str(ts)
        MESSAGE = data
        # formating final email body
        message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, MESSAGE)
        server = smtplib.SMTP()
        server.connect(SERVER,PORT)
        server.starttls()
        server.login(USER,PASS)
        server.sendmail(FROM, TO, message)
        server.quit()
        print 'Log Send!!'
        data=''
    return True

This function email() is called periodically and is in a loop. the
program just execute once and keep running in the loop without exiting
but the data is mailed only once. i will also attache the Traceback
details:
Traceback (most recent call last):
  File "c:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in Keybo
ardSwitch
    return func(event)
  File "key2.py", line 132, in keypressed
    email()
  File "key2.py", line 83, in email
    server = smtplib.SMTP()
  File "c:\Python27\lib\smtplib.py", line 258, in __init__
    fqdn = socket.getfqdn()
  File "c:\Python27\lib\socket.py", line 142, in getfqdn
    for name in aliases:
TypeError: an integer is required
Log Send!!


I believe someone can help on this matter.

Regards,
Ajin Abraham

Information Security Enthusiast.
www.ajinabraham.com | www.defconkerala.org
www.keralacyberforce.in | +91-9633325997

From ramit.prasad at jpmorgan.com  Tue Apr 30 17:48:43 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 30 Apr 2013 15:48:43 +0000
Subject: [Tutor] Tutor Digest, Vol 110, Issue 117
In-Reply-To: <CALRAYNVxyeGM=NYsEbMsYQ7v387PrDdhV30=rnTULLFQs_5=_g@mail.gmail.com>
References: <mailman.9.1367143201.19870.tutor@python.org>
	<CALRAYNVxyeGM=NYsEbMsYQ7v387PrDdhV30=rnTULLFQs_5=_g@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF4741836517D@SCACMX008.exchad.jpmchase.net>

Jim Mooney wrote:
> 
> > In py3.x, iteritems was replaced by .items()
> 
> Interesting, since iteritems was in my book, which was "updated" for
> Py33. I guess the moral is you shouldn't trust an author 100% ;')  I
> must admit, iteritems did seem awkward and annoying so I'm glad it's
> dropped.
> 
> Jim

Technically, .items() was dropped and .iteritems() was renamed .items()


~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.  

From __peter__ at web.de  Tue Apr 30 19:44:28 2013
From: __peter__ at web.de (Peter Otten)
Date: Tue, 30 Apr 2013 19:44:28 +0200
Subject: [Tutor] dict.iteritems() in Python3, was Re: Tutor Digest, Vol 110,
	Issue 117
References: <mailman.9.1367143201.19870.tutor@python.org>
	<CALRAYNVxyeGM=NYsEbMsYQ7v387PrDdhV30=rnTULLFQs_5=_g@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741836517D@SCACMX008.exchad.jpmchase.net>
Message-ID: <klovto$1ci$1@ger.gmane.org>

Prasad, Ramit wrote:

> Jim Mooney wrote:
>> 
>> > In py3.x, iteritems was replaced by .items()
>> 
>> Interesting, since iteritems was in my book, which was "updated" for
>> Py33. I guess the moral is you shouldn't trust an author 100% ;')  I
>> must admit, iteritems did seem awkward and annoying so I'm glad it's
>> dropped.
>> 
>> Jim
> 
> Technically, .items() was dropped and .iteritems() was renamed .items()

One way to verify that is to run 

$ cat tmp.py
d = dict(a=1, b=2)
x = d.items()
y = d.iteritems()
z = d.viewitems()

through the 2to3 tool:

$ 2to3 tmp.py 2> /dev/null
--- tmp.py      (original)
+++ tmp.py      (refactored)
@@ -1,5 +1,5 @@
 d = dict(a=1, b=2)
-x = d.items()
-y = d.iteritems()
-z = d.viewitems()
+x = list(d.items())
+y = iter(d.items())
+z = d.items()

So

d.items() --> list(d.items())
d.iteritems() --> iter(d.items())
d.viewitems() --> d.items()

In short: items() and iteritems() were both dropped, and viewitems() was 
renamed items().



From sparkle.plenty12481632 at gmail.com  Tue Apr 30 20:13:39 2013
From: sparkle.plenty12481632 at gmail.com (sparkle Plenty)
Date: Tue, 30 Apr 2013 14:13:39 -0400
Subject: [Tutor] Associate decimal values with an integer range
In-Reply-To: <CAHVvXxS+0ZHJfcJGPQ7=J6aSr50UySL7NyzbyzX5m4=Wn6mOOw@mail.gmail.com>
References: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
	<CAHVvXxS+0ZHJfcJGPQ7=J6aSr50UySL7NyzbyzX5m4=Wn6mOOw@mail.gmail.com>
Message-ID: <CABeS=HZaXy=GurNmjVQheCOaK7rvau-+vrjq5uq=ixwt-8nJtw@mail.gmail.com>

On Mon, Apr 29, 2013 at 11:27 AM, Oscar Benjamin <oscar.j.benjamin at gmail.com
> wrote:

> On 29 April 2013 15:28, sparkle Plenty <sparkle.plenty12481632 at gmail.com>
> wrote:
> > Hi, I need some hints on where to start solving this problem.
> > I have to interpret a one-byte floating point number as a range between 0
> > and 240.  This is for a gui that controls an amplifier.  I am getting a
> > value such as 0.8367 from a fader control, and my Python is interpreting
> it
> > as either a 0 or 1.  I need to define this number to Python as an integer
> > value between 0 and 240.  I know that in hex I have the potential for
> > numbers from 0 to 255 within my one byte of available space, and the
> value
> > will be sent from gui to amp and back as a packed one-byte number.  I
> have
> > looked at the math module and so far, I am still stuck.
>
> You need to define the range of values that you will accept. If you
> want the floating point numbers to map linearly to integers you can
> then use:
>
> byte = int(241 * float_value / max_float_value)
>
> This will give a value between 0 and 240 inclusive for any positive
> float_value that is less than max_float_value. The integer values will
> be approximately proportional to the float values.
>
> You may also want to check for overflow:
>
> byte = min(byte, 240)
>
> > Alas, business calc was a long time ago, and I never studied logarithms.
>  I
> > expect the answer would be easier to find if I had more math.
>
> Logarithms would be useful for a different (non-linear) type of
> scaling. I can't tell you whether or not you want logarithmic scaling
> since I'm not sure what the byte integer is needed for. If you did
> want to use logarithmic scaling then you could do something like:
>
> byte = int((241 / math.log(2)) * math.log(1 + float_value /
> max_float_value))
>
>
> Oscar
>

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130430/a8925ada/attachment.html>

From sparkle.plenty12481632 at gmail.com  Tue Apr 30 20:29:36 2013
From: sparkle.plenty12481632 at gmail.com (sparkle Plenty)
Date: Tue, 30 Apr 2013 14:29:36 -0400
Subject: [Tutor] Associate decimal values with an integer range
In-Reply-To: <CABeS=HZaXy=GurNmjVQheCOaK7rvau-+vrjq5uq=ixwt-8nJtw@mail.gmail.com>
References: <CABeS=HataEm6uJxM2-0d2=ZkZQWYWyxF9np_QmmjD-PqF-Bccw@mail.gmail.com>
	<CAHVvXxS+0ZHJfcJGPQ7=J6aSr50UySL7NyzbyzX5m4=Wn6mOOw@mail.gmail.com>
	<CABeS=HZaXy=GurNmjVQheCOaK7rvau-+vrjq5uq=ixwt-8nJtw@mail.gmail.com>
Message-ID: <CABeS=HYW1-=9SdqttMkjk_R+LyMEPXFd9w7zW-hpDLKER7W0eA@mail.gmail.com>

On Tue, Apr 30, 2013 at 2:13 PM, sparkle Plenty <
sparkle.plenty12481632 at gmail.com> wrote:

>
>
> On Mon, Apr 29, 2013 at 11:27 AM, Oscar Benjamin <
> oscar.j.benjamin at gmail.com> wrote:
>
>> On 29 April 2013 15:28, sparkle Plenty <sparkle.plenty12481632 at gmail.com>
>> wrote:
>> > Hi, I need some hints on where to start solving this problem.
>> > I have to interpret a one-byte floating point number as a range between
>> 0
>> > and 240.  This is for a gui that controls an amplifier.  I am getting a
>> > value such as 0.8367 from a fader control, and my Python is
>> interpreting it
>> > as either a 0 or 1.  I need to define this number to Python as an
>> integer
>> > value between 0 and 240.  I know that in hex I have the potential for
>> > numbers from 0 to 255 within my one byte of available space, and the
>> value
>> > will be sent from gui to amp and back as a packed one-byte number.  I
>> have
>> > looked at the math module and so far, I am still stuck.
>>
>> You need to define the range of values that you will accept. If you
>> want the floating point numbers to map linearly to integers you can
>> then use:
>>
>> byte = int(241 * float_value / max_float_value)
>>
>> This will give a value between 0 and 240 inclusive for any positive
>> float_value that is less than max_float_value. The integer values will
>> be approximately proportional to the float values.
>>
>> You may also want to check for overflow:
>>
>> byte = min(byte, 240)
>>
>> > Alas, business calc was a long time ago, and I never studied
>> logarithms.  I
>> > expect the answer would be easier to find if I had more math.
>>
>> Logarithms would be useful for a different (non-linear) type of
>> scaling. I can't tell you whether or not you want logarithmic scaling
>> since I'm not sure what the byte integer is needed for. If you did
>> want to use logarithmic scaling then you could do something like:
>>
>> byte = int((241 / math.log(2)) * math.log(1 + float_value /
>> max_float_value))
>>
>>
>> Oscar
>>
>
> Thanks!
>

Sorry for the ambiguity.  The device is an amplifier, a fader is a control
on the amplifier, the input is from a gui, and arrives as a floating
point number, and the output goes to the amplifier.  Some of the faders
take a range from -40mH to 20mH, and others have different ranges.  I
receive a floating point number from the gui and need to represent it in
one packed hex byte between x00 and xff.  I have solved the problem of how
to adjust the values, now I have to figure out how to translate it into
Python.

Thanks again for all your help.  I appreciate it.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130430/2166a9fd/attachment.html>

From ramit.prasad at jpmorgan.com  Tue Apr 30 21:24:00 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 30 Apr 2013 19:24:00 +0000
Subject: [Tutor] Loop not executing.
In-Reply-To: <CAKHNSoxfh7OtAg3JE8dX+bctHajHOQF+hi3VmDY4LPGQTcEqoA@mail.gmail.com>
References: <CAKHNSoxfh7OtAg3JE8dX+bctHajHOQF+hi3VmDY4LPGQTcEqoA@mail.gmail.com>
Message-ID: <5B80DD153D7D744689F57F4FB69AF47418365C37@SCACMX008.exchad.jpmchase.net>

Ajin Abraham wrote:
> Hi,
>    I am using a python snippet that will send some data after the data
> length reaches a particular length. So it is supposed to loop and
> periodically sends the data to an email. i am using smtplib to send
> mail. i will attach the code snippet.
> 
> def email():
>     global data
>     if len(data)>50:
>         ts = datetime.datetime.now()
>         SERVER = "smtp.gmail.com" #Specify Server Here
>         PORT = "587" #Specify Port Here
>         USER="ajin at gmail.com"#Specify Username Here
>         PASS="mypassword"#Specify Password Here
>         FROM = USER#From address is taken from username
>         TO = ["ajin at gmail.com"] #Specify to address.Use comma if more
> than one to address is needed.
>         SUBJECT = " Data at: "+str(ts)
>         MESSAGE = data
>         # formating final email body
>         message = """\
> From: %s
> To: %s
> Subject: %s
> 
> %s
> """ % (FROM, ", ".join(TO), SUBJECT, MESSAGE)
>         server = smtplib.SMTP()
>         server.connect(SERVER,PORT)
>         server.starttls()
>         server.login(USER,PASS)
>         server.sendmail(FROM, TO, message)
>         server.quit()
>         print 'Log Send!!'
>         data=''
>     return True
> 
> This function email() is called periodically and is in a loop. the
> program just execute once and keep running in the loop without exiting
> but the data is mailed only once. i will also attache the Traceback
> details:
> Traceback (most recent call last):
>   File "c:\Python27\lib\site-packages\pyHook\HookManager.py", line 351, in Keybo
> ardSwitch
>     return func(event)
>   File "key2.py", line 132, in keypressed
>     email()
>   File "key2.py", line 83, in email
>     server = smtplib.SMTP()
>   File "c:\Python27\lib\smtplib.py", line 258, in __init__
>     fqdn = socket.getfqdn()
>   File "c:\Python27\lib\socket.py", line 142, in getfqdn
>     for name in aliases:
> TypeError: an integer is required
> Log Send!!
> 

Have you looked at the documentation?

Help on method __init__ in module smtplib:
__init__(self, host='', port=0, local_hostname=None, timeout=<object object>) unbound smtplib.SMTP method
    Initialize a new instance.
    
    If specified, `host' is the name of the remote host to which to
    connect.  If specified, `port' specifies the port to which to connect.
    By default, smtplib.SMTP_PORT is used.  An SMTPConnectError is raised
    if the specified `host' doesn't respond correctly.  If specified,
    `local_hostname` is used as the FQDN of the local host.  By default,
    the local hostname is found using socket.getfqdn().



Well that explains the usage of socket.getfqdn() from your trace.


Help on function getfqdn in module socket:
getfqdn(name='')
    Get fully qualified domain name from name.
    
    An empty argument is interpreted as meaning the local host.
    
    First the hostname returned by gethostbyaddr() is checked, then
    possibly existing aliases. In case no FQDN is available, hostname
    from gethostname() is returned.


Hmm, not illuminating anything for me, but you can likely skip all 
this by passing the FQDN (fully qualified domain name) directly to 
smtplib.SMTP( local_hostname='blah.blah.blah').


> 
> I believe someone can help on this matter.
> 
> Regards,
> Ajin Abraham
> 
> Information Security Enthusiast.
> www.ajinabraham.com | www.defconkerala.org
> www.keralacyberforce.in | +91-9633325997
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
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.  

From ramit.prasad at jpmorgan.com  Tue Apr 30 21:13:22 2013
From: ramit.prasad at jpmorgan.com (Prasad, Ramit)
Date: Tue, 30 Apr 2013 19:13:22 +0000
Subject: [Tutor] dict.iteritems() in Python3, was Re: Tutor Digest,
 Vol 110, Issue 117
In-Reply-To: <klovto$1ci$1@ger.gmane.org>
References: <mailman.9.1367143201.19870.tutor@python.org>
	<CALRAYNVxyeGM=NYsEbMsYQ7v387PrDdhV30=rnTULLFQs_5=_g@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741836517D@SCACMX008.exchad.jpmchase.net>
	<klovto$1ci$1@ger.gmane.org>
Message-ID: <5B80DD153D7D744689F57F4FB69AF47418365BE8@SCACMX008.exchad.jpmchase.net>

Peter Otten wrote:
> Prasad, Ramit wrote:
> 
> > Jim Mooney wrote:
> >>
> >> > In py3.x, iteritems was replaced by .items()
> >>
> >> Interesting, since iteritems was in my book, which was "updated" for
> >> Py33. I guess the moral is you shouldn't trust an author 100% ;')  I
> >> must admit, iteritems did seem awkward and annoying so I'm glad it's
> >> dropped.
> >>
> >> Jim
> >
> > Technically, .items() was dropped and .iteritems() was renamed .items()
> 
> One way to verify that is to run
> 
> $ cat tmp.py
> d = dict(a=1, b=2)
> x = d.items()
> y = d.iteritems()
> z = d.viewitems()
> 
> through the 2to3 tool:
> 
> $ 2to3 tmp.py 2> /dev/null
> --- tmp.py      (original)
> +++ tmp.py      (refactored)
> @@ -1,5 +1,5 @@
>  d = dict(a=1, b=2)
> -x = d.items()
> -y = d.iteritems()
> -z = d.viewitems()
> +x = list(d.items())
> +y = iter(d.items())
> +z = d.items()
> 
> So
> 
> d.items() --> list(d.items())
> d.iteritems() --> iter(d.items())
> d.viewitems() --> d.items()
> 
> In short: items() and iteritems() were both dropped, and viewitems() was
> renamed items().
> 

Thanks for the excellent (and well laid out) correction Peter!


~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.  

From eryksun at gmail.com  Tue Apr 30 23:42:13 2013
From: eryksun at gmail.com (eryksun)
Date: Tue, 30 Apr 2013 17:42:13 -0400
Subject: [Tutor] dict.iteritems() in Python3, was Re: Tutor Digest,
 Vol 110, Issue 117
In-Reply-To: <klovto$1ci$1@ger.gmane.org>
References: <mailman.9.1367143201.19870.tutor@python.org>
	<CALRAYNVxyeGM=NYsEbMsYQ7v387PrDdhV30=rnTULLFQs_5=_g@mail.gmail.com>
	<5B80DD153D7D744689F57F4FB69AF4741836517D@SCACMX008.exchad.jpmchase.net>
	<klovto$1ci$1@ger.gmane.org>
Message-ID: <CACL+1avX+v6Hh4daCofQUDfT6jzz2CVwK-Raavfx2ynA4KmgQw@mail.gmail.com>

On Tue, Apr 30, 2013 at 1:44 PM, Peter Otten <__peter__ at web.de> wrote:
>
> d.items() --> list(d.items())
> d.iteritems() --> iter(d.items())
> d.viewitems() --> d.items()
>
> In short: items() and iteritems() were both dropped, and viewitems() was
> renamed items().

Following on from this, the iterator types weren't dropped, but
iteritems, iterkeys, itervalues were removed from the mapping API.
iter(d.items()) returns an item iterator similar to the old
d.iteritems(), but the name was corrected from the weird 'dictionary-'
prefix to simply 'dict_'. Also, even though it's instantiated by a
view, the 3.x iterator references the dict directly, not the view.