From dieter at handshake.de Wed Oct 1 01:55:54 2014 From: dieter at handshake.de (dieter) Date: Wed, 01 Oct 2014 07:55:54 +0200 Subject: SNI support in python 2.7 for Locust load tests References: Message-ID: <87tx3opc45.fsf@handshake.de> Reddy writes: > ... > I'm trying to use locust (http://locust.io/) to run load test of one site we're developing. Everything was running nice and smooth until we switch the servers to use SNI. SNI is not officially supported in python 2.7.5 A recent post in this list regarding missing SNI support in Python 2.x got as a suggestion to use the "backports.ssl" package on PyPI. From mathematisch at gmail.com Wed Oct 1 03:01:22 2014 From: mathematisch at gmail.com (math math) Date: Wed, 1 Oct 2014 00:01:22 -0700 (PDT) Subject: how to parse standard algebraic notation In-Reply-To: References: <4a7f3e7a-ba4d-405e-a078-937bf861fcd8@googlegroups.com> Message-ID: On Tuesday, 30 September 2014 23:15:24 UTC+2, Gary Herron wrote: > On 09/30/2014 01:53 PM, math math wrote: > > > Hi, > > > > > > I am trying to learn Python while solving exercises. > > > > > > I want to basically write a program that inputs a polynomial in standard algebraic notation and outputs its derivative. > > > > > > I know that I need to get the exponent somehow, but I am not sure how to accomplish this in python (3.3) > > > > > > Do you have any ideas or suggestions? I don't want to use existing modules as this is meant to be a didactic experience. > > > > > > Regards > > > > This depends on things you have not yet told us. > > > > In particular -- what "standard algebraic notation"? For x-squared: > > x**2 ? or perhaps x^2 ? or something else like some Unicode > > characters or HTML to get a small superscript 2 above an x. > > > > Once you give an example of what your input looks like, we can start > > hashing out how to read it. > > > > Gary Herron > > > > -- > > Dr. Gary Herron > > Department of Computer Science > > DigiPen Institute of Technology > > (425) 895-4418 Thanks Gary (and Chris), I should have sent a sample expression indeed. What would be a good starting strategy for writing a program to take the derivative of a polynomial expression, such as this below?: "x**3 + x**2 + x + 1" I am a bit confused about my overall strategy. Should one be writing a parser class to split the input on operators and then on the double asterisks? Are there more clever ways? Or is this something one should solve using mathematical formulas instead of parsing the characters? I just wonder how a seasoned Pythonian would go about a problem like this without using a ready-made derivative function from some module. Regards, Felix From zondo42 at gmail.com Wed Oct 1 03:15:52 2014 From: zondo42 at gmail.com (Glenn Hutchings) Date: Wed, 1 Oct 2014 00:15:52 -0700 (PDT) Subject: Python code in presentations In-Reply-To: References: <1617366671.8129227.1412075768865.JavaMail.root@sequans.com> Message-ID: On Tuesday, 30 September 2014 12:51:00 UTC+1, Jean-Michel Pichavant wrote: > I'm currently writing a presentation to help my co-workers ramp up on new features of our tool (written in python (2.7)). > > I have some difficulties presenting code in an efficient way (with some basic syntax highlights). I need to be catchy about the code I'm presenting otherwise the presentation will fail and I would be better saying to my co-workers "RTFM", cause there is a manual. A good option is to use reStructuredText and the rst2s5 converter (http://docutils.sourceforge.net/docs/user/slide-shows.html). It can do syntax highlighting of python, and produces a slide show you display in a browser. An example of what you can produce is at http://farmdev.com/talks/unicode. Glenn From breamoreboy at yahoo.co.uk Wed Oct 1 03:35:34 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 01 Oct 2014 08:35:34 +0100 Subject: how to parse standard algebraic notation In-Reply-To: References: <4a7f3e7a-ba4d-405e-a078-937bf861fcd8@googlegroups.com> Message-ID: On 01/10/2014 08:01, math math wrote: [mega-snip] You are far more likely to get answers if you access this list via https://mail.python.org/mailman/listinfo/python-list or read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing and single line paragraphs, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From wxjmfauth at gmail.com Wed Oct 1 04:08:57 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 1 Oct 2014 01:08:57 -0700 (PDT) Subject: how to parse standard algebraic notation In-Reply-To: <4a7f3e7a-ba4d-405e-a078-937bf861fcd8@googlegroups.com> References: <4a7f3e7a-ba4d-405e-a078-937bf861fcd8@googlegroups.com> Message-ID: <8c6cf42c-9a0f-4efe-8411-f3bea2aa35b9@googlegroups.com> Le mardi 30 septembre 2014 22:53:22 UTC+2, math math a ?crit?: > Hi, > > > > I am trying to learn Python while solving exercises. > > > > I want to basically write a program that inputs a polynomial in standard algebraic notation and outputs its derivative. > > > > I know that I need to get the exponent somehow, but I am not sure how to accomplish this in python (3.3) > > > > Do you have any ideas or suggestions? I don't want to use existing modules as this is meant to be a didactic experience. > > I would - stick with a single algebric notation - stick with a "variable" - toy with string manipulations Suggestion: - split your polynomial in monomials - extract the coefficients - recompose the derivative Eg, Transform f(x) = azx**3 + 3x**2 +2y -x(3-2) into f'(x) = 3azx**2 + 6x - (3-2) trap: 3*2 -> 6! Simpler way f(x) = a*z*x**3 + 3*x**2 +2*y -x*(3-2) into f'(x) = 3*a*z*x**2 + 3*2*x - (3-2) jmf From mathematisch at gmail.com Wed Oct 1 04:14:56 2014 From: mathematisch at gmail.com (math math) Date: Wed, 1 Oct 2014 01:14:56 -0700 (PDT) Subject: Thoughts on python classes to represent an ebook reader Message-ID: <8cbce703-968f-4474-a013-063d7844c22a@googlegroups.com> Hi, I hope there are people here with strong OOP experience. Which classes would an object-oriented python programmer create for the design of a e-book reader for example? I am not really interested in the code, just the OOP classes that would come to one's mind for a task like this. It should allow users to buy new e-books, view their list of purchased books and read the books. I have made an attempt of class diagram here "http://imgur.com/9TR2Tlm" but I would be really glad to hear other opinions. I have not used any inheritance for example. I didn't know exactly where it would be handy and I also dont know if these classes are theoretically a good basis at all... Thanks a lot for comments/feedback. Felix From roland.hedberg at umu.se Wed Oct 1 04:22:54 2014 From: roland.hedberg at umu.se (Roland Hedberg) Date: Wed, 1 Oct 2014 10:22:54 +0200 Subject: Weird SSL problem In-Reply-To: References: Message-ID: <3E6F8524-BD7D-4224-8BBE-69674558D2DE@adm.umu.se> 30 sep 2014 kl. 00:55 skrev Ned Deily : > In article , > Roland Hedberg wrote: > >> Hi! >> >> I?m trying to access >> https://stsadweb.one.microsoft.com/adfs/.well-known/openid-configuration >> >> Doing it the simplest way I get the following: >> >>>>> import urllib >>>>> f = >>>>> urllib.urlopen("https://stsadweb.one.microsoft.com/adfs/.well-known/openid >>>>> -configuration") >> Traceback (most recent call last): >> File "", line 1, in >> File >> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", >> line 87, in urlopen >> return opener.open(url) >> File >> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", >> line 208, in open >> return getattr(self, name)(url) >> File >> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", >> line 437, in open_https >> h.endheaders(data) >> File >> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py" >> , line 969, in endheaders >> self._send_output(message_body) >> File >> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py" >> , line 829, in _send_output >> self.send(msg) >> File >> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py" >> , line 791, in send >> self.connect() >> File >> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py" >> , line 1176, in connect >> self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file) >> File >> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", >> line 387, in wrap_socket >> ciphers=ciphers) >> File >> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", >> line 143, in __init__ >> self.do_handshake() >> File >> "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", >> line 305, in do_handshake >> self._sslobj.do_handshake() >> IOError: [Errno socket error] [Errno 54] Connection reset by peer >>>>> import ssl >>>>> ssl.OPENSSL_VERSION >> ?OpenSSL 0.9.8za 5 Jun 2014' >> >> Now, using Safari, or curl for that matter, from the same machine works >> without a hitch. >> >> The URL above is also the only URL I?ve encountered this problem with. >> >> Anyone got an idea ? > > I believe the problem is that the connection is protected by a > multi-hostname server certificate and Python 2's urllib (and underlying > httplib and ssl modules) do not support SNI extensions to TLS. The > request above works fine with Python 3 (which has supported client-side > SNI since Python 3.2). See http://bugs.python.org/issue5639 for more > discussion of the matter. If Python 3 is not an option for you, the > requests package available via PyPI should help. You?re absolutely correct in that it?s a SNI problem. Python 3 is not an option and I was already using requests obviously missing something. Ah, had to install some extra libraries. ? Roland ?Being able to think like a child is an important attribute of being an adult? - Eddie Izzard From rosuav at gmail.com Wed Oct 1 04:38:35 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 1 Oct 2014 18:38:35 +1000 Subject: how to parse standard algebraic notation In-Reply-To: References: <4a7f3e7a-ba4d-405e-a078-937bf861fcd8@googlegroups.com> Message-ID: On Wed, Oct 1, 2014 at 5:01 PM, math math wrote: > What would be a good starting strategy for writing a program to take the derivative of a polynomial expression, such as this below?: > "x**3 + x**2 + x + 1" > > I am a bit confused about my overall strategy. Should one be writing a parser class to split the input on operators and then on the double asterisks? Are there more clever ways? Or is this something one should solve using mathematical formulas instead of parsing the characters? > > I just wonder how a seasoned Pythonian would go about a problem like this without using a ready-made derivative function from some module. Well, let's see. Are you planning to use exact Python syntax everywhere? For instance, will you use asterisks for multiplication ("5*x**3 + 2*x**2 - 5*x + 1")? If so, you could make use of the ast.parse() module to do some of the work for you. Otherwise, you'll have to start by writing up a grammar: exactly what is and isn't allowed? Then write a parser, and see how things go from there. ChrisA From wolfgang.maier at biologie.uni-freiburg.de Wed Oct 1 04:48:17 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Wed, 01 Oct 2014 10:48:17 +0200 Subject: Thoughts on python classes to represent an ebook reader In-Reply-To: <8cbce703-968f-4474-a013-063d7844c22a@googlegroups.com> References: <8cbce703-968f-4474-a013-063d7844c22a@googlegroups.com> Message-ID: <542BBFD1.3050209@biologie.uni-freiburg.de> On 01.10.2014 10:14, math math wrote: > Hi, > > I hope there are people here with strong OOP experience. > > Which classes would an object-oriented python programmer create for the design of a e-book reader for example? I am not really interested in the code, just the OOP classes that would come to one's mind for a task like this. > > It should allow users to buy new e-books, view their list of purchased books and read the books. > > I have made an attempt of class diagram here "http://imgur.com/9TR2Tlm" but I would be really glad to hear other opinions. I have not used any inheritance for example. I didn't know exactly where it would be handy and I also dont know if these classes are theoretically a good basis at all... > > Thanks a lot for comments/feedback. > Felix > As it happens, the very popular Calibre ebook software is written in Python. So, I guess, getting (https://github.com/kovidgoyal/calibre) and looking at its source code should give you a good start. Wolfgang From reddy at poczta.fm Wed Oct 1 05:27:47 2014 From: reddy at poczta.fm (Reddy) Date: Wed, 01 Oct 2014 11:27:47 +0200 Subject: SNI support in python 2.7 for Locust load tests In-Reply-To: <87tx3opc45.fsf@handshake.de> References: <87tx3opc45.fsf@handshake.de> Message-ID: Hi, > Reddy writes: > > ... > > I'm trying to use locust (http://locust.io/) to run load test of one site we're developing. Everything was running nice and smooth until we switch the servers to use SNI. SNI is not officially supported in python 2.7.5 > you have two options: > > Python 2.7.9 implements PEP 466 "Network Security Enhancements for > Python 2.7.x" including TLS 1.1, 1.2 and SNI support. 2.7.9 will be > released shortly. You could try the 2.7 branch from hg.python.org. > > Use PyOpenSSL instead of Python's ssl module. It supports SNI, too. > A recent post in this list regarding missing SNI support in Python 2.x > got as a suggestion to use the "backports.ssl" package on PyPI. Thanks Christian and Dieter for your prompt responses! I tried yesterday with Python built from https://hg.python.org/cpython/archive/9b4673d7b046.tar.gz. I also do use pyOpenSSL as described at http://stackoverflow.com/a/19477363 so I used pip to install pyOpenSSL, ndg-httpsclient and pyasn1 as well as patched locust startup file with the following: from urllib3.contrib import pyopenssl pyopenssl.inject_into_urllib3() I also tried adding the following: from functools import partial ssl.wrap_socket = partial(ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) Finally, I've just tried with: /usr/local/bin/pip2.7 install backports.ssl and patching the lucust file with: import backports.ssl as ssl import backports.ssl.monkey as monkey import requests monkey.patch() I've also added verify=False to my locust test scripts to disable certificate verification according to http://docs.locust.io/en/latest/api.html ...And I still get exactly the same error: [2014-09-30 14:19:41,793] ip-x-x-x-x/ERROR/stderr: File "build/bdist.linux-x86_64/egg/OpenSSL/SSL.py", line 977, in sendall [2014-09-30 14:19:41,793] ip-x-x-x-x/ERROR/stderr: File "build/bdist.linux-x86_64/egg/OpenSSL/SSL.py", line 849, in _raise_ssl_error [2014-09-30 14:19:41,794] ip-x-x-x-x/ERROR/stderr: OpenSSL.SSL [2014-09-30 14:19:41,794] ip-x-x-x-x/ERROR/stderr: . [2014-09-30 14:19:41,794] ip-x-x-x-x/ERROR/stderr: WantWriteError Now I'm starting to think it's something else than SNI, but all those scripts were working nice before and the only change done was turning on the SNI on tested servers... Any idea what my actually cause this WantWriteError? From feliphil at gmx.net Wed Oct 1 05:42:34 2014 From: feliphil at gmx.net (Wolfgang Keller) Date: Wed, 1 Oct 2014 11:42:34 +0200 Subject: Python code in presentations References: <1617366671.8129227.1412075768865.JavaMail.root@sequans.com> Message-ID: <20141001114234.d86083aeed01ea7ce99608fb@gmx.net> > Right now the method I'm using is write the code in notepad++, use a > plugin (NppExport) to copy paste code into powerpoint. After using it > a little bit, I'm really not satisfied with this method, it's > expensive and all this copy paste stuff is driving me crazy. Not to > mention that the syntax highlight from notepads renders like crap in > powerpoint. > > I wonder if some people in this list who have successfully presented > python code have some tips about doing the proper way. Ned's > presentations for pycons are to me one example of successful code > presentation: > - the layout is simple > - the code and code output are clearly identified > - a line of code can be highlighted while presenting LyX and Beamer. Sincerely, Wolfgang From cl at isbd.net Wed Oct 1 05:58:36 2014 From: cl at isbd.net (cl at isbd.net) Date: Wed, 1 Oct 2014 10:58:36 +0100 Subject: How to show a dictionary sorted on a value within its data? Message-ID: I have a dictionary as follows:- { u'StarterAmps1': Row(id=4, ain=u'AIN3', name=u'StarterAmps1', conv=6834.374834509803, Description=u'Starter Amps'), u'LeisureVolts': Row(id=1, ain=u'AIN0', name=u'LeisureVolts', conv=29.01374215995874, Description=u'Leisure Volts'), u'RudderPos': Row(id=6, ain=u'AIN5', name=u'RudderPos', conv=0.028125, Description=u'Rudder Position'), u'xx': Row(id=7, ain=u'AIN6', name=u'xx', conv=0.028125, Description=u''), u'LeisureAmps1': Row(id=3, ain=u'AIN2', name=u'LeisureAmps1', conv=32.727273081945, Description=u'Leisure Amps'), u'StarterVolts': Row(id=2, ain=u'AIN1', name=u'StarterVolts', conv=28.94469628911757, Description=u'Starter Volts') } I want to output a menu to a user comprising some parts of the dictionary (ain and Description) sorted by ain. Is there some incantation of sorted() that will do what I want? I can't quite fathom out the 'key=' parameter needed to sort it by the tuple item. Maybe I need a cmp= ? E.g. I want to do something like:- for meas in sorted(adc.cfg, key=???): print(adc.cfg[meas].ain, adc.cfg[meas].Description) What's needed in the ??? -- Chris Green ? From alfred at 54.org Wed Oct 1 06:13:51 2014 From: alfred at 54.org (Alfred Morgan) Date: Wed, 1 Oct 2014 03:13:51 -0700 (PDT) Subject: JSON-encoding very long iterators In-Reply-To: References: <4232c92a-101c-4a1b-89b2-e80d67ef7bc6@googlegroups.com> Message-ID: <209e604c-1a18-43ff-9358-12fb784d3d4c@googlegroups.com> On Monday, September 29, 2014 7:10:18 PM UTC-7, Ian wrote: > This would cause things that aren't lists to be encoded as lists. > Sometimes that may be desirable, but in general if e.g. a file object > sneaks its way into your JSON encode call, it is more likely correct > to raise an error than to silently encode the file as if it were a > list of strings. So it should not be the default behavior. That said, > it sounds like it could be made easier to enable streaming from > iterators as an option for those cases where it's desired. I added a stream flag (off by default) and also added file streaming (thanks for the idea). https://github.com/Zectbumo/cpython/compare/2.7 What do you think now? From __peter__ at web.de Wed Oct 1 06:24:46 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 01 Oct 2014 12:24:46 +0200 Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: cl at isbd.net wrote: > I have a dictionary as follows:- > > { > u'StarterAmps1': Row(id=4, ain=u'AIN3', name=u'StarterAmps1', > conv=6834.374834509803, Description=u'Starter Amps'), u'LeisureVolts': > Row(id=1, ain=u'AIN0', name=u'LeisureVolts', conv=29.01374215995874, > Description=u'Leisure Volts'), u'RudderPos': Row(id=6, ain=u'AIN5', > name=u'RudderPos', conv=0.028125, Description=u'Rudder Position'), u'xx': > Row(id=7, ain=u'AIN6', name=u'xx', conv=0.028125, Description=u''), > u'LeisureAmps1': Row(id=3, ain=u'AIN2', name=u'LeisureAmps1', > conv=32.727273081945, Description=u'Leisure Amps'), u'StarterVolts': > Row(id=2, ain=u'AIN1', name=u'StarterVolts', conv=28.94469628911757, > Description=u'Starter Volts') } > > I want to output a menu to a user comprising some parts of the > dictionary (ain and Description) sorted by ain. > > Is there some incantation of sorted() that will do what I want? I > can't quite fathom out the 'key=' parameter needed to sort it by the > tuple item. Maybe I need a cmp= ? > > E.g. I want to do something like:- > > for meas in sorted(adc.cfg, key=???): > print(adc.cfg[meas].ain, adc.cfg[meas].Description) > > What's needed in the ??? for meas in sorted(adc.cfg, key=lambda key: adc.cfg[key].ain): print(adc.cfg[meas].ain, adc.cfg[meas].Description) or simpler for row in sorted(adc.cfg.values(), key=operator.attrgetter("ain")) print(row.ain, row.Description) or even for row in sorted( map(operator.attrgetter("ain", "Description"), adc.cfg.values())): print(*row) From breamoreboy at yahoo.co.uk Wed Oct 1 06:27:04 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 01 Oct 2014 11:27:04 +0100 Subject: How to show a dictionary sorted on a value within its data? In-Reply-To: References: Message-ID: On 01/10/2014 10:58, cl at isbd.net wrote: > I have a dictionary as follows:- > > { > u'StarterAmps1': Row(id=4, ain=u'AIN3', name=u'StarterAmps1', conv=6834.374834509803, Description=u'Starter Amps'), > u'LeisureVolts': Row(id=1, ain=u'AIN0', name=u'LeisureVolts', conv=29.01374215995874, Description=u'Leisure Volts'), > u'RudderPos': Row(id=6, ain=u'AIN5', name=u'RudderPos', conv=0.028125, Description=u'Rudder Position'), > u'xx': Row(id=7, ain=u'AIN6', name=u'xx', conv=0.028125, Description=u''), > u'LeisureAmps1': Row(id=3, ain=u'AIN2', name=u'LeisureAmps1', conv=32.727273081945, Description=u'Leisure Amps'), > u'StarterVolts': Row(id=2, ain=u'AIN1', name=u'StarterVolts', conv=28.94469628911757, Description=u'Starter Volts') > } > > I want to output a menu to a user comprising some parts of the > dictionary (ain and Description) sorted by ain. > > Is there some incantation of sorted() that will do what I want? I > can't quite fathom out the 'key=' parameter needed to sort it by the > tuple item. Maybe I need a cmp= ? > > E.g. I want to do something like:- > > for meas in sorted(adc.cfg, key=???): > print(adc.cfg[meas].ain, adc.cfg[meas].Description) > > What's needed in the ??? > IIRC one method involves using itemgetter from https://docs.python.org/3/library/operator.html#module-operator -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From joel.goldstick at gmail.com Wed Oct 1 06:37:51 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 1 Oct 2014 06:37:51 -0400 Subject: How to show a dictionary sorted on a value within its data? In-Reply-To: References: Message-ID: On Wed, Oct 1, 2014 at 5:58 AM, wrote: > I have a dictionary as follows:- > > { > u'StarterAmps1': Row(id=4, ain=u'AIN3', name=u'StarterAmps1', conv=6834.374834509803, Description=u'Starter Amps'), > u'LeisureVolts': Row(id=1, ain=u'AIN0', name=u'LeisureVolts', conv=29.01374215995874, Description=u'Leisure Volts'), > u'RudderPos': Row(id=6, ain=u'AIN5', name=u'RudderPos', conv=0.028125, Description=u'Rudder Position'), > u'xx': Row(id=7, ain=u'AIN6', name=u'xx', conv=0.028125, Description=u''), > u'LeisureAmps1': Row(id=3, ain=u'AIN2', name=u'LeisureAmps1', conv=32.727273081945, Description=u'Leisure Amps'), > u'StarterVolts': Row(id=2, ain=u'AIN1', name=u'StarterVolts', conv=28.94469628911757, Description=u'Starter Volts') > } Is Row a function? Or do you have a key with a tuple as the value? > > I want to output a menu to a user comprising some parts of the > dictionary (ain and Description) sorted by ain. > > Is there some incantation of sorted() that will do what I want? I > can't quite fathom out the 'key=' parameter needed to sort it by the > tuple item. Maybe I need a cmp= ? > > E.g. I want to do something like:- > > for meas in sorted(adc.cfg, key=???): > print(adc.cfg[meas].ain, adc.cfg[meas].Description) > > What's needed in the ??? > > -- > Chris Green > ? You might read here: http://www.pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/ > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From cl at isbd.net Wed Oct 1 06:45:32 2014 From: cl at isbd.net (cl at isbd.net) Date: Wed, 1 Oct 2014 11:45:32 +0100 Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: Peter Otten <__peter__ at web.de> wrote: > cl at isbd.net wrote: > > > I have a dictionary as follows:- > > > > { > > u'StarterAmps1': Row(id=4, ain=u'AIN3', name=u'StarterAmps1', > > conv=6834.374834509803, Description=u'Starter Amps'), u'LeisureVolts': > > Row(id=1, ain=u'AIN0', name=u'LeisureVolts', conv=29.01374215995874, > > Description=u'Leisure Volts'), u'RudderPos': Row(id=6, ain=u'AIN5', > > name=u'RudderPos', conv=0.028125, Description=u'Rudder Position'), u'xx': > > Row(id=7, ain=u'AIN6', name=u'xx', conv=0.028125, Description=u''), > > u'LeisureAmps1': Row(id=3, ain=u'AIN2', name=u'LeisureAmps1', > > conv=32.727273081945, Description=u'Leisure Amps'), u'StarterVolts': > > Row(id=2, ain=u'AIN1', name=u'StarterVolts', conv=28.94469628911757, > > Description=u'Starter Volts') } > > > > I want to output a menu to a user comprising some parts of the > > dictionary (ain and Description) sorted by ain. > > > > Is there some incantation of sorted() that will do what I want? I > > can't quite fathom out the 'key=' parameter needed to sort it by the > > tuple item. Maybe I need a cmp= ? > > > > E.g. I want to do something like:- > > > > for meas in sorted(adc.cfg, key=???): > > print(adc.cfg[meas].ain, adc.cfg[meas].Description) > > > > What's needed in the ??? > > for meas in sorted(adc.cfg, key=lambda key: adc.cfg[key].ain): > print(adc.cfg[meas].ain, adc.cfg[meas].Description) > Brilliant, worked perfectly, thank you. The bit I didn't understamd was that 'lambda' bit, but I just looked it up and I'm a bit clearer now. > or simpler > > for row in sorted(adc.cfg.values(), key=operator.attrgetter("ain")) > print(row.ain, row.Description) > I tried this, I got:- Traceback (most recent call last): File "/home/chris/bin/calibrate.py", line 24, in for meas in sorted(adc.cfg.values, key=operator.attrgetter("ain")): NameError: name 'operator' is not defined I must admit that it's the bits like 'operator' in the parameters that I can't really understand where they come from. > or even > > for row in sorted( > map(operator.attrgetter("ain", "Description"), adc.cfg.values())): > print(*row) > -- Chris Green ? From joel.goldstick at gmail.com Wed Oct 1 06:56:57 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 1 Oct 2014 06:56:57 -0400 Subject: How to show a dictionary sorted on a value within its data? In-Reply-To: References: Message-ID: On Wed, Oct 1, 2014 at 6:45 AM, wrote: > Peter Otten <__peter__ at web.de> wrote: >> cl at isbd.net wrote: >> >> > I have a dictionary as follows:- >> > >> > { >> > u'StarterAmps1': Row(id=4, ain=u'AIN3', name=u'StarterAmps1', >> > conv=6834.374834509803, Description=u'Starter Amps'), u'LeisureVolts': >> > Row(id=1, ain=u'AIN0', name=u'LeisureVolts', conv=29.01374215995874, >> > Description=u'Leisure Volts'), u'RudderPos': Row(id=6, ain=u'AIN5', >> > name=u'RudderPos', conv=0.028125, Description=u'Rudder Position'), u'xx': >> > Row(id=7, ain=u'AIN6', name=u'xx', conv=0.028125, Description=u''), >> > u'LeisureAmps1': Row(id=3, ain=u'AIN2', name=u'LeisureAmps1', >> > conv=32.727273081945, Description=u'Leisure Amps'), u'StarterVolts': >> > Row(id=2, ain=u'AIN1', name=u'StarterVolts', conv=28.94469628911757, >> > Description=u'Starter Volts') } >> > >> > I want to output a menu to a user comprising some parts of the >> > dictionary (ain and Description) sorted by ain. >> > >> > Is there some incantation of sorted() that will do what I want? I >> > can't quite fathom out the 'key=' parameter needed to sort it by the >> > tuple item. Maybe I need a cmp= ? >> > >> > E.g. I want to do something like:- >> > >> > for meas in sorted(adc.cfg, key=???): >> > print(adc.cfg[meas].ain, adc.cfg[meas].Description) >> > >> > What's needed in the ??? >> >> for meas in sorted(adc.cfg, key=lambda key: adc.cfg[key].ain): >> print(adc.cfg[meas].ain, adc.cfg[meas].Description) >> > Brilliant, worked perfectly, thank you. The bit I didn't understamd was > that 'lambda' bit, but I just looked it up and I'm a bit clearer now. > >> or simpler >> >> for row in sorted(adc.cfg.values(), key=operator.attrgetter("ain")) >> print(row.ain, row.Description) >> > I tried this, I got:- > > Traceback (most recent call last): > File "/home/chris/bin/calibrate.py", line 24, in > for meas in sorted(adc.cfg.values, > key=operator.attrgetter("ain")): > NameError: name 'operator' is not defined > I must admit that it's the bits like 'operator' in the parameters that > I can't really understand where they come from. > operator is a module. See https://docs.python.org/2/library/operator.html#module-operator > >> or even >> >> for row in sorted( >> map(operator.attrgetter("ain", "Description"), adc.cfg.values())): >> print(*row) >> > > -- > Chris Green > ? > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From __peter__ at web.de Wed Oct 1 07:12:37 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 01 Oct 2014 13:12:37 +0200 Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: cl at isbd.net wrote: > Peter Otten <__peter__ at web.de> wrote: >> cl at isbd.net wrote: >> >> > I have a dictionary as follows:- >> > >> > { >> > u'StarterAmps1': Row(id=4, ain=u'AIN3', name=u'StarterAmps1', >> > conv=6834.374834509803, Description=u'Starter Amps'), u'LeisureVolts': >> > Row(id=1, ain=u'AIN0', name=u'LeisureVolts', conv=29.01374215995874, >> > Description=u'Leisure Volts'), u'RudderPos': Row(id=6, ain=u'AIN5', >> > name=u'RudderPos', conv=0.028125, Description=u'Rudder Position'), >> > u'xx': Row(id=7, ain=u'AIN6', name=u'xx', conv=0.028125, >> > Description=u''), u'LeisureAmps1': Row(id=3, ain=u'AIN2', >> > name=u'LeisureAmps1', conv=32.727273081945, Description=u'Leisure >> > Amps'), u'StarterVolts': Row(id=2, ain=u'AIN1', name=u'StarterVolts', >> > conv=28.94469628911757, Description=u'Starter Volts') } >> > >> > I want to output a menu to a user comprising some parts of the >> > dictionary (ain and Description) sorted by ain. >> > >> > Is there some incantation of sorted() that will do what I want? I >> > can't quite fathom out the 'key=' parameter needed to sort it by the >> > tuple item. Maybe I need a cmp= ? >> > >> > E.g. I want to do something like:- >> > >> > for meas in sorted(adc.cfg, key=???): >> > print(adc.cfg[meas].ain, adc.cfg[meas].Description) >> > >> > What's needed in the ??? >> >> for meas in sorted(adc.cfg, key=lambda key: adc.cfg[key].ain): >> print(adc.cfg[meas].ain, adc.cfg[meas].Description) >> > Brilliant, worked perfectly, thank you. The bit I didn't understamd was > that 'lambda' bit, but I just looked it up and I'm a bit clearer now. `lambda` is just a fancy way to define a function inline. With a normal `def` it would be def get_ain(key): return adc.cfg[key].ain or meas in sorted(adc.cfg, key=get_ain): print(adc.cfg[meas].ain, adc.cfg[meas].Description) > >> or simpler >> >> for row in sorted(adc.cfg.values(), key=operator.attrgetter("ain")) >> print(row.ain, row.Description) >> > I tried this, I got:- > > Traceback (most recent call last): > File "/home/chris/bin/calibrate.py", line 24, in > for meas in sorted(adc.cfg.values, > key=operator.attrgetter("ain")): > NameError: name 'operator' is not defined > I must admit that it's the bits like 'operator' in the parameters that > I can't really understand where they come from. As Joel says, operator is a module. To use it add import operator at the beginning of your module. To check if you've really understood the lambda you can try to replace the operator.attrgetter("ain") in >> for row in sorted(adc.cfg.values(), key=operator.attrgetter("ain")): with for row in sorted(adc.cfg.values(), key=lambda ...): >> or even >> >> for row in sorted( >> map(operator.attrgetter("ain", "Description"), >> adc.cfg.values())): >> print(*row) From reddy at poczta.fm Wed Oct 1 07:30:14 2014 From: reddy at poczta.fm (Reddy) Date: Wed, 01 Oct 2014 13:30:14 +0200 Subject: SNI support in python 2.7 for Locust load tests In-Reply-To: References: <87tx3opc45.fsf@handshake.de> Message-ID: Hi, > > Reddy writes: > > > ... > > > I'm trying to use locust (http://locust.io/) to run load test of one site we're developing. Everything was running nice and smooth until we switch the servers to use SNI. SNI is not officially supported in python 2.7.5 > > > you have two options: > > > > Python 2.7.9 implements PEP 466 "Network Security Enhancements for > > Python 2.7.x" including TLS 1.1, 1.2 and SNI support. 2.7.9 will be > > released shortly. You could try the 2.7 branch from hg.python.org. > > > > Use PyOpenSSL instead of Python's ssl module. It supports SNI, too. > > > A recent post in this list regarding missing SNI support in Python 2.x > > got as a suggestion to use the "backports.ssl" package on PyPI. > > Thanks Christian and Dieter for your prompt responses! > I tried yesterday with Python built from https://hg.python.org/cpython/archive/9b4673d7b046.tar.gz. I also do use pyOpenSSL as described at http://stackoverflow.com/a/19477363 so I used pip to install pyOpenSSL, ndg-httpsclient and pyasn1 as well as patched locust startup file with the following: > > from urllib3.contrib import pyopenssl > pyopenssl.inject_into_urllib3() > > I also tried adding the following: > from functools import partial > ssl.wrap_socket = partial(ssl.wrap_socket, ssl_version=ssl.PROTOCOL_TLSv1) > > Finally, I've just tried with: > /usr/local/bin/pip2.7 install backports.ssl > > and patching the lucust file with: > > import backports.ssl as ssl > import backports.ssl.monkey as monkey > import requests > monkey.patch() > > I've also added verify=False to my locust test scripts to disable certificate verification according to http://docs.locust.io/en/latest/api.html > > ...And I still get exactly the same error: > > [2014-09-30 14:19:41,793] ip-x-x-x-x/ERROR/stderr: File "build/bdist.linux-x86_64/egg/OpenSSL/SSL.py", line 977, in sendall > [2014-09-30 14:19:41,793] ip-x-x-x-x/ERROR/stderr: File "build/bdist.linux-x86_64/egg/OpenSSL/SSL.py", line 849, in _raise_ssl_error > [2014-09-30 14:19:41,794] ip-x-x-x-x/ERROR/stderr: OpenSSL.SSL > [2014-09-30 14:19:41,794] ip-x-x-x-x/ERROR/stderr: . > [2014-09-30 14:19:41,794] ip-x-x-x-x/ERROR/stderr: WantWriteError > > Now I'm starting to think it's something else than SNI, but all those scripts were working nice before and the only change done was turning on the SNI on tested servers... > > Any idea what my actually cause this WantWriteError? > -- I think I have a clue what's wrong. By default using: /usr/local/bin/pip2.7 install pyOpenSSL ndg-httpsclient pyasn1 gives me pyOpenSSL version 0.14. When I downgrade it to 0.13 with /usr/local/bin/pip2.7 install pyOpenSSL==0.13 everything works nice and smooth. Interestingly, on my local Ubuntu I do have 0.14 version of that package and it works well there... I noticed that dowgrading it to 0.13 buids 'OpenSSL.crypto' extension and that does not happen when installing v. 0.14 so I guess there's simply a connection to openssl missing somehow there in 0.14. According to https://github.com/pyca/pyopenssl/releases there was a big change there: "Second, pyOpenSSL is no longer implemented in C as a collection of extension modules using the Python/C API. Instead, pyOpenSSL is now a pure-Python project with a dependency on a new project, http://github.com/pyca/cryptography, which provides (among other things) a cffi-based interface to OpenSSL." but I also have the most recent version of cryptography (0.6) installed there. And again - it works on local Ubuntu. Weird. I guess I'll just stick to pyOpenSSL==0.13 for the time being, unless somebody gives me a hint what I'm doing wrong with 0.14 :) Br, Reddy From tomcsanyi at slovanet.sk Wed Oct 1 07:51:19 2014 From: tomcsanyi at slovanet.sk (Peter Tomcsanyi) Date: Wed, 1 Oct 2014 13:51:19 +0200 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk In-Reply-To: References: Message-ID: "Ned Deily" wrote in message news:nad-D2DDCB.14070824062014 at news.gmane.org... > The easiest option would be a downloadable package that would allow the > default python.org 8.5-linked _tkinter to be overridden with an 8.6 > version. There may be some news on that front in the near future. It's October... So I tried Python 3.4.2rc1 and it seems that it still links to Tk 8.5 on Mac. Does it mean that there is no plan to link to Tk 8.6 in Python 3.4.2 on Mac? Or is there something that can override 8.5 to 8.6 as you wrote? In the meantime I tried MacPorts. It has Tk 8.6.1 so rotating text work well, but it has still a problem with semi-transparency as described here: http://core.tcl.tk/tk/tktview?name=99b84e49ff It has been fixed in Tk 8.6.2 that is already published for nearly a month, but there seems to be no uypdate on macports yet... So I am quite frustrated that I am not able to make my Python installation on Mac do the same things (namely roatting text and use png files that have semi-transparent pixels) both on Windows and Mac. Best regards Peter From mathematisch at gmail.com Wed Oct 1 08:04:21 2014 From: mathematisch at gmail.com (math math) Date: Wed, 1 Oct 2014 05:04:21 -0700 (PDT) Subject: how to parse standard algebraic notation In-Reply-To: References: <4a7f3e7a-ba4d-405e-a078-937bf861fcd8@googlegroups.com> Message-ID: Thanks a lot, I will give this a shot. From cl at isbd.net Wed Oct 1 08:16:07 2014 From: cl at isbd.net (cl at isbd.net) Date: Wed, 1 Oct 2014 13:16:07 +0100 Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: <7t7tfb-5lu.ln1@chris.zbmc.eu> Joel Goldstick wrote: > On Wed, Oct 1, 2014 at 6:45 AM, wrote: > > Peter Otten <__peter__ at web.de> wrote: > >> cl at isbd.net wrote: > >> > >> > I have a dictionary as follows:- > >> > > >> > { > >> > u'StarterAmps1': Row(id=4, ain=u'AIN3', name=u'StarterAmps1', > >> > conv=6834.374834509803, Description=u'Starter Amps'), u'LeisureVolts': > >> > Row(id=1, ain=u'AIN0', name=u'LeisureVolts', conv=29.01374215995874, > >> > Description=u'Leisure Volts'), u'RudderPos': Row(id=6, ain=u'AIN5', > >> > name=u'RudderPos', conv=0.028125, Description=u'Rudder Position'), u'xx': > >> > Row(id=7, ain=u'AIN6', name=u'xx', conv=0.028125, Description=u''), > >> > u'LeisureAmps1': Row(id=3, ain=u'AIN2', name=u'LeisureAmps1', > >> > conv=32.727273081945, Description=u'Leisure Amps'), u'StarterVolts': > >> > Row(id=2, ain=u'AIN1', name=u'StarterVolts', conv=28.94469628911757, > >> > Description=u'Starter Volts') } > >> > > >> > I want to output a menu to a user comprising some parts of the > >> > dictionary (ain and Description) sorted by ain. > >> > > >> > Is there some incantation of sorted() that will do what I want? I > >> > can't quite fathom out the 'key=' parameter needed to sort it by the > >> > tuple item. Maybe I need a cmp= ? > >> > > >> > E.g. I want to do something like:- > >> > > >> > for meas in sorted(adc.cfg, key=???): > >> > print(adc.cfg[meas].ain, adc.cfg[meas].Description) > >> > > >> > What's needed in the ??? > >> > >> for meas in sorted(adc.cfg, key=lambda key: adc.cfg[key].ain): > >> print(adc.cfg[meas].ain, adc.cfg[meas].Description) > >> > > Brilliant, worked perfectly, thank you. The bit I didn't understamd was > > that 'lambda' bit, but I just looked it up and I'm a bit clearer now. > > > >> or simpler > >> > >> for row in sorted(adc.cfg.values(), key=operator.attrgetter("ain")) > >> print(row.ain, row.Description) > >> > > I tried this, I got:- > > > > Traceback (most recent call last): > > File "/home/chris/bin/calibrate.py", line 24, in > > for meas in sorted(adc.cfg.values, > > key=operator.attrgetter("ain")): > > NameError: name 'operator' is not defined > > I must admit that it's the bits like 'operator' in the parameters that > > I can't really understand where they come from. > > > > operator is a module. See > https://docs.python.org/2/library/operator.html#module-operator Ah, OK, as it sort of might be a keyword I hadn't thought of that. :-) -- Chris Green ? From marco.buttu at gmail.com Wed Oct 1 08:22:59 2014 From: marco.buttu at gmail.com (Marco Buttu) Date: Wed, 01 Oct 2014 14:22:59 +0200 Subject: how to parse standard algebraic notation In-Reply-To: References: <4a7f3e7a-ba4d-405e-a078-937bf861fcd8@googlegroups.com> Message-ID: <542BF223.9080200@oa-cagliari.inaf.it> On 01/10/2014 09:01, math math wrote: > What would be a good starting strategy for writing a program to take the derivative of a polynomial expression, such as this below?: > "x**3 + x**2 + x + 1" You can look at sympy: >>> from sympy import * >>> equation = simplify("x**3 + x**2 + x + 1") >>> equation x**3 + x**2 + x + 1 >>> diff(equation) 3*x**2 + 2*x + 1 -- Marco Buttu INAF-Osservatorio Astronomico di Cagliari Via della Scienza n. 5, 09047 Selargius (CA) Phone: 070 711 80 217 Email: mbuttu at oa-cagliari.inaf.it From marco.buttu at gmail.com Wed Oct 1 08:26:26 2014 From: marco.buttu at gmail.com (Marco Buttu) Date: Wed, 01 Oct 2014 14:26:26 +0200 Subject: how to parse standard algebraic notation References: <4a7f3e7a-ba4d-405e-a078-937bf861fcd8@googlegroups.com> Message-ID: On 01/10/2014 09:01, math math wrote: > What would be a good starting strategy for writing a program to take the derivative of a polynomial expression, such as this below?: > "x**3 + x**2 + x + 1" You can look at sympy: >>> from sympy import * >>> equation = simplify("x**3 + x**2 + x + 1") >>> equation x**3 + x**2 + x + 1 >>> diff(equation) 3*x**2 + 2*x + 1 -- Marco Buttu From cl at isbd.net Wed Oct 1 08:19:51 2014 From: cl at isbd.net (cl at isbd.net) Date: Wed, 1 Oct 2014 13:19:51 +0100 Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: <748tfb-5lu.ln1@chris.zbmc.eu> Joel Goldstick wrote: > On Wed, Oct 1, 2014 at 5:58 AM, wrote: > > I have a dictionary as follows:- > > > > { > > u'StarterAmps1': Row(id=4, ain=u'AIN3', name=u'StarterAmps1', conv=6834.374834509803, > Description=u'Starter Amps'), > > u'LeisureVolts': Row(id=1, ain=u'AIN0', name=u'LeisureVolts', conv=29.01374215995874, > Description=u'Leisure Volts'), > > u'RudderPos': Row(id=6, ain=u'AIN5', name=u'RudderPos', conv=0.028125, > Description=u'Rudder Position'), > > u'xx': Row(id=7, ain=u'AIN6', name=u'xx', conv=0.028125, Description=u''), > > u'LeisureAmps1': Row(id=3, ain=u'AIN2', name=u'LeisureAmps1', conv=32.727273081945, > Description=u'Leisure Amps'), > > u'StarterVolts': Row(id=2, ain=u'AIN1', name=u'StarterVolts', conv=28.94469628911757, > Description=u'Starter Volts') > > } > > Is Row a function? Or do you have a key with a tuple as the value? Row is a namedtuple, the dictionary is extracted from a database with a row factory so the namedtuple names are the column names. It means that if I change a column name then most things continue to work without any code changes, and also I can refer to items in the tuple by name of course. I have the answer to my question in other responses. -- Chris Green ? From rosuav at gmail.com Wed Oct 1 09:06:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 1 Oct 2014 23:06:42 +1000 Subject: JSON-encoding very long iterators In-Reply-To: <209e604c-1a18-43ff-9358-12fb784d3d4c@googlegroups.com> References: <4232c92a-101c-4a1b-89b2-e80d67ef7bc6@googlegroups.com> <209e604c-1a18-43ff-9358-12fb784d3d4c@googlegroups.com> Message-ID: On Wed, Oct 1, 2014 at 8:13 PM, Alfred Morgan wrote: > I added a stream flag (off by default) and also added file streaming (thanks for the idea). > > https://github.com/Zectbumo/cpython/compare/2.7 > > What do you think now? I think that you're adding features to Python 2.7, which isn't getting new features. That won't be merged into trunk. Does your patch apply to 3.x? ChrisA From steve+comp.lang.python at pearwood.info Wed Oct 1 09:08:56 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 01 Oct 2014 23:08:56 +1000 Subject: Restarting Python References: <447m2atpvha8jt21cpulq8qu5p92pmogk3@4ax.com> Message-ID: <542bfce8$0$13009$c3e8da3$5496439d@news.astraweb.com> Terry Reedy wrote: > Python does not have 'commands'. Terry, even experienced Python developers sometimes describe functions and statements as "commands", e.g. "Use the print command to display results". I think we can cut a beginner like Seymore a bit of slack for misusing terminology. -- Steven From kw at codebykevin.com Wed Oct 1 09:13:08 2014 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 01 Oct 2014 09:13:08 -0400 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk In-Reply-To: References: Message-ID: On 10/1/14, 7:51 AM, Peter Tomcsanyi wrote: > "Ned Deily" wrote in message > news:nad-D2DDCB.14070824062014 at news.gmane.org... >> The easiest option would be a downloadable package that would allow the >> default python.org 8.5-linked _tkinter to be overridden with an 8.6 >> version. There may be some news on that front in the near future. > > It's October... > So I tried Python 3.4.2rc1 and it seems that it still links to Tk 8.5 on > Mac. > Does it mean that there is no plan to link to Tk 8.6 in Python 3.4.2 on > Mac? > Or is there something that can override 8.5 to 8.6 as you wrote? > The solution here is to build Python and Tcl/Tk yourself, in the versions you want, and then things should work just fine. -- Kevin Walzer Code by Kevin/Mobile Code by Kevin http://www.codebykevin.com http://www.wtmobilesoftware.com From rustompmody at gmail.com Wed Oct 1 09:39:15 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 1 Oct 2014 06:39:15 -0700 (PDT) Subject: Restarting Python In-Reply-To: <542bfce8$0$13009$c3e8da3$5496439d@news.astraweb.com> References: <447m2atpvha8jt21cpulq8qu5p92pmogk3@4ax.com> <542bfce8$0$13009$c3e8da3$5496439d@news.astraweb.com> Message-ID: <187ba983-e98a-4cd0-b19f-d78f6c1bafce@googlegroups.com> On Wednesday, October 1, 2014 6:39:11 PM UTC+5:30, Steven D'Aprano wrote: > Terry Reedy wrote: > > Python does not have 'commands'. > Terry, even experienced Python developers sometimes describe functions and > statements as "commands", e.g. "Use the print command to display results". > I think we can cut a beginner like Seymore a bit of slack for misusing > terminology. Agreed in general. However in this case I wonder... Do you even understand what is being requested? From steve+comp.lang.python at pearwood.info Wed Oct 1 10:47:13 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 02 Oct 2014 00:47:13 +1000 Subject: Restarting Python References: <447m2atpvha8jt21cpulq8qu5p92pmogk3@4ax.com> Message-ID: <542c13f1$0$13007$c3e8da3$5496439d@news.astraweb.com> Seymore4Head wrote: > Since the developers of Python decided to make Python 3 non backward > compatible, I can't help but wonder why they don't think a command to > restart would be a useful addition? Possibly because it isn't a useful addition? Or maybe they just never thought of it. But more likely the first. Why doesn't Microsoft Office have a "Restart Office" command? Or Outlook? Or Notepad? Normally to restart anything, with the exception of the operating system, you exit/quit, then start again. Inside the interactive interpreter, I can restart the interpreter with four keystrokes: - Ctrl-D - UP-ARROW - ENTER Ctrl-D exits Python and returns me to the shell, UP-ARROW fetches the previous command ("python"), and ENTER runs that command. On Windows, I *think* you have to type Ctrl-Z ENTER instead of Ctrl-D, so that will be five keystrokes. Either way, that's significantly faster and simpler than using a "restart" function, say: - type "restart()" - ENTER (twelve keystrokes). Even if restarting is a little harder: - type "quit()" - press ENTER - click Start Menu > Programs > Python > Python33.exe it's still not very hard in the big picture. So having a restart command would be of very little benefit in the interactive interpreter. (I don't say *no* benefit.) But it's actually a quite hard thing to do, restarting a process from within itself. It can obviously be done, since I've seen programs like Firefox do it, but I'm not sure how to write such a function. I think that something like this might do the job: - grab the current process ID; - start a daemon process which monitors that process ID; - exit; - when the daemon process sees that process ID is no longer alive, start up the application again; but that glosses over a number of painful difficulties. What if the parent terminal is no longer running? What about environment variables and command line arguments? What happens if you are running over a remote shell like ssh, and the link is terminated as soon as the Python process ends? So "automatically restart" would be a lot of work, it would quite likely be fragile and easily broken, and the benefit would be minimal. But it gets worse... because restart() would also be available when running non-interactive programs. And it isn't even clear what that should do, let alone how to do it. Consider a program like this: import sys x = 42 sys.exit() print("Hello World") That prints nothing, because exit() stops the program from running any further. But what if we replace the exit() with a restart()? What would you expect it to do? If you expect it to restart, then continue on by printing "Hello World", then the Python interpreter would have to be completely redesigned from scratch. All that work, just as a convenience for restarting, is not worth it. I note that this sort of system can actually be justified. During the Apollo program, the landing module's computer was designed to restart when it ran out of memory and continue on with the current calculation that had been interrupted: https://www.hq.nasa.gov/alsj/a11/a11.1201-pa.html During the eight minutes that it took for the Eagle to land on the moon, the computer restarted at least five times, including three times in one 40 second period. http://www.doneyles.com/LM/Tales.html But Python is a long way from a Lunar Lander, and a restart() command would be a lot of effort for not much benefit. -- Steven From steve+comp.lang.python at pearwood.info Wed Oct 1 10:49:16 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 02 Oct 2014 00:49:16 +1000 Subject: Keepin constants, configuration values, etc. in Python - dedicated module or what? References: <54hqfb-nan.ln1@chris.zbmc.eu> <36d7ddca-29f4-403c-a64d-611e187afc3a@googlegroups.com> <2ea96bcf-e905-4d77-a105-82b27715aa6e@googlegroups.com> Message-ID: <542c146c$0$13007$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > I'd agree, where "trivial limits" is defined by each individual item. > Going with straight Python code is fine for huge projects with long > config files, as long as each config entry is itself simple. You even > get a form of #include: "from otherfile import *". I would argue the opposite. If I have a large Python project, with big config files, then the added complexity of moving the config data into separate files using a non-executable format (say, JSON or INI) is minimal, and keeping the data and code separate will pay off. But for small Python projects, with only a few data values, keeping them separate is overkill. So, to the Original Poster, I think that depending on the size of your program and the amount of config data you have to deal with, there's nothing wrong with including it directly in the module. -- Steven From rosuav at gmail.com Wed Oct 1 10:55:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 2 Oct 2014 00:55:11 +1000 Subject: Keepin constants, configuration values, etc. in Python - dedicated module or what? In-Reply-To: <542c146c$0$13007$c3e8da3$5496439d@news.astraweb.com> References: <54hqfb-nan.ln1@chris.zbmc.eu> <36d7ddca-29f4-403c-a64d-611e187afc3a@googlegroups.com> <2ea96bcf-e905-4d77-a105-82b27715aa6e@googlegroups.com> <542c146c$0$13007$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Oct 2, 2014 at 12:49 AM, Steven D'Aprano wrote: > Chris Angelico wrote: > >> I'd agree, where "trivial limits" is defined by each individual item. >> Going with straight Python code is fine for huge projects with long >> config files, as long as each config entry is itself simple. You even >> get a form of #include: "from otherfile import *". > > I would argue the opposite. Welcome to design debates, where there are as many valid and justifiable views as there are participants :) Though I wasn't precluding small config files from being code - just saying that I don't think size of project is a factor at all. ChrisA From steve+comp.lang.python at pearwood.info Wed Oct 1 12:00:37 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 02 Oct 2014 02:00:37 +1000 Subject: Clearing globals in CPython Message-ID: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Out of curiosity, I ran: globals().clear() in the interactive interpreter. It broke much more than I expected! Built-ins were no longer available, and import stopped working. I expected that global variables would be all lost, but built-ins would remain, since they don't live in the global namespace. I was wrong: >>> globals().clear() >>> x = len([]) Traceback (most recent call last): File "", line 1, in NameError: name 'len' is not defined The reason, I think, is that CPython has a special __builtins__ global variable that the interpreter uses to access built-in functions. What *appears* to be happening is that if that __builtins__ global is missing, CPython can not access the built-ins. (Supporting this interpretation: IronPython, like CPython, has a __builtins__ global, and behaves the same when the globals() are cleared. Jython, which does not have a __builtins__ global, does not.) Well that's okay, I thought to myself, I'll just import the built-in functions: >>> from builtins import len # use '__builtin__' in Python 2 Traceback (most recent call last): File "", line 1, in ImportError: __import__ not found Oops. So, with no built-ins available, import no longer works. That makes things rather tricky. Obviously the easiest way to recover is to exit the current session and restart it, but as a challenge, can we recover from this state? -- Steven From rosuav at gmail.com Wed Oct 1 12:14:03 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 2 Oct 2014 02:14:03 +1000 Subject: Clearing globals in CPython In-Reply-To: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Oct 2, 2014 at 2:00 AM, Steven D'Aprano wrote: > Obviously the easiest way to recover is to exit the current session and > restart it, but as a challenge, can we recover from this state? Oooh interesting. This is kinda like breaking out of a sandbox, and I know there are people here who are experts at that. However... I'm not entirely sure how to get a backtrace, when you don't have any built-in exceptions! In Python 2, I can define an old-style class and raise that. However, with the removal of __builtins__, Python throws a bunch of errors about restricted mode, so I'm really not sure where to go from there. ChrisA From jeanmichel at sequans.com Wed Oct 1 12:30:21 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 1 Oct 2014 18:30:21 +0200 (CEST) Subject: Python code in presentations In-Reply-To: <20141001114234.d86083aeed01ea7ce99608fb@gmx.net> Message-ID: <197476113.8354973.1412181021488.JavaMail.root@sequans.com> ----- Original Message ----- > From: "Wolfgang Keller" > To: python-list at python.org > Sent: Wednesday, 1 October, 2014 11:42:34 AM > Subject: Re: Python code in presentations > > > Right now the method I'm using is write the code in notepad++, use > > a > > plugin (NppExport) to copy paste code into powerpoint. After using > > it > > a little bit, I'm really not satisfied with this method, it's > > expensive and all this copy paste stuff is driving me crazy. Not to > > mention that the syntax highlight from notepads renders like crap > > in > > powerpoint. > > > > I wonder if some people in this list who have successfully > > presented > > python code have some tips about doing the proper way. Ned's > > presentations for pycons are to me one example of successful code > > presentation: > > - the layout is simple > > - the code and code output are clearly identified > > - a line of code can be highlighted while presenting > > LyX and Beamer. > > Sincerely, > > Wolfgang Thank you all for all your great suggestions. I think I now have all I need. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From steve+comp.lang.python at pearwood.info Wed Oct 1 12:45:13 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 02 Oct 2014 02:45:13 +1000 Subject: how to parse standard algebraic notation References: <4a7f3e7a-ba4d-405e-a078-937bf861fcd8@googlegroups.com> Message-ID: <542c2f9a$0$12975$c3e8da3$5496439d@news.astraweb.com> math math wrote: > Hi, > > I am trying to learn Python while solving exercises. > > I want to basically write a program that inputs a polynomial in standard > algebraic notation and outputs its derivative. > > I know that I need to get the exponent somehow, but I am not sure how to > accomplish this in python (3.3) > > Do you have any ideas or suggestions? I don't want to use existing modules > as this is meant to be a didactic experience. Code for evaluating mathematical expressions are very common, if you google for "expression parser" I am sure you will find many examples. Don't limit yourself to Python code, you can learn from code written in other languages too, e.g. I have a Pascal programming book that develops a parser for both polynomials and arithmetic expression. The code is fairly long, but quite straightforward to translate into Python (and Pascal code is quite readable.) Look at an standard infix expression, using ^ for powers: 4*x^3 + x^2 - 5*x + 1 There are four terms: 4*x^3 x^2 -5*x 1 So if you replace "-" with "+-" and then split on "+", you will get terms: py> expr = "4*x^3 + x^2 - 5*x + 1" py> terms = expr.replace("-", "+-").split("+") py> terms ['4*x^3 ', ' x^2 ', '- 5*x ', ' 1'] Strip spaces from each term: py> terms = [s.replace(' ', '') for s in terms] py> terms ['4*x^3', 'x^2', '-5*x', '1'] Unfortunately, terms can include optional parts. The coefficient is optional, and may be just a minus sign; the power is optional. To make processing easier, we can do this: term = term.replace('-x', '-1*x') if term.startswith('x'): term = term.replace('x', '1*x') if term.endswith('x'): term = term.replace('x', 'x^1') to each term, which will give us something like: ['4*x^3', '1*x^2', '-5*x^1', '1'] If a term is all digits (with an optional leading minus sign) then it is the constant term. Otherwise, it will be of the form: [optional minus sign][one or more digits]*x^[one or more digits] which can now be easily parsed by splitting it up around the *, x or ^ symbols. Or use a regular expression. -- Steven From rosuav at gmail.com Wed Oct 1 13:01:44 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 2 Oct 2014 03:01:44 +1000 Subject: how to parse standard algebraic notation In-Reply-To: <542c2f9a$0$12975$c3e8da3$5496439d@news.astraweb.com> References: <4a7f3e7a-ba4d-405e-a078-937bf861fcd8@googlegroups.com> <542c2f9a$0$12975$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Oct 2, 2014 at 2:45 AM, Steven D'Aprano wrote: > Code for evaluating mathematical expressions are very common, if you google > for "expression parser" I am sure you will find many examples. Don't limit > yourself to Python code, you can learn from code written in other languages > too, e.g. I have a Pascal programming book that develops a parser for both > polynomials and arithmetic expression. Building expression evaluators is good fun! And then you can add specialty terms, like dice rolling. > roll 2d6 + d6 "Electric" + 12 "Strength" [ROLL] Rosuav rolls 2d6: 3, 6, totalling 9. [ROLL] Rosuav rolls d6: 1 ("Electric") [ROLL] Rosuav adds a bonus of 12 ("Strength") [ROLL] For 2d6 + d6 "Electric" + 12 "Strength", Rosuav totals: 22 The code behind that follows a fairly similar pattern to what you describe, only it deals with dice rolls (NdM -> roll N dice with M sides each) instead of powers of x. (And it allows comments/tags.) ChrisA From ckaynor at zindagigames.com Wed Oct 1 13:08:34 2014 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Wed, 1 Oct 2014 10:08:34 -0700 Subject: Clearing globals in CPython In-Reply-To: References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Oct 1, 2014 at 9:14 AM, Chris Angelico wrote: > On Thu, Oct 2, 2014 at 2:00 AM, Steven D'Aprano > wrote: > > Obviously the easiest way to recover is to exit the current session and > > restart it, but as a challenge, can we recover from this state? > > Oooh interesting. This is kinda like breaking out of a sandbox, and I > know there are people here who are experts at that. However... I'm not > entirely sure how to get a backtrace, when you don't have any built-in > exceptions! In Python 2, I can define an old-style class and raise > that. However, with the removal of __builtins__, Python throws a bunch > of errors about restricted mode, so I'm really not sure where to go > from there. > I've played with it a bit, and I haven't found any way to break it yet. I have discovered that you cannot directly declare classes, although you can access the type built-in (indirectly) so it might be possible to indirectly declare a class. It is also possible to access the types of many of the built-ins (str, bytes, dict, set, type, object, frame, function, code, generator, int, float at a minimum). Note that I've been playing with Python 3.4.1. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Oct 1 13:24:05 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 01 Oct 2014 19:24:05 +0200 Subject: Clearing globals in CPython References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Out of curiosity, I ran: > > globals().clear() > > in the interactive interpreter. It broke much more than I expected! > Built-ins were no longer available, and import stopped working. > > I expected that global variables would be all lost, but built-ins would > remain, since they don't live in the global namespace. I was wrong: > >>>> globals().clear() >>>> x = len([]) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'len' is not defined > > The reason, I think, is that CPython has a special __builtins__ global > variable that the interpreter uses to access built-in functions. What > *appears* to be happening is that if that __builtins__ global is missing, > CPython can not access the built-ins. > > (Supporting this interpretation: IronPython, like CPython, has a > __builtins__ global, and behaves the same when the globals() are cleared. > Jython, which does not have a __builtins__ global, does not.) > > Well that's okay, I thought to myself, I'll just import the built-in > functions: > >>>> from builtins import len # use '__builtin__' in Python 2 > Traceback (most recent call last): > File "", line 1, in > ImportError: __import__ not found > > Oops. > > So, with no built-ins available, import no longer works. That makes things > rather tricky. > > Obviously the easiest way to recover is to exit the current session and > restart it, but as a challenge, can we recover from this state? $ python3 Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> globals().clear() >>> import that Traceback (most recent call last): File "", line 1, in ImportError: __import__ not found >>> object = 1 .__class__.__bases__[0] >>> Quitter = [c for c in object.__subclasses__() if c.__name__ == "Quitter"][0] >>> __builtins__ = Quitter.__call__.__globals__["__builtins__"] >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! From nad at acm.org Wed Oct 1 13:34:47 2014 From: nad at acm.org (Ned Deily) Date: Wed, 01 Oct 2014 10:34:47 -0700 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk References: Message-ID: In article , "Peter Tomcsanyi" wrote: > "Ned Deily" wrote in message > news:nad-D2DDCB.14070824062014 at news.gmane.org... > It's October... > So I tried Python 3.4.2rc1 and it seems that it still links to Tk 8.5 on > Mac. > Does it mean that there is no plan to link to Tk 8.6 in Python 3.4.2 on Mac? > Or is there something that can override 8.5 to 8.6 as you wrote? The python.org 3.4.x series of installers will likely never change from linking with Tk 8.5 by default. That would break a number of important third-party Python packages that supply binary distributions built for the python.org OS X pythons, like matplotlib. For Python 3.5, we will have the opportunity to change that. > In the meantime I tried MacPorts. It has Tk 8.6.1 so rotating text work > well, but it has still a problem with semi-transparency as described here: > http://core.tcl.tk/tk/tktview?name=99b84e49ff > It has been fixed in Tk 8.6.2 that is already published for nearly a month, > but there seems to be no uypdate on macports yet... File an update request for the tcl and tk ports on the MacPorts tracker. The project is usually very responsive to such requests. https://trac.macports.org Note that ActiveState hasn't yet released their versions of 8.6.2. > So I am quite frustrated that I am not able to make my Python installation > on Mac do the same things (namely roatting text and use png files that have > semi-transparent pixels) both on Windows and Mac. As Kevin Walzer points out, you *can* also build your own. I still intend to provide a downloadable solution for 3.4.x and 2.7.x; I hope to get back to it shortly. Sorry for the delay! -- Ned Deily, nad at acm.org From tjreedy at udel.edu Wed Oct 1 13:52:57 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 01 Oct 2014 13:52:57 -0400 Subject: Restarting Python In-Reply-To: <542c13f1$0$13007$c3e8da3$5496439d@news.astraweb.com> References: <447m2atpvha8jt21cpulq8qu5p92pmogk3@4ax.com> <542c13f1$0$13007$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/1/2014 10:47 AM, Steven D'Aprano wrote: > Inside the interactive interpreter, I can restart the interpreter with four > keystrokes: > > - Ctrl-D > - UP-ARROW > - ENTER > > Ctrl-D exits Python and returns me to the shell, UP-ARROW fetches the > previous command ("python"), and ENTER runs that command. On Windows, I > *think* you have to type Ctrl-Z ENTER instead of Ctrl-D, so that will be > five keystrokes. For the console interpreter, this is still true even in 3.5.0a0 >>> ^D File "", line 1 ? ^ SyntaxError: invalid syntax Idle now quits on ^D on all systems. ^Z (unlike other control chars) is rejected with an immediate error beep. Either way, restart is a single click if one have the console or Idle interpreter icon pinned on the task bar. Even this is unnecessary with Idle as it has a Restart Shell command on the Shell menu (hotkey ^F6). (This is automatically invoked when running an edited file (F5)). Some problems with restarting are unwinding the call stack, undoing what has been done, and doing something else so as to not run into the same problem. We can view every raise -- except pair as a partial restart of some sort. A minimal startup script something like the following allows a nearly global restart that addresses all three problems listed above. from appmain import main, cleanup, RestartError restart = False while True: try: main(restart) except RestartError as err: cleanup() restart = err continue The main and cleanup functions, switching on the restart arg, and possibly the class RestartError depend on the app. -- Terry Jan Reedy From breamoreboy at yahoo.co.uk Wed Oct 1 14:17:03 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 01 Oct 2014 19:17:03 +0100 Subject: Clearing globals in CPython In-Reply-To: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 01/10/2014 17:00, Steven D'Aprano wrote: > Out of curiosity, I ran: > > globals().clear() > > in the interactive interpreter. It broke much more than I expected! > Built-ins were no longer available, and import stopped working. > > I expected that global variables would be all lost, but built-ins would > remain, since they don't live in the global namespace. I was wrong: > >>>> globals().clear() >>>> x = len([]) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'len' is not defined > > The reason, I think, is that CPython has a special __builtins__ global > variable that the interpreter uses to access built-in functions. What > *appears* to be happening is that if that __builtins__ global is missing, > CPython can not access the built-ins. > > (Supporting this interpretation: IronPython, like CPython, has a > __builtins__ global, and behaves the same when the globals() are cleared. > Jython, which does not have a __builtins__ global, does not.) > > Well that's okay, I thought to myself, I'll just import the built-in > functions: > >>>> from builtins import len # use '__builtin__' in Python 2 > Traceback (most recent call last): > File "", line 1, in > ImportError: __import__ not found > > Oops. > > So, with no built-ins available, import no longer works. That makes things > rather tricky. > > Obviously the easiest way to recover is to exit the current session and > restart it, but as a challenge, can we recover from this state? > > We obviously need a Restart Command. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From tjreedy at udel.edu Wed Oct 1 14:44:26 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 01 Oct 2014 14:44:26 -0400 Subject: Clearing globals in CPython In-Reply-To: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/1/2014 12:00 PM, Steven D'Aprano wrote: > Out of curiosity, I ran: > > globals().clear() > > in the interactive interpreter. It broke much more than I expected! > Built-ins were no longer available, and import stopped working. As you discovered, this reduces the interpreter to a pure syntax machine with no name bindings -- sort of like a high-level assembler with no access to a function library. > I expected that global variables would be all lost, but built-ins would > remain, since they don't live in the global namespace. ... > The reason, I think, is that CPython has a special __builtins__ global > variable that the interpreter uses to access built-in functions. When executing statements from Shell, Idle restores __builtins__. >>> globals().clear() >>> print(dir()) ['__builtins__'] >>> print(__builtins__) The odd thing is that executing the same code from a file prints [] and then raises "NameError: name '__builtins__' is not defined". > Well that's okay, I thought to myself, I'll just import the built-in > functions: > >>>> from builtins import len # use '__builtin__' in Python 2 > Traceback (most recent call last): > File "", line 1, in > ImportError: __import__ not found Most keyword statements are implemented by internal functions not accessible from Python except through the statement syntax. Import is an exception. This is one of the hooks that allow the behavior of imports to be modified. The result is like, for instance, programming in C with 'include' disabled. > Oops. > > So, with no built-ins available, import no longer works. That makes things > rather tricky. > > Obviously the easiest way to recover is to exit the current session and > restart it, but as a challenge, can we recover from this state? -- Terry Jan Reedy From alfred at 54.org Wed Oct 1 18:01:32 2014 From: alfred at 54.org (Alfred Morgan) Date: Wed, 1 Oct 2014 15:01:32 -0700 (PDT) Subject: JSON-encoding very long iterators In-Reply-To: References: <4232c92a-101c-4a1b-89b2-e80d67ef7bc6@googlegroups.com> <209e604c-1a18-43ff-9358-12fb784d3d4c@googlegroups.com> Message-ID: On Wednesday, October 1, 2014 6:07:23 AM UTC-7, Chris Angelico wrote: > On Wed, Oct 1, 2014 at 8:13 PM, Alfred Morgan wrote: > > What do you think now? > > I think that you're adding features to Python 2.7, which isn't getting > new features. That won't be merged into trunk. Does your patch apply > to 3.x? > > ChrisA Thanks Chris, Yes I made changes to 2.7 because I'm not familiar with Python3 yet. Once I get some feedback I was going to see if someone was interested in porting it. If not I will learn and do it myself. The patch will not work on the 3.x code but the code is similar enough to easily port over. From drsalists at gmail.com Wed Oct 1 18:06:00 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Wed, 1 Oct 2014 15:06:00 -0700 Subject: Obscuring Python source from end users In-Reply-To: <542946ec$0$12998$c3e8da3$5496439d@news.astraweb.com> References: <89381545-5edc-4f85-a4b8-86eebfdf34ee@googlegroups.com> <542946ec$0$12998$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Sep 29, 2014 at 4:47 AM, Steven D'Aprano wrote: > norman.ives at gmail.com wrote: > >> Hello list >> >> Python 3.4 applies. >> >> I have a project that involves distributing Python code to users in an >> organisation. Users do not interact directly with the Python code; they >> only know this project as an Excel add-in. >> >> Now, internal audit takes exception in some cases if users are able to see >> the source code. > > You have my sympathy. Actually, I don't think this is that bad. Companies have rules; one simply has to learn to live with this or suffer greatly. Some rules are worth fighting, but this probably isn't one of them. >> So I'm wondering if anyone has clever suggestions in this regard... > > Yes. Distribute the pyc files only. Yes, this is the way it's usually done. Supposedly Microsoft did this for a while, after acquiring some Python software. In the Python 3.4 case, the pyc's should be in the __pycache__ subdirectory. Another option would be to convert to Cython and compile (not as bad as it sounds). But __pycache__/*.pyc would probably be easier. From shivaji_tn at yahoo.com Wed Oct 1 18:37:13 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Wed, 1 Oct 2014 22:37:13 +0000 (UTC) Subject: Function passed as an argument returns none Message-ID: Hi, I am learning Python (version 3.4) strings.I have a function that takes in a parameter and prints it out as given below. def donuts(count): if count <= 5: print('Number of donuts: ',count) else: print('Number of donuts: many') return It works fine if I call donuts(5) It returns: we have 5 DN (as expected) However if I do : test(donuts(4), 'Number of donuts: 4') where test is defined as below: def test(got, expected): print('got: ', got, 'Expected:' ,expected) if got == expected: prefix = ' OK ' else: prefix = ' X ' print (('%s got: %s expected: %s') % (prefix, repr(got), repr(expected))) Only 'None' gets passed on to parameter 'got' instead of the expected value of 4. Any idea why 'None' is getting passed even though calling the donuts(4) alone returns the expected value? Thanks, Shiva. From aberg010 at my.hennepintech.edu Wed Oct 1 18:45:01 2014 From: aberg010 at my.hennepintech.edu (Andrew Berg) Date: Wed, 1 Oct 2014 17:45:01 -0500 Subject: Function passed as an argument returns none In-Reply-To: References: Message-ID: <542C83ED.6070204@my.hennepintech.edu> On 2014.10.01 17:37, Shiva wrote: > Only 'None' gets passed on to parameter 'got' instead of the expected value > of 4. > Any idea why 'None' is getting passed even though calling the donuts(4) > alone returns the expected value? donuts() prints what you tell it to ("Number of donuts: 5"), and then returns what you tell it to (nothing). If you don't explicitly make a function return something, it returns None. Whatever other logic you have in the function is irrelevant. From ckaynor at zindagigames.com Wed Oct 1 18:45:56 2014 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Wed, 1 Oct 2014 15:45:56 -0700 Subject: Function passed as an argument returns none In-Reply-To: References: Message-ID: Chris On Wed, Oct 1, 2014 at 3:37 PM, Shiva wrote: > Hi, > I am learning Python (version 3.4) strings.I have a function that takes in > a > parameter and prints it out as given below. > > def donuts(count): > if count <= 5: > print('Number of donuts: ',count) > else: > print('Number of donuts: many') > return > Print actually prints the value, and does not return it. Based off the rest of your code, you probably want this to look like (untested): def donuts(count): if count <= 5: return 'Number of donuts: {}'.format(count) # You could also use other formatting methods here, if you prefer the printf-style "%s" instead. else: return 'Number of donuts: many' Which will cause donuts to return the actual string, rather than printing it out to the TTY. Note that this means that, if run from the interpreter as you have been trying, the interpreter will now display "Number of donuts: 4" - including the quotes. > It works fine if I call > donuts(5) > > It returns: > we have 5 DN (as expected) > > However if I do : > > test(donuts(4), 'Number of donuts: 4') > If you do as mentioned above, donuts will then return the value, and it will be passed into test. > where test is defined as below: > > def test(got, expected): > print('got: ', got, 'Expected:' ,expected) > if got == expected: > prefix = ' OK ' > else: > prefix = ' X ' > print (('%s got: %s expected: %s') % (prefix, repr(got), repr(expected))) > > > Only 'None' gets passed on to parameter 'got' instead of the expected value > of 4. > Any idea why 'None' is getting passed even though calling the donuts(4) > alone returns the expected value? > donuts is, in fact, returning None when called alone. It merely looks like it is returning it as, when run from the interpreter, Python prints the "repr" of the return values of any non-None returns. This is known as a REPL: read, execute, print, loop. It is quite handy for debugging. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Wed Oct 1 18:54:56 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 2 Oct 2014 08:54:56 +1000 Subject: JSON-encoding very long iterators In-Reply-To: References: <4232c92a-101c-4a1b-89b2-e80d67ef7bc6@googlegroups.com> <209e604c-1a18-43ff-9358-12fb784d3d4c@googlegroups.com> Message-ID: On Thu, Oct 2, 2014 at 8:01 AM, Alfred Morgan wrote: > On Wednesday, October 1, 2014 6:07:23 AM UTC-7, Chris Angelico wrote: >> On Wed, Oct 1, 2014 at 8:13 PM, Alfred Morgan wrote: >> > What do you think now? >> >> I think that you're adding features to Python 2.7, which isn't getting >> new features. That won't be merged into trunk. Does your patch apply >> to 3.x? >> >> ChrisA > > Thanks Chris, Yes I made changes to 2.7 because I'm not familiar with Python3 yet. Once I get some feedback I was going to see if someone was interested in porting it. If not I will learn and do it myself. > The patch will not work on the 3.x code but the code is similar enough to easily port over. Okay. At some point, you'll have to port your patch to the latest codebase, though, as the core devs won't want to do that work themselves. I recommend getting familiar enough with Python 3 to be able to see if the patch at least makes sense. (I expect it probably will.) Try out a vanilla 3.4 or master (3.5ish), then apply your patch, and see if the improvement is indeed visible. Assuming it is (again, I expect it will be; JSON isn't materially different in Python 3), you can post a 3.x patch here, and you'll have rather more interest, I think - certainly people like me won't be applying your 2.7 patch, as that's not something that's ever going to "actually happen". But due to the changes of str/unicode to str/bytes in Py3, you will find that your patch requires more than just simple tweaks. It won't be as simple as "apply the patch and fix a merge conflict"; you'll have to rethink your changes and apply them to the different codebase. Unfortunately, that's just what happens when you start development on 2.7; there are differences in the code, and there's no getting around them. It'll be much easier for you if you get familiar with Py3 and do development there. :) ChrisA From breamoreboy at yahoo.co.uk Wed Oct 1 19:48:44 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 02 Oct 2014 00:48:44 +0100 Subject: Function passed as an argument returns none In-Reply-To: References: Message-ID: On 01/10/2014 23:37, Shiva wrote: > Hi, > I am learning Python (version 3.4) strings.I have a function that takes in a > parameter and prints it out as given below. > > def donuts(count): > if count <= 5: > print('Number of donuts: ',count) > else: > print('Number of donuts: many') > return > > It works fine if I call > donuts(5) > > It returns: > we have 5 DN (as expected) It doesn't :) As it takes the first path through the function it will *print* 'Number of donuts: 5' and then return None as you haven't specified what your function returns. > > However if I do : > > test(donuts(4), 'Number of donuts: 4') > > > where test is defined as below: > > def test(got, expected): > print('got: ', got, 'Expected:' ,expected) > if got == expected: > prefix = ' OK ' > else: > prefix = ' X ' > print (('%s got: %s expected: %s') % (prefix, repr(got), repr(expected))) > > > Only 'None' gets passed on to parameter 'got' instead of the expected value > of 4. Your expectations are wrong, your function makes no attempt to return the value you've passed in. I'd (re)read the tutorial again and digest it, then have another go. > Any idea why 'None' is getting passed even though calling the donuts(4) > alone returns the expected value? What is your expected value? My expected value is None for a value of 4 as you've given a return statement without specifying a value. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From denismfmcmahon at gmail.com Wed Oct 1 20:23:59 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 2 Oct 2014 00:23:59 +0000 (UTC) Subject: Function passed as an argument returns none References: Message-ID: On Wed, 01 Oct 2014 22:37:13 +0000, Shiva wrote: > Hi, > I am learning Python (version 3.4) strings.I have a function that takes > in a parameter and prints it out as given below. > > def donuts(count): > if count <= 5: > print('Number of donuts: ',count) > else: > print('Number of donuts: many') return > > It works fine if I call donuts(5) > > It returns: No it doesn't > we have 5 DN (as expected) It doesn't return anything, it prints something out. Printing something out from within a function is not the same as returning something. Consider the following:: def nonsense( something ): print( "something is", something ) return ( 5, "elephants", { "monkey": "peanut", "baboon": "banana", "numbers": ( 1, ), }, [ 1, 2, 3, 4, 5, "mouse",( -6.34565e-35, 4.765213e84, ), ], None, True, False, ) print( "nonsense( 10 ) is", nonsense( 10 ) ) print( "nonsense( None ) is", nonsense( None ) ) print( "nonsense( ( 5, \"donuts\", ) ) is", nonsense( ( 5, "donuts", ) ) ) The above code shows there is no automatic connection between data output carried out within a function and the value (if any) returned by that function. -- Denis McMahon, denismfmcmahon at gmail.com From ryanshuell at gmail.com Wed Oct 1 21:50:37 2014 From: ryanshuell at gmail.com (ryanshuell at gmail.com) Date: Wed, 1 Oct 2014 18:50:37 -0700 (PDT) Subject: Error from pandas.io.data import DataReader Message-ID: <3efaa62e-46e0-4eee-a013-fdd135503014@googlegroups.com> I am trying to run this snippet of code. from pandas.io.data import DataReader from pandas import Panel, DataFrame import datetime start = datetime.datetime(2010, 1, 1) end = datetime.datetime(2013, 1, 27) with open('dow.txt') as f: symbols = f.read().splitlines() # ['AAPL', 'GLD', 'SPX', 'MCD'] data = dict((symbol, DataReader(symbol, "yahoo", start, end, pause=1)) for symbol in symbols) panel = Panel(data).swapaxes('items', 'minor') closing = panel['Close'].dropna() closing.head() I keep getting this error. Traceback (most recent call last): File "C:\Python27\download_dow.py", line 1, in from pandas.io.data import DataReader ImportError: No module named pandas.io.data From rustompmody at gmail.com Wed Oct 1 22:29:33 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 1 Oct 2014 19:29:33 -0700 (PDT) Subject: Function passed as an argument returns none In-Reply-To: References: Message-ID: <6bf1fc74-e40f-41f0-88b9-e4543c731e69@googlegroups.com> On Thursday, October 2, 2014 4:07:44 AM UTC+5:30, Shiva wrote: > Hi, > I am learning Python (version 3.4) strings.I have a function that takes in a > parameter and prints it out as given below. > def donuts(count): > if count <= 5: > print('Number of donuts: ',count) > else: > print('Number of donuts: many') > return > It works fine if I call > donuts(5) > It returns: > we have 5 DN (as expected) > However if I do : > test(donuts(4), 'Number of donuts: 4') > where test is defined as below: > def test(got, expected): > print('got: ', got, 'Expected:' ,expected) > if got == expected: > prefix = ' OK ' > else: > prefix = ' X ' > print (('%s got: %s expected: %s') % (prefix, repr(got), repr(expected))) > Only 'None' gets passed on to parameter 'got' instead of the expected value > of 4. > Any idea why 'None' is getting passed even though calling the donuts(4) > alone returns the expected value? Others have given you the correct python-technicalities answer: print ? return However given your starting point ? I am learning Python ? let me try a less technical one. You start from the assumption that your donuts returns 5, which it seems to in some contexts and not in others. So by now you know there are 2 kinds of return: >>> def foo(x): return x+5 ... >>> def bar(x): print(x+5) ... >>> foo(4) 9 >>> bar(4) 9 So they seem identical here, right? But as you further discover bar is useless to do anything other than being called at the command line, whereas foo can be used in all sorts of ways: in particular you can use foo to write bar: def bar(x): print(foo(x)) But not conversely. So the morals in short: 1. Stick to the return that works -- python's return statement -- and avoid the return that seems to work -- the print statement 2. print is good for debugging code. When your code is bugfree it should have few/no prints 3. The official tutorial/docs unfortunately foster bad habits in children by showing prints early -- Know better! From rosuav at gmail.com Thu Oct 2 00:02:58 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 2 Oct 2014 14:02:58 +1000 Subject: Function passed as an argument returns none In-Reply-To: <6bf1fc74-e40f-41f0-88b9-e4543c731e69@googlegroups.com> References: <6bf1fc74-e40f-41f0-88b9-e4543c731e69@googlegroups.com> Message-ID: On Thu, Oct 2, 2014 at 12:29 PM, Rustom Mody wrote: > So by now you know there are 2 kinds of return: > > So the morals in short: > > 1. Stick to the return that works -- python's return statement -- > and avoid the return that seems to work -- the print statement Please. There are not two types of return; there are two completely different things here. Don't pretend that print is a bad form of return. It isn't. ChrisA From travisgriggs at gmail.com Thu Oct 2 00:57:41 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Wed, 1 Oct 2014 21:57:41 -0700 Subject: How to show a dictionary sorted on a value within its data? In-Reply-To: References: Message-ID: Sent from my iPhone > On Oct 1, 2014, at 04:12, Peter Otten <__peter__ at web.de> wrote: > > `lambda` is just a fancy way to define a function inline Not sure "fancy" is the correct adjective; more like syntactic tartness (a less sweet version of syntactic sugar). :) From marko at pacujo.net Thu Oct 2 01:17:40 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 02 Oct 2014 08:17:40 +0300 Subject: Obscuring Python source from end users References: <89381545-5edc-4f85-a4b8-86eebfdf34ee@googlegroups.com> <542946ec$0$12998$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8738b7t5hn.fsf@elektro.pacujo.net> Dan Stromberg : > On Mon, Sep 29, 2014 at 4:47 AM, Steven D'Aprano >> Yes. Distribute the pyc files only. > > Yes, this is the way it's usually done. Has the .pyc file format stabilized? A decade ago, my employer shipped an application as .pyc files but had to ship the matching CPython binary with it. Marko From alfred at 54.org Thu Oct 2 02:05:59 2014 From: alfred at 54.org (Alfred Morgan) Date: Wed, 1 Oct 2014 23:05:59 -0700 (PDT) Subject: JSON-encoding very long iterators In-Reply-To: References: <4232c92a-101c-4a1b-89b2-e80d67ef7bc6@googlegroups.com> <209e604c-1a18-43ff-9358-12fb784d3d4c@googlegroups.com> Message-ID: <168531a5-e5df-456d-a24e-db1235a4167f@googlegroups.com> On Wednesday, October 1, 2014 3:55:19 PM UTC-7, Chris Angelico wrote: > At some point, you'll have to port your patch to the latest codebase Okay, done. https://github.com/Zectbumo/cpython/compare/master Iterators for JSON is now Python 3 ready. From rosuav at gmail.com Thu Oct 2 02:33:46 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 2 Oct 2014 16:33:46 +1000 Subject: JSON-encoding very long iterators In-Reply-To: <168531a5-e5df-456d-a24e-db1235a4167f@googlegroups.com> References: <4232c92a-101c-4a1b-89b2-e80d67ef7bc6@googlegroups.com> <209e604c-1a18-43ff-9358-12fb784d3d4c@googlegroups.com> <168531a5-e5df-456d-a24e-db1235a4167f@googlegroups.com> Message-ID: On Thu, Oct 2, 2014 at 4:05 PM, Alfred Morgan wrote: > On Wednesday, October 1, 2014 3:55:19 PM UTC-7, Chris Angelico wrote: >> At some point, you'll have to port your patch to the latest codebase > > Okay, done. > > https://github.com/Zectbumo/cpython/compare/master > > Iterators for JSON is now Python 3 ready. Cool! I didn't think it'd be that easy, actually (all those references to 'basestring' are actually still there in the current source... whodathunkit). Now you can raise a tracker issue on bugs.python.org, or suggest it on python-ideas, and see whether other people get excited by the enhancement! ChrisA From alfred at 54.org Thu Oct 2 02:49:30 2014 From: alfred at 54.org (Alfred Morgan) Date: Wed, 1 Oct 2014 23:49:30 -0700 (PDT) Subject: JSON-encoding very long iterators In-Reply-To: References: <4232c92a-101c-4a1b-89b2-e80d67ef7bc6@googlegroups.com> <209e604c-1a18-43ff-9358-12fb784d3d4c@googlegroups.com> <168531a5-e5df-456d-a24e-db1235a4167f@googlegroups.com> Message-ID: <267cb0c3-d805-4954-8643-9125b0200995@googlegroups.com> Excellent, thank you. http://bugs.python.org/issue14573 -alfred From tjreedy at udel.edu Thu Oct 2 03:19:32 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 02 Oct 2014 03:19:32 -0400 Subject: Obscuring Python source from end users In-Reply-To: <8738b7t5hn.fsf@elektro.pacujo.net> References: <89381545-5edc-4f85-a4b8-86eebfdf34ee@googlegroups.com> <542946ec$0$12998$c3e8da3$5496439d@news.astraweb.com> <8738b7t5hn.fsf@elektro.pacujo.net> Message-ID: On 10/2/2014 1:17 AM, Marko Rauhamaa wrote: > Dan Stromberg : > >> On Mon, Sep 29, 2014 at 4:47 AM, Steven D'Aprano >>> Yes. Distribute the pyc files only. >> >> Yes, this is the way it's usually done. > > Has the .pyc file format stabilized? No. The cache files are binary specific and are so labelled. x.py is compiled, for instance, to x.cpython-34.pyc > A decade ago, my employer shippe > an application as .pyc files but had to ship the matching CPython binary > with it. -- Terry Jan Reedy From steve+comp.lang.python at pearwood.info Thu Oct 2 03:22:48 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 02 Oct 2014 17:22:48 +1000 Subject: Obscuring Python source from end users References: <89381545-5edc-4f85-a4b8-86eebfdf34ee@googlegroups.com> <542946ec$0$12998$c3e8da3$5496439d@news.astraweb.com> <8738b7t5hn.fsf@elektro.pacujo.net> Message-ID: <542cfd48$0$12999$c3e8da3$5496439d@news.astraweb.com> Marko Rauhamaa wrote: > Dan Stromberg : > >> On Mon, Sep 29, 2014 at 4:47 AM, Steven D'Aprano >>> Yes. Distribute the pyc files only. >> >> Yes, this is the way it's usually done. > > Has the .pyc file format stabilized? A decade ago, my employer shipped > an application as .pyc files but had to ship the matching CPython binary > with it. There is no promise that Python byte code or the format of .pyc files will be stable across minor releases. However, PEP 6 states that bugfix releases should have stable .pyc files. http://legacy.python.org/dev/peps/pep-0006/ So, you ought to expect that .pyc files will change when any of the following differs: - the hardware (e.g. 32- versus 64-bit, or ARM versus x86 processor); - the Python implementation (e.g. Stackless versus CPython); - the minor or major version number (e.g. 2.6 to 2.7, or 2.x to 3.x); but you can expect the .pyc files to remain compatible for: - the operating system (e.g. Windows, Mac, Linux); - bug-release versions (e.g. 2.7.1 to 2.7.2). Of course, you can distribute the Python executable, but it may be easier to just distribute a separate .pyc file for each minor release you wish to support. Here are some comments from one of the senior core developers: http://www.curiousefficiency.org/posts/2011/04/benefits-and-limitations-of-pyc-only.html -- Steven From dfnsonfsduifb at gmx.de Thu Oct 2 03:50:48 2014 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Thu, 02 Oct 2014 09:50:48 +0200 Subject: Obscuring Python source from end users In-Reply-To: References: <89381545-5edc-4f85-a4b8-86eebfdf34ee@googlegroups.com> Message-ID: On 29.09.2014 16:53, Sturla Molden wrote: > Chris Angelico wrote: > >>> I have a project that involves distributing Python code to users in an >>> organisation. Users do not interact directly with the Python code; they >>> only know this project as an Excel add-in. >>> >>> Now, internal audit takes exception in some cases if users are able to >>> see the source code. >> >> The solution is to fix your internal audit. > > +1 You two have obviously never worked at a large corporation or you would both realize how tremendously naive and unhelpful this "solution" is. Cheers, Johannes -- >> Wo hattest Du das Beben nochmal GENAU vorhergesagt? > Zumindest nicht ?ffentlich! Ah, der neueste und bis heute genialste Streich unsere gro?en Kosmologen: Die Geheim-Vorhersage. - Karl Kaos ?ber R?diger Thomas in dsa From steve+comp.lang.python at pearwood.info Thu Oct 2 03:59:50 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 02 Oct 2014 17:59:50 +1000 Subject: Function passed as an argument returns none References: <6bf1fc74-e40f-41f0-88b9-e4543c731e69@googlegroups.com> Message-ID: <542d05f7$0$12998$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Thu, Oct 2, 2014 at 12:29 PM, Rustom Mody > wrote: >> So by now you know there are 2 kinds of return: >> >> So the morals in short: >> >> 1. Stick to the return that works -- python's return statement -- >> and avoid the return that seems to work -- the print statement > > Please. There are not two types of return; there are two completely > different things here. Don't pretend that print is a bad form of > return. It isn't. I strongly agree with Chris here. The OP's problem was due to confusion between print and return, and the solution is to learn the difference between printing output to the screen and returning values from a function, and under what circumstances Python will automatically print said returned values as a convenience. Conflating the two as "2 kinds of return" is an invitation to even more confusion: "which was the 'good' return again?". While it is true that both return and print are related in the sense that they are both ways of having a function produce output, that's about the end of the similarity. One might as well say that assignment is a third kind of return, because one can assign output to a global variable. (Since print does not actually exit the current sub-routine, it definitively is not a kind of return.) -- Steven From steve+comp.lang.python at pearwood.info Thu Oct 2 04:11:58 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 02 Oct 2014 18:11:58 +1000 Subject: Clearing globals in CPython References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: <542d08cf$0$13006$c3e8da3$5496439d@news.astraweb.com> Peter Otten wrote: > Steven D'Aprano wrote: >> Obviously the easiest way to recover is to exit the current session and >> restart it, but as a challenge, can we recover from this state? > > $ python3 > Python 3.4.0 (default, Apr 11 2014, 13:05:11) > [GCC 4.8.2] on linux > Type "help", "copyright", "credits" or "license" for more information. >>>> globals().clear() >>>> import that > Traceback (most recent call last): > File "", line 1, in > ImportError: __import__ not found >>>> object = 1 .__class__.__bases__[0] >>>> Quitter = [c for c in object.__subclasses__() if c.__name__ == > "Quitter"][0] >>>> __builtins__ = Quitter.__call__.__globals__["__builtins__"] >>>> import this > The Zen of Python, by Tim Peters Nicely done! -- Steven From breamoreboy at yahoo.co.uk Thu Oct 2 04:30:20 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 02 Oct 2014 09:30:20 +0100 Subject: Clearing globals in CPython In-Reply-To: <542d08cf$0$13006$c3e8da3$5496439d@news.astraweb.com> References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> <542d08cf$0$13006$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 02/10/2014 09:11, Steven D'Aprano wrote: > Peter Otten wrote: > >> Steven D'Aprano wrote: > >>> Obviously the easiest way to recover is to exit the current session and >>> restart it, but as a challenge, can we recover from this state? >> >> $ python3 >> Python 3.4.0 (default, Apr 11 2014, 13:05:11) >> [GCC 4.8.2] on linux >> Type "help", "copyright", "credits" or "license" for more information. >>>>> globals().clear() >>>>> import that >> Traceback (most recent call last): >> File "", line 1, in >> ImportError: __import__ not found >>>>> object = 1 .__class__.__bases__[0] >>>>> Quitter = [c for c in object.__subclasses__() if c.__name__ == >> "Quitter"][0] >>>>> __builtins__ = Quitter.__call__.__globals__["__builtins__"] >>>>> import this >> The Zen of Python, by Tim Peters > > Nicely done! > Other than the Zen of Python what has Tim Peters ever done for us? Apart from... -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rosuav at gmail.com Thu Oct 2 04:32:10 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 2 Oct 2014 18:32:10 +1000 Subject: Obscuring Python source from end users In-Reply-To: References: <89381545-5edc-4f85-a4b8-86eebfdf34ee@googlegroups.com> Message-ID: On Thu, Oct 2, 2014 at 5:50 PM, Johannes Bauer wrote: > On 29.09.2014 16:53, Sturla Molden wrote: >> Chris Angelico wrote: >> >>>> I have a project that involves distributing Python code to users in an >>>> organisation. Users do not interact directly with the Python code; they >>>> only know this project as an Excel add-in. >>>> >>>> Now, internal audit takes exception in some cases if users are able to >>>> see the source code. >>> >>> The solution is to fix your internal audit. >> >> +1 > > You two have obviously never worked at a large corporation or you would > both realize how tremendously naive and unhelpful this "solution" is. Unhelpful? Perhaps, perhaps not. I would, however, distinguish between the two parts of my original response as follows: 1) The *solution* is to fix the audit process. 2) But here's one of several *work-arounds*. It may well be impossible to truly solve the problem, and I'm aware of that. But sometimes you need to point out that a pyc-only distribution is still distributing something very VERY close to the source code, and therefore it's nigh useless to talk of not distributing Python source. ChrisA From shivaji_tn at yahoo.com Thu Oct 2 04:46:13 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Thu, 2 Oct 2014 08:46:13 +0000 (UTC) Subject: Function passed as an argument returns none References: Message-ID: Hi All, Thank you everyone. This is fantastic - I post a query and go to sleep and by the time I get up there is already a nice little thread of discussion going on..... By the way, I sorted it with all your suggestions. def donuts(count): if count <= 9: #This had to be 9 instead of 5 as per the question req. return 'Number of donuts: {0}'.format(count) else: return 'Number of donuts: many' So to summarise what I learnt: * Just 'return' returns None - it is not related to what you print inside the function.If you want something specific out of a function return something specific. * return 'Number of donuts: ',count returns a tuple like: ('Number of donuts: ',9) * To just print the string without returning it as tuple , use string formatting. Thanks again, Shiva From rosuav at gmail.com Thu Oct 2 04:54:47 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 2 Oct 2014 18:54:47 +1000 Subject: Function passed as an argument returns none In-Reply-To: References: Message-ID: On Thu, Oct 2, 2014 at 6:46 PM, Shiva wrote: > Hi All, > > Thank you everyone. This is fantastic - I post a query and go to sleep and > by the time I get up there is already a nice little thread of discussion > going on..... Yeah, that's what python-list is like! Busy list, lots of opinionated people here... > By the way, I sorted it with all your suggestions. > > def donuts(count): > if count <= 9: #This had to be 9 instead of 5 as per the question req. > return 'Number of donuts: {0}'.format(count) > else: > return 'Number of donuts: many' Looks good! > So to summarise what I learnt: > > * Just 'return' returns None - it is not related to what you print inside > the function.If you want something specific out of a function return > something specific. Correct. As Steven and I said, printing is unrelated to returned values. Running off the end of a function, or using "return" on its own, is the same as "return None". > * return 'Number of donuts: ',count returns a tuple like: > ('Number of donuts: ',9) Right. The comma creates a tuple; the parentheses are printed on display, to make it easier to read, but it's the comma that does it. The comma has different meaning in some places, such as a function call (like print), but otherwise it'll create a tuple. > * To just print the string without returning it as tuple , use string > formatting. Yep! You're three for three. There are other ways to do things (you could use str() and concatenation, or percent formatting, or any number of ways), but they all do the same thing: they construct a single string, which you can then return. Incidentally, when you use .format() as you do there, the number 0 can be omitted - it's obvious to the parser, so you can shortcut it: >>> "Hello, {}!".format("world") 'Hello, world!' ChrisA From cl at isbd.net Thu Oct 2 05:43:48 2014 From: cl at isbd.net (cl at isbd.net) Date: Thu, 2 Oct 2014 10:43:48 +0100 Subject: Function passed as an argument returns none References: <6bf1fc74-e40f-41f0-88b9-e4543c731e69@googlegroups.com> <542d05f7$0$12998$c3e8da3$5496439d@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > between printing output to the screen and returning values from a function, > and under what circumstances Python will automatically print said returned > values as a convenience. Conflating the two as "2 kinds of return" is an To me automically printing something is a mis-feature! -- Chris Green ? From cl at isbd.net Thu Oct 2 05:40:33 2014 From: cl at isbd.net (cl at isbd.net) Date: Thu, 2 Oct 2014 10:40:33 +0100 Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: Travis Griggs wrote: > > > Sent from my iPhone > > > On Oct 1, 2014, at 04:12, Peter Otten <__peter__ at web.de> wrote: > > > > `lambda` is just a fancy way to define a function inline > > Not sure "fancy" is the correct adjective; more like syntactic tartness > (a less sweet version of syntactic sugar). > It throws me because 'lambda' simply has no meaning whatsoever for me, i.e. it's just a greek letter. So from my point of view it's like seeing 'epsilon' stuck in the middle of some code. It's not as if I'm new to programming either, I've been writing software professionally since the early 1970s, now retired. I have no formal computer training, there wasn't much in the way of university courses on computing in the 1960s, I have a degree in Electrical Engineering. Maybe that's why 'lambda' means nothing to me! :-) -- Chris Green ? From sachin.tiwari50 at gmail.com Thu Oct 2 05:49:05 2014 From: sachin.tiwari50 at gmail.com (sachin.tiwari50 at gmail.com) Date: Thu, 2 Oct 2014 02:49:05 -0700 (PDT) Subject: pyqt problem Message-ID: Hi I am learning pyqt, can any one help me to make instances of pushbutton wherever cursor will be clicked on canvas,like a circuit simulator where we add components on canvas just by left or right click. Thanks & Regards, Sachin From breamoreboy at yahoo.co.uk Thu Oct 2 07:00:20 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 02 Oct 2014 12:00:20 +0100 Subject: pyqt problem In-Reply-To: References: Message-ID: On 02/10/2014 10:49, sachin.tiwari50 at gmail.com wrote: > Hi > I am learning pyqt, can any one help me to make instances of pushbutton wherever cursor will be clicked on canvas,like a circuit simulator where we add components on canvas just by left or right click. > > Thanks & Regards, > Sachin > Please show us what you're tried so far and where it's going wrong, we're not here simply to write code for you. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From marko at pacujo.net Thu Oct 2 07:17:37 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 02 Oct 2014 14:17:37 +0300 Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: <878ukyu3e6.fsf@elektro.pacujo.net> cl at isbd.net: > It's not as if I'm new to programming either, I've been writing > software professionally since the early 1970s, now retired. I have no > formal computer training, there wasn't much in the way of university > courses on computing in the 1960s, I have a degree in Electrical > Engineering. Maybe that's why 'lambda' means nothing to me! :-) Lambda is special because it was thought of in the 1920's, well before there were any general-purpose computers. See Chapter 4. Marko From tomcsanyi at slovanet.sk Thu Oct 2 07:23:08 2014 From: tomcsanyi at slovanet.sk (Peter Tomcsanyi) Date: Thu, 2 Oct 2014 13:23:08 +0200 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk In-Reply-To: References: Message-ID: Thanks again for quick and informative reply. "Ned Deily" wrote in message news:nad-40CB03.10344701102014 at news.gmane.org... > The python.org 3.4.x series of installers will likely never change from > linking with Tk 8.5 by default. That would break a number of important > third-party Python packages that supply binary distributions built for > the python.org OS X pythons, like matplotlib. I respect your decision. But it surprises me because the Windows version of Python 3.4.1 already comes with Tcl/Tk 8.6. Does it mean that there are no such problems with matplotlib etc. in Windows? I think that one of the point when advertising Python is that it works accross the platforms, so keeping one platform (mac) "behind" for months seems to me going against the multiplatform promise of Python... > File an update request for the tcl and tk ports on the MacPorts tracker. > The project is usually very responsive to such requests. > https://trac.macports.org Thanks for the suggestion, I was considering asking them, but I did not know what is the best place/best way to do it. > Note that ActiveState hasn't yet released their versions of 8.6.2. I know, I am waching their Web page, too. > As Kevin Walzer points out, you *can* also build your own. I know. But *can* is quite subjective. Being a Windows-only user and programmer for a (too) long time, the idea that the end-user should compile something from sources is very unconfortable to me. So many things can go wrong it the process when working with toolchains that I am not familiar with. > Sorry for the delay! You do not need to appologize, I understand that it is extra work and that you did not promise it for sure. Best regards Peter From rustompmody at gmail.com Thu Oct 2 07:30:34 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 2 Oct 2014 04:30:34 -0700 (PDT) Subject: Function passed as an argument returns none In-Reply-To: References: <6bf1fc74-e40f-41f0-88b9-e4543c731e69@googlegroups.com> <542d05f7$0$12998$c3e8da3$5496439d@news.astraweb.com> Message-ID: <9efb2820-14b0-4950-8f1c-858248972819@googlegroups.com> On Thursday, October 2, 2014 3:18:22 PM UTC+5:30, wrote: > Steven D'Aprano wrote: > > between printing output to the screen and returning values from a function, > > and under what circumstances Python will automatically print said returned > > values as a convenience. Conflating the two as "2 kinds of return" is an > To me automatically printing something is a mis-feature! Hehe! Nice one! From rustompmody at gmail.com Thu Oct 2 07:38:32 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 2 Oct 2014 04:38:32 -0700 (PDT) Subject: Function passed as an argument returns none In-Reply-To: <542d05f7$0$12998$c3e8da3$5496439d@news.astraweb.com> References: <6bf1fc74-e40f-41f0-88b9-e4543c731e69@googlegroups.com> <542d05f7$0$12998$c3e8da3$5496439d@news.astraweb.com> Message-ID: <0aaba2f6-dfa4-4ec1-9460-a97c65f2e0eb@googlegroups.com> On Thursday, October 2, 2014 1:30:03 PM UTC+5:30, Steven D'Aprano wrote: > Chris Angelico wrote: > > wrote: > >> So by now you know there are 2 kinds of return: > >> So the morals in short: > >> 1. Stick to the return that works -- python's return statement -- > >> and avoid the return that seems to work -- the print statement > > Please. There are not two types of return; there are two completely > > different things here. Don't pretend that print is a bad form of > > return. It isn't. > I strongly agree with Chris here. The OP's problem was due to confusion > between print and return, and the solution is to learn the difference > between printing output to the screen and returning values from a function, > and under what circumstances Python will automatically print said returned > values as a convenience. Conflating the two as "2 kinds of return" is an > invitation to even more confusion: "which was the 'good' return again?". Right and the OP subject as well as post are essentially that conflation: > Any idea why 'None' is getting passed even though calling the donuts(4) > alone returns the expected value? And further if you consider that the explanations have aided, here's the most recent 'conclusion': > * return 'Number of donuts: ',count returns a tuple like: > ('Number of donuts: ',9) > * To just print the string without returning it as tuple , use string > formatting. You find this understanding satisfactory?? From sachin.tiwari50 at gmail.com Thu Oct 2 09:12:43 2014 From: sachin.tiwari50 at gmail.com (Sachin Tiwari) Date: Thu, 2 Oct 2014 06:12:43 -0700 (PDT) Subject: pyqt problem In-Reply-To: References: Message-ID: <44ed365f-8896-4d33-a44a-97801ea06434@googlegroups.com> On Thursday, October 2, 2014 3:19:22 PM UTC+5:30, Sachin Tiwari wrote: > Hi > > I am learning pyqt, can any one help me to make instances of pushbutton wherever cursor will be clicked on canvas,like a circuit simulator where we add components on canvas just by left or right click. > > > > Thanks & Regards, > > Sachin Hi swch = QPushButton('', self) swch.setToolTip('Switch ') swch.setCheckable(True) swch.setIcon(QIcon('sw.png')) swch.setIconSize(QSize(40,40)) swch.move(05, 25) swch.clicked.connect(self.switch) The above code will make a push button on canvas, now what I want when I will click on this button it get ready to drop anywhere on canvas by left click,I mean if I click 10 times on canvas 10 push button will be there. From lynto28 at gmail.com Thu Oct 2 09:24:25 2014 From: lynto28 at gmail.com (Didymus) Date: Thu, 2 Oct 2014 06:24:25 -0700 (PDT) Subject: Assignment Operators? Message-ID: <9669f493-cfa4-4a84-9f4a-ce3009926ca3@googlegroups.com> Hi All, I was wondering if someone could explain an assignment operator that I'm seeing in some code. As an example: >>> errors = False >>> errors |= 3 >>> errors 3 >>> errors |= 4 >>> errors 7 The '|=' operator, I read should be like a = a | b, but this appears to add the two numbers as long as it's more than the previous: >>> errors |= 5 >>> errors 7 Is there anywhere I can read up more on this and the other assignment operators and what/how they work. I got this off http://rgruet.free.fr/PQR27/PQR2.7.html I'm using: % python Python 2.7.5 (default, Sep 25 2014, 13:57:38) [GCC 4.8.3 20140911 (Red Hat 4.8.3-7)] on linux2 Thanks for any help in advance. Tom From rosuav at gmail.com Thu Oct 2 09:27:37 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 2 Oct 2014 23:27:37 +1000 Subject: Assignment Operators? In-Reply-To: <9669f493-cfa4-4a84-9f4a-ce3009926ca3@googlegroups.com> References: <9669f493-cfa4-4a84-9f4a-ce3009926ca3@googlegroups.com> Message-ID: On Thu, Oct 2, 2014 at 11:24 PM, Didymus wrote: >>>> errors = False >>>> errors |= 3 >>>> errors > 3 >>>> errors |= 4 >>>> errors > 7 > > The '|=' operator, I read should be like a = a | b, but this appears to add the two numbers as long as it's more than the previous: > >>>> errors |= 5 >>>> errors > 7 It is indeed (mostly) equivalent to "a = a | b". Do you understand what bitwise 'or' does? When you use False there, it's equivalent to zero. Everything after that is straight-forward bitwise or. http://en.wikipedia.org/wiki/Bitwise_operation#OR ChrisA From doug.farrell at gmail.com Thu Oct 2 09:30:24 2014 From: doug.farrell at gmail.com (writeson) Date: Thu, 2 Oct 2014 06:30:24 -0700 (PDT) Subject: Recommended hosting Message-ID: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> Hi all, I'd like to build a web site for myself, essentially a "vanity" web site to show off whatever web development skills I have, and perhaps do some blogging. I'm a Python developer, so I'd like to develop the site with the following stack: web applications written with Python and Flask, running as uwsgi applications. These would support dynamic HTML where needed, but mostly it would provide REST API's. static content delivered by Nginx Can anyone give me some recommendations for a good hosting company that would allow me work with the above tool set? I'm US based if that makes a difference. Thanks in advance! Doug From marco.buttu at gmail.com Wed Oct 1 12:39:20 2014 From: marco.buttu at gmail.com (Marco Buttu) Date: Wed, 01 Oct 2014 18:39:20 +0200 Subject: Clearing globals in CPython In-Reply-To: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: <542C2E38.6000906@oa-cagliari.inaf.it> On 01/10/2014 18:00, Steven D'Aprano wrote: > Out of curiosity, I ran: > > globals().clear() > > in the interactive interpreter. It broke much more than I expected! > Built-ins were no longer available, and import stopped working. Interesting... :D > Obviously the easiest way to recover is to exit the current session and > restart it, but as a challenge, can we recover from this state? >>> [].__class__.__module__ # It is a string... '__builtin__' So, I do not have any idea about how to get a module without importing something. Thanks for sharing :) -- Marco Buttu INAF-Osservatorio Astronomico di Cagliari Via della Scienza n. 5, 09047 Selargius (CA) Phone: 070 711 80 217 Email: mbuttu at oa-cagliari.inaf.it From mathematisch at gmail.com Thu Oct 2 09:38:05 2014 From: mathematisch at gmail.com (math math) Date: Thu, 2 Oct 2014 15:38:05 +0200 Subject: Thoughts on python classes to represent an ebook reader Message-ID: Thanks a lot. It is quite helpful to follow the thought process here. Another person gave the example of 'Calibre', but I've found it overwhelming and I couldn't find any UML diagram there (maybe not searched hard enough). Regards, Felix -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid.invalid Thu Oct 2 10:05:55 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 2 Oct 2014 14:05:55 +0000 (UTC) Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: On 2014-10-02, cl at isbd.net wrote: > Travis Griggs wrote: >> >> >> Sent from my iPhone >> >> > On Oct 1, 2014, at 04:12, Peter Otten <__peter__ at web.de> wrote: >> > >> > `lambda` is just a fancy way to define a function inline >> >> Not sure "fancy" is the correct adjective; more like syntactic tartness >> (a less sweet version of syntactic sugar). >> > It throws me because 'lambda' simply has no meaning whatsoever for me, > i.e. it's just a greek letter. > > So from my point of view it's like seeing 'epsilon' stuck in the > middle of some code. > > It's not as if I'm new to programming either, I've been writing > software professionally since the early 1970s, now retired. The use of "lamba" as a keyword to define an anonymous function is borrowed from Lisp which got it from Lambda calculus. http://en.wikipedia.org/wiki/Lambda_calculus -- Grant Edwards grant.b.edwards Yow! Is this going to at involve RAW human ecstasy? gmail.com From invalid at invalid.invalid Thu Oct 2 10:07:24 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 2 Oct 2014 14:07:24 +0000 (UTC) Subject: Clearing globals in CPython References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2014-10-01, Steven D'Aprano wrote: > Obviously the easiest way to recover is to exit the current session and > restart it, but as a challenge, can we recover from this state? Python apparently _does_ need a "restart command". -- Grant Edwards grant.b.edwards Yow! The PILLSBURY DOUGHBOY at is CRYING for an END to gmail.com BURT REYNOLDS movies!! From rosuav at gmail.com Thu Oct 2 10:12:49 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 3 Oct 2014 00:12:49 +1000 Subject: Clearing globals in CPython In-Reply-To: References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Oct 3, 2014 at 12:07 AM, Grant Edwards wrote: > On 2014-10-01, Steven D'Aprano wrote: > >> Obviously the easiest way to recover is to exit the current session and >> restart it, but as a challenge, can we recover from this state? > > Python apparently _does_ need a "restart command". Apparently not... you saw how easily Peter recovered :) ChrisA From invalid at invalid.invalid Thu Oct 2 10:23:07 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 2 Oct 2014 14:23:07 +0000 (UTC) Subject: Assignment Operators? References: <9669f493-cfa4-4a84-9f4a-ce3009926ca3@googlegroups.com> Message-ID: On 2014-10-02, Chris Angelico wrote: > On Thu, Oct 2, 2014 at 11:24 PM, Didymus wrote: >>>>> errors = False >>>>> errors |= 3 >>>>> errors >> 3 >>>>> errors |= 4 >>>>> errors >> 7 [...] > When you use False there, it's equivalent to zero. Why is that, you ask? [Or should, anyway] The fact that booleans when found in an arithmetic context are auto-magically coerced into integers with values 0,1 is a rather unpythonic wart which has it's historical roots in the time when Python didn't have a boolean type. People used integers instead and a lot of code bound the names True and False to the integers 1 and 0. When the boolean type was introduced it was decided that backwards compatibility with that practice was important. This resulted in two pragmatic but somewhat "impure" decisions: 1) In Python 2, True and False are not keywords, they're just global keywords that come pre-bound to the boolean singleton values of 'true' and 'false'. You can re-bind them to other objects: Python 2.7.7 (default, Aug 20 2014, 11:41:28) >>> False = 3.14159 >>> if False: print "False" ... False >>> >>> import math >>> math.cos(False) -0.9999999999964793 2) When used in an arithmetic context, boolean values would be converted into integer values 0,1. When Python 3 came out, 1) was dropped and True/False were "promoted" to keywords. But, 2) is still the case. -- Grant Edwards grant.b.edwards Yow! I guess you guys got at BIG MUSCLES from doing too gmail.com much STUDYING! From mail at timgolden.me.uk Thu Oct 2 10:29:33 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 02 Oct 2014 15:29:33 +0100 Subject: Recommended hosting In-Reply-To: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> References: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> Message-ID: <542D614D.4070102@timgolden.me.uk> On 02/10/2014 14:30, writeson wrote: > Hi all, > > I'd like to build a web site for myself, essentially a "vanity" web > site to show off whatever web development skills I have, and perhaps > do some blogging. I'm a Python developer, so I'd like to develop the > site with the following stack: > > web applications written with Python and Flask, running as uwsgi > applications. These would support dynamic HTML where needed, but > mostly it would provide REST API's. > > static content delivered by Nginx > > Can anyone give me some recommendations for a good hosting company > that would allow me work with the above tool set? I'm US based if > that makes a difference. WebFaction is definitely a good bet; I've used them for years and, aside from their developer-friendly features, their support is always prompt, responsive and helpful. I'm also starting to look at Python Anywhere but I don't know enough about their service to recommend them or not. (Altho' they've been active supporters of the Python world especially in the UK for quite a few years and they're basically smart and good guys). TJG From milsonmun at gmail.com Thu Oct 2 11:29:54 2014 From: milsonmun at gmail.com (Milson Munakami) Date: Thu, 2 Oct 2014 08:29:54 -0700 (PDT) Subject: How to set the global variable so that it can be accessed and released inside other methods Message-ID: <3bb9f56c-eff3-472e-8239-58b58cdb16be@googlegroups.com> Hi, I am newbie to Python, I am trying to use unittest and python. My python script is like this: #! /usr/bin/env python __author__ = 'Milson Munakami' __revision__ = '0.0.2' import json import urllib import httplib from scapy.all import * import unittest import os, sys, socket, struct, select, time from threading import Thread import logging import traceback from mininet.net import Mininet from mininet.node import OVSSwitch, OVSKernelSwitch, Controller, RemoteController from mininet.log import setLogLevel, info from mininet.cli import CLI class testFirewallS1( unittest.TestCase ): #I am trying to set net variable to global global net ###################### def setUp(self): self.controllerIp="127.0.0.1" self.switch = "00:00:00:00:00:00:00:01" self.destinationIp = "10.0.0.1" self.startTime_ = time.time() self.failed = False self.reportStatus_ = True self.name_ = "Firewall" self.log = logging.getLogger("unittest") self.CreateNet() self.SetPrecondition() def CreateNet(self): "Create an empty network and add nodes to it." net = Mininet( controller=RemoteController ) info( '*** Adding controller\n' ) net.addController( 'c0' , controller=RemoteController,ip= "127.0.0.1", port=6633) info( '*** Adding hosts\n' ) h1 = net.addHost( 'h1', ip='10.0.0.1' ) h2 = net.addHost( 'h2', ip='10.0.0.2' ) h3 = net.addHost( 'h3', ip='10.0.0.3' ) info( '*** Adding switch\n' ) s1 = net.addSwitch( 's1' ) info( '*** Creating links\n' ) net.addLink( h1, s1 ) net.addLink( h2, s1 ) net.addLink( h3, s1 ) info( '*** Starting network\n') net.start() def tearDown(self): if self.failed: return duration = time.time() - self.startTime_ self.cleanup(True) if self.reportStatus_: self.log.info("=== Test %s completed normally (%d sec)", self.name_, duration) def cleanup(self, success): sys.excepthook = sys.__excepthook__ self.SetFinalcondition() try: return except NameError: self.log.error("Exception hit during cleanup, bypassing:\n%s\n\n" % traceback.format_exc()) pass else: fail("Expected a NameError") def StatusFirewall(self): command = "http://%s:8080/wm/firewall/module/status/json" % self.controllerIp x = urllib.urlopen(command).read() parsedResult = json.loads(x) return parsedResult['result'] def CountFirewallRules(self): command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp x = urllib.urlopen(command).read() return x def CountFlowRules(self): command = "http://%s:8080/wm/core/switch/%s/flow/json" % (self.controllerIp, self.switch) x = urllib.urlopen(command).read() parsedResult = json.loads(x) content = parsedResult['00:00:00:00:00:00:00:01'] if content is None: return "[]" else: return str(content) def SetPrecondition(self): command = "http://%s:8080/wm/firewall/module/enable/json" % self.controllerIp urllib.urlopen(command).read() # cleanup all Firewall rules command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp x = urllib.urlopen(command).read() parsedResult = json.loads(x) for i in range(len(parsedResult)): params = "{\"ruleid\":\"%s\"}" % parsedResult[i]['ruleid'] command = "/wm/firewall/rules/json" url = "%s:8080" % self.controllerIp connection = httplib.HTTPConnection(url) connection.request("DELETE", command, params) connection.getresponse().read() # sleep for REST command to get processed to avoid racing time.sleep(5) def SetFinalcondition(self): command = "http://%s:8080/wm/firewall/module/disable/json" % self.controllerIp urllib.urlopen(command).read() # cleanup all Firewall rules command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp x = urllib.urlopen(command).read() parsedResult = json.loads(x) for i in range(len(parsedResult)): params = "{\"ruleid\":\"%s\"}" % parsedResult[i]['ruleid'] command = "/wm/firewall/rules/json" url = "%s:8080" % self.controllerIp connection = httplib.HTTPConnection(url) connection.request("DELETE", command, params) connection.getresponse().read() # sleep for REST command to get processed to avoid racing time.sleep(5) info( '*** Stopping network' ) net.stop() #Precondition Test def testPreConditionFirewall(self): self.assertTrue("enabled" in self.StatusFirewall()) self.assertTrue("[]" in self.CountFirewallRules()) self.assertEqual("[]",self.CountFlowRules(), "should be empty") #7 def testCreateFlow(self): info( '*** Testing network connecivity\n') net.pingAll() #Using Scapy #send(IP(dst="10.0.0.3")/ICMP()/"Hello World") #info( '*** Running CLI\n' ) #CLI( net ) # Post Conditions Validation self.assertTrue("enabled" in self.StatusFirewall()) self.assertTrue("[]" in self.CountFirewallRules()) self.assertNotEqual("[]",self.CountFlowRules(), "should not be empty rules cause it is added from Firewall with Action = []") #8 def testCountFlow(self): command = "http://%s:8080/wm/core/switch/all/flow/json" % self.controllerIp x = urllib.urlopen(command).read() self.assertEqual("[]",self.CountFlowRules(), "should be empty") # Post Conditions Validation self.assertTrue("enabled" in self.StatusFirewall()) self.assertTrue("[]" in self.CountFirewallRules()) self.assertEqual("[]",self.CountFlowRules(), "should be empty") #10 def testDeleteFlow(self): # sleep for REST command to get processed to avoid racing time.sleep(5) command = "http://%s:8080/wm/core/switch/all/flow/json" % self.controllerIp x = urllib.urlopen(command).read() self.assertEqual("[]",self.CountFlowRules(), "should be empty") # Post Conditions Validation self.assertTrue("enabled" in self.StatusFirewall()) self.assertTrue("[]" in self.CountFirewallRules()) self.assertEqual("[]",self.CountFlowRules(), "should be empty") def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(testFirewallS1)) return suite if __name__ == '__main__': logging.basicConfig(filename='/tmp/testfirewall.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s') logger=logging.getLogger(__name__) suiteFew = unittest.TestSuite() # Preconditions: suiteFew.addTest(testFirewallS1("testPreConditionFirewall")) # 7. Add one Flow Entry suiteFew.addTest(testFirewallS1("testCreateFlow")) # 8. Count Flow rules - empty suiteFew.addTest(testFirewallS1("testCountFlow")) # 9. Update a Flow Rule - Not Implemented due to Controller's Constraint # 10. wait till the time-stamp period to validate the flow is deleted with that time. suiteFew.addTest(testFirewallS1("testDeleteFlow")) #Testing the Test Cases Begins Here unittest.TextTestRunner(verbosity=2).run(suiteFew) #unittest.main() #unittest.TextTestRunner(verbosity=2).run(suite()) I tired to set a globla net variable inside the class and tring to access it from another methods like from def SetFinalcondition(self): and def testCreateFlow(self): but the error says:\ ERROR: testPreConditionFirewall (__main__.testFirewallS1) ---------------------------------------------------------------------- Traceback (most recent call last): File "mm.py", line 68, in tearDown self.cleanup(True) File "mm.py", line 74, in cleanup self.SetFinalcondition() File "mm.py", line 144, in SetFinalcondition net.stop() NameError: global name 'net' is not defined ====================================================================== ERROR: testCreateFlow (__main__.testFirewallS1) ---------------------------------------------------------------------- Traceback (most recent call last): File "mm.py", line 156, in testCreateFlow net.pingAll() NameError: global name 'net' is not defined ====================================================================== ERROR: testCreateFlow (__main__.testFirewallS1) ---------------------------------------------------------------------- Traceback (most recent call last): File "mm.py", line 68, in tearDown self.cleanup(True) File "mm.py", line 74, in cleanup self.SetFinalcondition() File "mm.py", line 144, in SetFinalcondition net.stop() NameError: global name 'net' is not defined ====================================================================== ERROR: testCountFlow (__main__.testFirewallS1) ---------------------------------------------------------------------- Traceback (most recent call last): File "mm.py", line 68, in tearDown self.cleanup(True) File "mm.py", line 74, in cleanup self.SetFinalcondition() File "mm.py", line 144, in SetFinalcondition net.stop() NameError: global name 'net' is not defined ====================================================================== ERROR: testDeleteFlow (__main__.testFirewallS1) ---------------------------------------------------------------------- Traceback (most recent call last): File "mm.py", line 68, in tearDown self.cleanup(True) File "mm.py", line 74, in cleanup self.SetFinalcondition() File "mm.py", line 144, in SetFinalcondition net.stop() NameError: global name 'net' is not defined How to fix it! Thanks for any help - Milson From rosuav at gmail.com Thu Oct 2 11:34:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 3 Oct 2014 01:34:29 +1000 Subject: How to set the global variable so that it can be accessed and released inside other methods In-Reply-To: <3bb9f56c-eff3-472e-8239-58b58cdb16be@googlegroups.com> References: <3bb9f56c-eff3-472e-8239-58b58cdb16be@googlegroups.com> Message-ID: On Fri, Oct 3, 2014 at 1:29 AM, Milson Munakami wrote: > #I am trying to set net variable to global > global net > > def CreateNet(self): > "Create an empty network and add nodes to it." > net = Mininet( controller=RemoteController ) You're almost there! All you have to do is move that global declaration into CreateNet itself. That's the only place where it's assigned to. I'm not sure why you have a class that sets up a global, though. It would be much more normal to use "self.net" everywhere instead. ChrisA From milsonmun at gmail.com Thu Oct 2 11:30:39 2014 From: milsonmun at gmail.com (Milson Munakami) Date: Thu, 2 Oct 2014 08:30:39 -0700 (PDT) Subject: Python unittesting method call issue In-Reply-To: References: Message-ID: On Saturday, September 27, 2014 5:26:00 PM UTC-6, Milson Munakami wrote: > I am trying to set the precondition for the test first prior to test other test cases. But as you can see in my code the precondition print command is not fired! Can you explain the cause and solution how to fire the code with in that method i.e. SetPreConditionFirewall() with setup variable self. in this fucntion. Here is my code: > > > > import json > > import urllib > > #import time > > #from util import * > > import httplib > > > > #import sys > > #from scapy.all import * > > > > import unittest > > > > import os, sys, socket, struct, select, time > > from threading import Thread > > > > import logging > > import traceback > > > > class testFirewallS1( unittest.TestCase ): > > def setUp(self): > > self.controllerIp="127.0.0.1" > > def tearDown(self): > > if self.failed: > > return > > duration = time.time() - self.startTime_ > > self.cleanup(True) > > if self.reportStatus_: > > self.log.info("=== Test %s completed normally (%d sec)", self.name_, duration) > > > > def cleanup(self, success): > > sys.excepthook = sys.__excepthook__ > > try: > > return > > except NameError: > > self.log.error("Exception hit during cleanup, bypassing:\n%s\n\n" % traceback.format_exc()) > > pass > > else: > > > > fail("Expected a NameError") > > > > def SetPreConditionFirewall(self): > > command = "http://%s:8080/wm/firewall/module/enable/json" % self.controllerIp > > urllib.urlopen(command).read() > > print self.controllerIp > > print "Test Pre-condition setting here" > > > > #Precondition Test > > def testPreConditionFirewall(self): > > print "Test pass" > > > > def suite(): > > > > suite = unittest.TestSuite() > > > > suite.addTest(unittest.makeSuite(testFirewallS1)) > > > > return suite > > > > > > if __name__ == '__main__': > > > > suiteFew = unittest.TestSuite() > > > > testFirewallS1("SetPreConditionFirewall") > > > > suiteFew.addTest(testFirewallS1("testPreConditionFirewall")) > > > > > > #Testing the Test Cases Begins Here > > unittest.TextTestRunner(verbosity=2).run(suiteFew) > > > > How can I do access that method on __main__ and how can that method can access the setup variable. > > > > Thanks Thanks :) From ian.g.kelly at gmail.com Thu Oct 2 12:00:32 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 2 Oct 2014 10:00:32 -0600 Subject: Assignment Operators? In-Reply-To: <9669f493-cfa4-4a84-9f4a-ce3009926ca3@googlegroups.com> References: <9669f493-cfa4-4a84-9f4a-ce3009926ca3@googlegroups.com> Message-ID: On Thu, Oct 2, 2014 at 7:24 AM, Didymus wrote: > The '|=' operator, I read should be like a = a | b, but this appears to add the two numbers as long as it's more than the previous: Note that: a = a or b and: a = a | b are different operations. It sounds like you're probably looking for the former, not the latter. From jtim.arnold at gmail.com Thu Oct 2 12:33:23 2014 From: jtim.arnold at gmail.com (Tim) Date: Thu, 2 Oct 2014 09:33:23 -0700 (PDT) Subject: Recommended hosting In-Reply-To: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> References: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> Message-ID: On Thursday, October 2, 2014 9:30:38 AM UTC-4, writeson wrote: > Hi all, > I'd like to build a web site for myself, essentially a "vanity" web site > web applications written with Python and Flask, running as uwsgi applications. These would support dynamic HTML where needed, but mostly it would provide REST API's. > static content delivered by Nginx Hi, I second webfaction--you can indeed run flask and nginx. They have good documentation and helpful support. I've used them over the years for Django sites, bottle applications, and plain static blog sites and never had a complaint. good luck! --Tim Arnold From cl at isbd.net Thu Oct 2 12:33:52 2014 From: cl at isbd.net (cl at isbd.net) Date: Thu, 2 Oct 2014 17:33:52 +0100 Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: Grant Edwards wrote: > On 2014-10-02, cl at isbd.net wrote: > > Travis Griggs wrote: > >> > >> > >> Sent from my iPhone > >> > >> > On Oct 1, 2014, at 04:12, Peter Otten <__peter__ at web.de> wrote: > >> > > >> > `lambda` is just a fancy way to define a function inline > >> > >> Not sure "fancy" is the correct adjective; more like syntactic tartness > >> (a less sweet version of syntactic sugar). > >> > > It throws me because 'lambda' simply has no meaning whatsoever for me, > > i.e. it's just a greek letter. > > > > So from my point of view it's like seeing 'epsilon' stuck in the > > middle of some code. > > > > It's not as if I'm new to programming either, I've been writing > > software professionally since the early 1970s, now retired. > > The use of "lamba" as a keyword to define an anonymous function is > borrowed from Lisp which got it from Lambda calculus. > > http://en.wikipedia.org/wiki/Lambda_calculus > Ah, so at least there is a reason for it, I'm far from being a mathematician though so it's not particularly obvious (for me anyway). -- Chris Green ? From breamoreboy at yahoo.co.uk Thu Oct 2 13:01:54 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 02 Oct 2014 18:01:54 +0100 Subject: Reticulated Python Message-ID: My apologies if this has been discussed before but I thought it may be of interest wphomes.soic.indiana.edu/jsiek/files/2014/08/retic-python-v3.pdf -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From dwightdhutto at gmail.com Thu Oct 2 13:33:11 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Thu, 2 Oct 2014 13:33:11 -0400 Subject: Recommended hosting In-Reply-To: References: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> Message-ID: You can go over to Zenfinite. I just so happen to know the owner; so if you see a nice plan you like, and it's a little pricey, I can see if the price can be dropped. On Thu, Oct 2, 2014 at 12:33 PM, Tim wrote: > On Thursday, October 2, 2014 9:30:38 AM UTC-4, writeson wrote: > > Hi all, > > I'd like to build a web site for myself, essentially a "vanity" web site > > > web applications written with Python and Flask, running as uwsgi > applications. These would support dynamic HTML where needed, but mostly it > would provide REST API's. > > static content delivered by Nginx > > Hi, I second webfaction--you can indeed run flask and nginx. They have > good documentation and helpful support. > > I've used them over the years for Django sites, bottle applications, and > plain static blog sites and never had a complaint. > > good luck! > --Tim Arnold > -- > https://mail.python.org/mailman/listinfo/python-list > -- Best Regards, David Hutto *CEO:* *Hutto Industrial Technologies Inc.http://www.zenfinite.com * http://www.payizm.com -Coming Soon! http://www.mylayawayplan.com -Coming Soon! -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Thu Oct 2 13:36:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 3 Oct 2014 03:36:01 +1000 Subject: Recommended hosting In-Reply-To: References: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> Message-ID: On Fri, Oct 3, 2014 at 3:33 AM, David Hutto wrote: > You can go over to Zenfinite. I just so happen to know the owner; so if you > see a nice plan you like, and it's a little pricey, I can see if the price > can be dropped. Or maybe you not so much *know* the owner as *are* the owner... given that it's your name all over the domain's whois info :) ChrisA From ethan at stoneleaf.us Thu Oct 2 13:45:15 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 02 Oct 2014 10:45:15 -0700 Subject: Reticulated Python In-Reply-To: References: Message-ID: <542D8F2B.4000904@stoneleaf.us> On 10/02/2014 10:01 AM, Mark Lawrence wrote: > > My apologies if this has been discussed before but I thought it may be of interest > wphomes.soic.indiana.edu/jsiek/files/2014/08/retic-python-v3.pdf Looks interesting, thanks for the link! -- ~Ethan~ From rustompmody at gmail.com Thu Oct 2 13:46:53 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 2 Oct 2014 10:46:53 -0700 (PDT) Subject: How to show a dictionary sorted on a value within its data? In-Reply-To: <878ukyu3e6.fsf@elektro.pacujo.net> References: <878ukyu3e6.fsf@elektro.pacujo.net> Message-ID: <35b68df9-3fe2-40f2-aa98-10f4de1ad435@googlegroups.com> On Thursday, October 2, 2014 4:47:50 PM UTC+5:30, Marko Rauhamaa wrote: > > It's not as if I'm new to programming either, I've been writing > > software professionally since the early 1970s, now retired. I have no > > formal computer training, there wasn't much in the way of university > > courses on computing in the 1960s, I have a degree in Electrical > > Engineering. Maybe that's why 'lambda' means nothing to me! :-) > Lambda is special because it was thought of in the 1920's, well before > there were any general-purpose computers. > References: <54hqfb-nan.ln1@chris.zbmc.eu> Message-ID: <542D9E69.5020704@davea.name> On 09/30/2014 10:55 AM, cl at isbd.net wrote: > Dave Angel wrote: >> .... >> name. And presumably you never remove an old name from the >> config. >> > The only things really likely to change (and may change regularly) are > the conversion factors, drifting voltage references etc. will > inevitably require these to be recalibrated every so often. Other > than that it's just typos or me deciding to change the name of > something. > Right there you have an important design decision. You then presumably have to have a way that each particular data point can record what configuration it's associated with. If you just change the calibration data externally, then all the old records are invalidated. > >> More troublesome is adding a new kind of data. You have to decide >> whether it's worth generalizing the code to anticipate the >> change, or just admit that the code will grow at that point and >> that old code won't deal with the new data. >> > There's a separate module for each input type (just ADC and 1-wire at > the moment), I don't anticipate any more though I suppose there might > be digital inputs one day. So a configuration [file] for each type > seems to make sense, generalising it would be more trouble than it's > worth I think. > > -- DaveA From ian.g.kelly at gmail.com Thu Oct 2 15:15:59 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 2 Oct 2014 13:15:59 -0600 Subject: How to show a dictionary sorted on a value within its data? In-Reply-To: References: Message-ID: On Thu, Oct 2, 2014 at 10:33 AM, wrote: > Ah, so at least there is a reason for it, I'm far from being a > mathematician though so it's not particularly obvious (for me anyway). You're not alone; a lot of people find the terminology not intuitive. Even GvR has publicly lamented the choice of keyword. From Seymore4Head at Hotmail.invalid Thu Oct 2 15:24:34 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 02 Oct 2014 15:24:34 -0400 Subject: Programming for Everybody (Python) Message-ID: Starts in 3 days Coursera.org About the Course This course is specifically designed to be a first programming course using the popular Python programming language. The pace of the course is designed to lead to mastery of each of the topics in the class. We will use simple data analysis as the programming exercises through the course. Understanding how to process data is valuable for everyone regardless of your career. This course might kindle an interest in more advanced programming courses or courses in web design and development or just provide skills when you are faced with a bunch of data that you need to analyze. You can do the programming assignments for the class using a web browser or using your personal computer. All required software for the course is free. Course Syllabus Week One: Introduction - Why we program? Week Two: Variables and Expressions Week Three: Conditional code Week Four: Functions Week Five: Loops and Iteration Week Six: Strings Week Seven: Files Week Eight: Lists Week Nine: Dictionaries Week Ten: Tuples Optional Topic: Regular Expressions and.........a free book. http://www.pythonlearn.com/book.php From invalid at invalid.invalid Thu Oct 2 15:36:38 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 2 Oct 2014 19:36:38 +0000 (UTC) Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: On 2014-10-02, cl at isbd.net wrote: > Grant Edwards wrote: >> On 2014-10-02, cl at isbd.net wrote: >> >> > It throws me because 'lambda' simply has no meaning whatsoever for me, >> > i.e. it's just a greek letter. >> > >> > So from my point of view it's like seeing 'epsilon' stuck in the >> > middle of some code. >> > >> > It's not as if I'm new to programming either, I've been writing >> > software professionally since the early 1970s, now retired. >> >> The use of "lamba" as a keyword to define an anonymous function is >> borrowed from Lisp which got it from Lambda calculus. >> >> http://en.wikipedia.org/wiki/Lambda_calculus > > Ah, so at least there is a reason for it, I'm far from being a > mathematician though so it's not particularly obvious (for me > anyway). We EE types did get complex number notation using "j" which the mathematicians find not particularly obvious. -- Grant Edwards grant.b.edwards Yow! It's a hole all the at way to downtown Burbank! gmail.com From juan0christian at gmail.com Thu Oct 2 15:51:18 2014 From: juan0christian at gmail.com (Juan Christian) Date: Thu, 2 Oct 2014 16:51:18 -0300 Subject: Programming for Everybody (Python) In-Reply-To: References: Message-ID: I recommend to everyone. Already took one of his courses on Coursera and he's amazing as a teacher. On Thu, Oct 2, 2014 at 4:24 PM, Seymore4Head wrote: > Starts in 3 days > Coursera.org > > About the Course > This course is specifically designed to be a first programming course > using the popular Python programming language. The pace of the course > is designed to lead to mastery of each of the topics in the class. We > will use simple data analysis as the programming exercises through the > course. Understanding how to process data is valuable for everyone > regardless of your career. This course might kindle an interest in > more advanced programming courses or courses in web design and > development or just provide skills when you are faced with a bunch of > data that you need to analyze. You can do the programming assignments > for the class using a web browser or using your personal computer. All > required software for the course is free. > Course Syllabus > Week One: Introduction - Why we program? > Week Two: Variables and Expressions > Week Three: Conditional code > Week Four: Functions > Week Five: Loops and Iteration > Week Six: Strings > Week Seven: Files > Week Eight: Lists > Week Nine: Dictionaries > Week Ten: Tuples > Optional Topic: Regular Expressions > > and.........a free book. > http://www.pythonlearn.com/book.php > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From drsalists at gmail.com Thu Oct 2 16:06:49 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Thu, 2 Oct 2014 13:06:49 -0700 Subject: How to show a dictionary sorted on a value within its data? In-Reply-To: References: Message-ID: On Thu, Oct 2, 2014 at 12:15 PM, Ian Kelly wrote: > On Thu, Oct 2, 2014 at 10:33 AM, wrote: >> Ah, so at least there is a reason for it, I'm far from being a >> mathematician though so it's not particularly obvious (for me anyway). > > You're not alone; a lot of people find the terminology not intuitive. > Even GvR has publicly lamented the choice of keyword. Was lambda almost removed from CPython 3.x? Anyway, pylint doesn't complain about a bare use of lambda, but it does complain about a map applied to a lambda or a filter applied to a lambda. Pylint says they could be replaced by a list comprehension, with the warning "deprecated-lambda". From rosuav at gmail.com Thu Oct 2 17:01:48 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 3 Oct 2014 07:01:48 +1000 Subject: How to show a dictionary sorted on a value within its data? In-Reply-To: References: Message-ID: On Fri, Oct 3, 2014 at 6:06 AM, Dan Stromberg wrote: > Anyway, pylint doesn't complain about a bare use of lambda, but it > does complain about a map applied to a lambda or a filter applied to a > lambda. Pylint says they could be replaced by a list comprehension, > with the warning "deprecated-lambda". That's not because lambda is a poor choice, but because map() in Py2 code can often be replaced with a list comp. (And map() in Py3 code can often be replaced by a genexp.) ChrisA From nad at acm.org Thu Oct 2 18:08:50 2014 From: nad at acm.org (Ned Deily) Date: Thu, 02 Oct 2014 15:08:50 -0700 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk References: Message-ID: In article , "Peter Tomcsanyi" wrote: > "Ned Deily" wrote in message > news:nad-40CB03.10344701102014 at news.gmane.org... > > The python.org 3.4.x series of installers will likely never change from > > linking with Tk 8.5 by default. That would break a number of important > > third-party Python packages that supply binary distributions built for > > the python.org OS X pythons, like matplotlib. > I respect your decision. > But it surprises me because the Windows version of Python 3.4.1 already > comes with Tcl/Tk 8.6. Does it mean that there are no such problems with > matplotlib etc. in Windows? The main issue is that, unlike MS and Windows, Apple has long shipped versions of Tcl and Tk with OS X. As I understand it, Apple even helped sponsor the writing of the newer Cocoa-based Tk that would also work on 64-bit systems after they decided to not extend the older Carbon APIs to 64-bit, making the original OS X native Carbon-based Tk problematic on newer Macs and releases of OS X. When the Cocoa Tk was first shipped with OS X 10.6, Tk 8.6 hadn't been released yet so they went with a backport to 8.5 and, for whatever reasons, Apple has been very slow to upgrade their 8.5.x Tk since then and have not shipped a 8.6 version yet. That leaves us in a bit of a quandary for the python.org installers. Ideally, we'd just like to continue to depend on an Apple-supplied version but even the most recent releases of OS X ship with serious bugs. Fortunately, it's been possible and long been our practice to ship the python.org installers Pythons built in such a way that, at run time, they will automatically use a compatible third-party Tcl and Tk, if present, otherwise fall back to the system version. By far, the leading third-party distributor of Tcl/Tk is ActiveState and they are actively involved in the development and maintenance of Tcl and Tk. But, their releases are not open-source and have a license that, while generous, do not permit totally unrestricted usage. Thus it is problematic to depend totally on their releases. So, to really support Tk 8.6, the only viable option at the moment would be for us to ship our own versions of Tk, like the Windows installer does. But it wouldn't be acceptable, IMO, to force other projects and users to migrate to 8.6 in the middle of a release cycle, e.g. 3.4.x or 2.7.x. Providing it as an option, though, would be OK. > I think that one of the point when advertising Python is that it works > accross the platforms, so keeping one platform (mac) "behind" for months > seems to me going against the multiplatform promise of Python... I don't think we mean to imply that all of the third-party libraries that Python is able to use are the same across all platforms. It depends on the platform and the practices there. The fact is that Tk 8.5 is still the de facto standard for OS X 10.6+ and Tk 8.4 is the de facto standard for OS X 10.5 and earlier systems, because that's what Apple has shipped. And that's why matplotlib et al and we still ship binary installers for OS X with 8.5 support. Third-party open source packages distributors, like MacPorts or Anaconda, can more easily move to newer versions of things, like Tk 8.6, because they provide complete solutions for many applications and libraries: they have ports for matplotlib, numpy, pythonx.x, Tk, and all other dependencies. The python.org installers have a much more limited scope. -- Ned Deily, nad at acm.org From steve+comp.lang.python at pearwood.info Thu Oct 2 19:16:55 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 03 Oct 2014 09:16:55 +1000 Subject: How to show a dictionary sorted on a value within its data? References: Message-ID: <542ddce8$0$12985$c3e8da3$5496439d@news.astraweb.com> Dan Stromberg wrote: > On Thu, Oct 2, 2014 at 12:15 PM, Ian Kelly wrote: >> On Thu, Oct 2, 2014 at 10:33 AM, wrote: >>> Ah, so at least there is a reason for it, I'm far from being a >>> mathematician though so it's not particularly obvious (for me anyway). >> >> You're not alone; a lot of people find the terminology not intuitive. >> Even GvR has publicly lamented the choice of keyword. > > Was lambda almost removed from CPython 3.x? I'm not sure about "almost", but there was serious discussion about removing it. > Anyway, pylint doesn't complain about a bare use of lambda, but it > does complain about a map applied to a lambda or a filter applied to a > lambda. Pylint says they could be replaced by a list comprehension, > with the warning "deprecated-lambda". The warning name is misleading, lambda is not deprecated. But stylistically, many people prefer to use a generator expression in place of map or filter: # instead of this map(lambda x: 2*x+1, values) # use this (2*x+1 for x in values) # instead of this filter(lambda x: x > 23, values) # use this (x for x in values if x > 23) -- Steven From steve+comp.lang.python at pearwood.info Thu Oct 2 20:10:53 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 03 Oct 2014 10:10:53 +1000 Subject: Function passed as an argument returns none References: <6bf1fc74-e40f-41f0-88b9-e4543c731e69@googlegroups.com> <542d05f7$0$12998$c3e8da3$5496439d@news.astraweb.com> <0aaba2f6-dfa4-4ec1-9460-a97c65f2e0eb@googlegroups.com> Message-ID: <542de98e$0$12981$c3e8da3$5496439d@news.astraweb.com> Rustom Mody wrote: > On Thursday, October 2, 2014 1:30:03 PM UTC+5:30, Steven D'Aprano wrote: >> Chris Angelico wrote: > Restoring the attribution line you removed: On Thu, Oct 2, 2014 at 12:29 PM, Rustom Mody wrote: >> >> So by now you know there are 2 kinds of return: >> >> So the morals in short: >> >> 1. Stick to the return that works -- python's return statement -- >> >> and avoid the return that seems to work -- the print statement [Chris] >> > Please. There are not two types of return; there are two completely >> > different things here. Don't pretend that print is a bad form of >> > return. It isn't. [Steven] >> I strongly agree with Chris here. The OP's problem was due to confusion >> between print and return, and the solution is to learn the difference >> between printing output to the screen and returning values from a >> function, and under what circumstances Python will automatically print >> said returned values as a convenience. Conflating the two as "2 kinds of >> return" is an invitation to even more confusion: "which was the 'good' >> return again?". [Rustom] > Right and the OP subject as well as post are essentially that conflation: > [allegedly Steven] >> Any idea why 'None' is getting passed even though calling the donuts(4) >> alone returns the expected value? I didn't write that. I don't know who you are quoting, but it isn't me. [Rustom] > And further if you consider that the explanations have aided, here's the > most recent 'conclusion': > [allegedly Steven] >> * return 'Number of donuts: ',count returns a tuple like: >> ('Number of donuts: ',9) And again, despite you attributing this to me, I did not write that. [allegedly Steven] >> * To just print the string without returning it as tuple , use string >> formatting. > [Rustom] > You find this understanding satisfactory?? And that's the third time in one post that you have attributed something written by somebody else to me. Rustom, I don't consider this blatant misattribution of other people's words to me is acceptable behaviour. I don't believe that somebody with your demonstrated competence at following email and usenet quoting conventions is unaware that you are attributing other people's comments to me. I would be inclined to chalk it up to an innocent mistake if not for the deliberate removal of the attribution line showing *your* advice to the OP to consider print one of "2 kinds of return". The original poster was confused about the difference between return and print. You replied by reinforcing that confusion, explicitly stating that print is a kind of return (it isn't). I don't hold that against you -- making an ill-thought-out comment in good faith is not a sin. But in your response to my criticism of that reply, you removed the attribution to yourself, then agreed with me ("Right") and implied that *your* comment about there being two kinds of return was the OP's confusion. To me, that looks like a deliberate, but feeble and pathetic, attempt to deflect criticism of your advice to the OP onto the OP. If true, that's a low and sordid thing to do. Your response to Shiva, the Original Poster: https://mail.python.org/pipermail/python-list/2014-October/678978.html Chris' response to you, with attribution line intact: https://mail.python.org/pipermail/python-list/2014-October/678979.html My response to Chris, with attribution line intact: https://mail.python.org/pipermail/python-list/2014-October/678988.html Your response to me, with attribution line deleted, and misattributing other people's comments to me: https://mail.python.org/pipermail/python-list/2014-October/679001.html -- Steven From rustompmody at gmail.com Thu Oct 2 21:49:13 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 2 Oct 2014 18:49:13 -0700 (PDT) Subject: Function passed as an argument returns none In-Reply-To: <542de98e$0$12981$c3e8da3$5496439d@news.astraweb.com> References: <6bf1fc74-e40f-41f0-88b9-e4543c731e69@googlegroups.com> <542d05f7$0$12998$c3e8da3$5496439d@news.astraweb.com> <0aaba2f6-dfa4-4ec1-9460-a97c65f2e0eb@googlegroups.com> <542de98e$0$12981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Friday, October 3, 2014 5:41:12 AM UTC+5:30, Steven D'Aprano wrote: > [Rustom] > > Right and the OP subject as well as post are essentially that conflation: > [allegedly Steven] > >> Any idea why 'None' is getting passed even though calling the donuts(4) > >> alone returns the expected value? > I didn't write that. I don't know who you are quoting, but it isn't me. Are you for real Steven?? Ok so there is no conventional attribution line because it was cut-pasted from elsewhere in the thread but there is a clear and unequivocal prefix of "OP subject as well as post". Why/how should there be any ambiguity that that is Shiva?? Since you are merrily throwing around mis-attribution charges please explain the logic by which "Steven" == "OP" Or are not aware OP means 'original post(er)'? Likewise all the below '[allegedly Steven]s'... > [Rustom] > > And further if you consider that the explanations have aided, here's the > > most recent 'conclusion': > [allegedly Steven] > >> * return 'Number of donuts: ',count returns a tuple like: > >> ('Number of donuts: ',9) > And again, despite you attributing this to me, I did not write that. > [allegedly Steven] > >> * To just print the string without returning it as tuple , use string > >> formatting. > [Rustom] > > You find this understanding satisfactory?? > And that's the third time in one post that you have attributed something > written by somebody else to me. > Rustom, I don't consider this blatant misattribution of other people's words > to me is acceptable behaviour. And what kind of conversation is it if I ask you > > You find this understanding satisfactory?? as a question ABOUT you? How you are able to confuse a question addressed TO you into a question ABOUT you is beyond me. Did you run out of your morning coffee or somethin? From rosuav at gmail.com Thu Oct 2 22:08:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 3 Oct 2014 12:08:36 +1000 Subject: Function passed as an argument returns none In-Reply-To: References: <6bf1fc74-e40f-41f0-88b9-e4543c731e69@googlegroups.com> <542d05f7$0$12998$c3e8da3$5496439d@news.astraweb.com> <0aaba2f6-dfa4-4ec1-9460-a97c65f2e0eb@googlegroups.com> <542de98e$0$12981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Oct 3, 2014 at 11:49 AM, Rustom Mody wrote: > Ok so there is no conventional attribution line because it was > cut-pasted from elsewhere in the thread but there is a clear > and unequivocal prefix of "OP subject as well as post". When I respond to this part... > Why/how should there be any ambiguity that that is Shiva?? ... and then to this, the normal assumption is that, since both are at the same indentation level, they're both covered by the same heading line. Compare: def rustom(): yield "... there is no conventional ..." yield "... elsewhere in the thread ..." yield "... unequivocal ..." # I respond to this... yield "... any ambiguity ..." # Is there any expectation that the above line of code isn't part of the same function? And there IS an unequivocal prefix of "OP subject as well as post". It looks like this: On Thu, Oct 2, 2014 at 8:37 AM, Shiva wrote: > Any idea why 'None' is getting passed even though calling the donuts(4) > alone returns the expected value? And there's even an unambiguous way to indicate that you're responding to the original poster, but not the original post. Watch! On Thu, Oct 2, 2014 at 6:46 PM, Shiva wrote: > * return 'Number of donuts: ',count returns a tuple like: > ('Number of donuts: ',9) I can correctly attribute every piece that I respond to. It's really not hard. In this particular case, I opened two additional replies, and copied and pasted the bits I want into this reply. Some people short-cut it, when they're responding to separate posts, and just do something like this: [Rustom Mode] > Are you for real Steven?? Complete with a demonstration of what happens all too often when things are done manually: a spelling error in the attribution line. It's still unambiguous as to who wrote what, though a little less helpful as regards chronology. Attribution lines are part of being honest about who said what. I wouldn't say that your post was evidence of malicious intent, but it was sloppiness that led to an easily misunderstood post. On rereading, I can see that you did try to indicate (by your text) that it was meant to be followed by the OP's words, but you didn't put that into the structure, and you certainly didn't distinguish between the original post and the one made a little bit later. Please, if you don't want to be called out for misattribution, just be a bit more careful. It doesn't take a huge amount of effort. ChrisA From rosuav at gmail.com Thu Oct 2 22:44:32 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 3 Oct 2014 12:44:32 +1000 Subject: How to show a dictionary sorted on a value within its data? In-Reply-To: <542ddce8$0$12985$c3e8da3$5496439d@news.astraweb.com> References: <542ddce8$0$12985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Oct 3, 2014 at 9:16 AM, Steven D'Aprano wrote: >> Anyway, pylint doesn't complain about a bare use of lambda, but it >> does complain about a map applied to a lambda or a filter applied to a >> lambda. Pylint says they could be replaced by a list comprehension, >> with the warning "deprecated-lambda". > > The warning name is misleading, lambda is not deprecated. But stylistically, > many people prefer to use a generator expression in place of map or filter: > > # instead of this > map(lambda x: 2*x+1, values) > > # use this > (2*x+1 for x in values) > > # instead of this > filter(lambda x: x > 23, values) > > # use this > (x for x in values if x > 23) Don't forget that your equivalencies are based on the Py3 map/filter, which return non-list iterables. There's no really convenient equivalent to the map() usage of "call this function with each of these args, and discard the return values", as it looks very odd to do a list comp for nothing: [print(x) for x in list_of_strings] Short of borrowing Pike's automap syntax: print(list_of_strings[*]) there's really not much that's better than the original map() call. On the other hand, there aren't actually all that many times when I've needed to do this, and the simple for loop generally suffices: for x in list_of_strings: print(x) So it's not a huge deal. ChrisA From miki.tebeka at gmail.com Fri Oct 3 00:46:53 2014 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Thu, 2 Oct 2014 21:46:53 -0700 (PDT) Subject: Error from pandas.io.data import DataReader In-Reply-To: <3efaa62e-46e0-4eee-a013-fdd135503014@googlegroups.com> References: <3efaa62e-46e0-4eee-a013-fdd135503014@googlegroups.com> Message-ID: Greetings, > I am trying to run this snippet of code. > > from pandas.io.data import DataReader > ... > > I keep getting this error. > > Traceback (most recent call last): > > File "C:\Python27\download_dow.py", line 1, in > > from pandas.io.data import DataReader > > ImportError: No module named pandas.io.data * Do you have pandas installed? (Does "import pandas" work?) * If it is installed, what version do you have? ( "print(pandas.__version__") HTH, -- Miki From stefan_ml at behnel.de Fri Oct 3 01:26:20 2014 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 03 Oct 2014 07:26:20 +0200 Subject: Clearing globals in CPython In-Reply-To: References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Angelico schrieb am 02.10.2014 um 16:12: > On Fri, Oct 3, 2014 at 12:07 AM, Grant Edwards wrote: >> On 2014-10-01, Steven D'Aprano wrote: >> >>> Obviously the easiest way to recover is to exit the current session and >>> restart it, but as a challenge, can we recover from this state? >> >> Python apparently _does_ need a "restart command". > > Apparently not... you saw how easily Peter recovered :) Right. All we need is a builtin function for that recovery code. Stefan From vhnguyenn at yahoo.com Fri Oct 3 01:34:04 2014 From: vhnguyenn at yahoo.com (Viet Nguyen) Date: Thu, 2 Oct 2014 22:34:04 -0700 (PDT) Subject: Is there a way to display source code for Python function? Message-ID: <2d5b0e56-992a-481c-9a8b-eb546cd9ac2e@googlegroups.com> Hi, When I am debug mode, is there some command which will help display the source code for a Python function of interest? Much like you'd use "info proc" to display contents of Tcl proc. Thanks, Viet From ian.g.kelly at gmail.com Fri Oct 3 01:46:25 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 2 Oct 2014 23:46:25 -0600 Subject: Is there a way to display source code for Python function? In-Reply-To: <2d5b0e56-992a-481c-9a8b-eb546cd9ac2e@googlegroups.com> References: <2d5b0e56-992a-481c-9a8b-eb546cd9ac2e@googlegroups.com> Message-ID: On Thu, Oct 2, 2014 at 11:34 PM, Viet Nguyen wrote: > Hi, > > When I am debug mode, is there some command which will help display the source code for a Python function of interest? Much like you'd use "info proc" to display contents of Tcl proc. > > Thanks, > Viet You can use inspect.getsource() to get the source code for a function, class, or module. The source must be available at whatever location the module was imported from, and of course it won't work for anything implemented in C. From vhnguyenn at yahoo.com Fri Oct 3 02:09:04 2014 From: vhnguyenn at yahoo.com (Viet Nguyen) Date: Thu, 2 Oct 2014 23:09:04 -0700 (PDT) Subject: Is there a way to display source code for Python function? In-Reply-To: <2d5b0e56-992a-481c-9a8b-eb546cd9ac2e@googlegroups.com> References: <2d5b0e56-992a-481c-9a8b-eb546cd9ac2e@googlegroups.com> Message-ID: On Thursday, October 2, 2014 10:34:15 PM UTC-7, Viet Nguyen wrote: > Hi, > > > > When I am debug mode, is there some command which will help display the source code for a Python function of interest? Much like you'd use "info proc" to display contents of Tcl proc. > > > > Thanks, > > Viet I tried this: >>> def func(a): ... a = 'abcd' >>> inspect.getsource(func) Traceback (most recent call last): File "", line 1, in File "/sw/packages/python/current/lib/python2.7/inspect.py", line 701, in getsource lines, lnum = getsourcelines(object) File "/sw/packages/python/current/lib/python2.7/inspect.py", line 690, in getsourcelines lines, lnum = findsource(object) File "/sw/packages/python/current/lib/python2.7/inspect.py", line 538, in findsource raise IOError('could not get source code') IOError: could not get source code >>> inspect.getsourcelines(func) Traceback (most recent call last): File "", line 1, in File "/sw/packages/python/current/lib/python2.7/inspect.py", line 690, in getsourcelines lines, lnum = findsource(object) File "/sw/packages/python/current/lib/python2.7/inspect.py", line 538, in findsource raise IOError('could not get source code') IOError: could not get source code What is wrong? Thanks, Viet From vhnguyenn at yahoo.com Fri Oct 3 02:13:12 2014 From: vhnguyenn at yahoo.com (Viet Nguyen) Date: Thu, 2 Oct 2014 23:13:12 -0700 (PDT) Subject: Is there a way to display source code for Python function? In-Reply-To: References: <2d5b0e56-992a-481c-9a8b-eb546cd9ac2e@googlegroups.com> Message-ID: <5cb0f9ec-b0b2-4350-a666-27f484af4720@googlegroups.com> On Thursday, October 2, 2014 10:47:28 PM UTC-7, Ian wrote: > On Thu, Oct 2, 2014 at 11:34 PM, Viet Nguyen > > wrote: > > > Hi, > > > > > > When I am debug mode, is there some command which will help display the source code for a Python function of interest? Much like you'd use "info proc" to display contents of Tcl proc. > > > > > > Thanks, > > > Viet > > > > You can use inspect.getsource() to get the source code for a function, > > class, or module. The source must be available at whatever location > > the module was imported from, and of course it won't work for anything > > implemented in C. Hi, I tried: def func(a): a = 'abcd' >>> inspect.getsource(func) Traceback (most recent call last): File "", line 1, in File "/sw/packages/python/current/lib/python2.7/inspect.py", line 701, in getsource lines, lnum = getsourcelines(object) File "/sw/packages/python/current/lib/python2.7/inspect.py", line 690, in getsourcelines lines, lnum = findsource(object) File "/sw/packages/python/current/lib/python2.7/inspect.py", line 538, in findsource raise IOError('could not get source code') IOError: could not get source code What is wrong? Thanks, Viet From auriocus at gmx.de Fri Oct 3 02:57:01 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Fri, 03 Oct 2014 08:57:01 +0200 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk In-Reply-To: References: Message-ID: Am 03.10.14 00:08, schrieb Ned Deily: > So, to really support > Tk 8.6, the only viable option at the moment would be for us to ship our > own versions of Tk, like the Windows installer does. But it wouldn't be > acceptable, IMO, to force other projects and users to migrate to 8.6 in > the middle of a release cycle, e.g. 3.4.x or 2.7.x. Providing it as an > option, though, would be OK. Hmm, I'm not sure that the other projects would need an update. In Tcl world, there is the concept of stub libraries, an extra level of indirect linking provided by both the Tcl and Tk core. If the extensions link to the stub library (the standard way), they can be loaded into any later version of Tcl and do not directly depend on libtcl or libtk. If the extensions link directly to libtcl, they are either broken or very special (providing one's own interpreter, doing nasty stuff with internals etc.) Christian From __peter__ at web.de Fri Oct 3 03:47:31 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 03 Oct 2014 09:47:31 +0200 Subject: Is there a way to display source code for Python function? References: <2d5b0e56-992a-481c-9a8b-eb546cd9ac2e@googlegroups.com> Message-ID: Viet Nguyen wrote: > On Thursday, October 2, 2014 10:34:15 PM UTC-7, Viet Nguyen wrote: >> Hi, >> >> >> >> When I am debug mode, is there some command which will help display the >> source code for a Python function of interest? Much like you'd use "info >> proc" to display contents of Tcl proc. >> >> >> >> Thanks, >> >> Viet > > I tried this: >>>> def func(a): > ... a = 'abcd' > > >>>> inspect.getsource(func) > Traceback (most recent call last): > File "", line 1, in > File "/sw/packages/python/current/lib/python2.7/inspect.py", line 701, > in getsource > lines, lnum = getsourcelines(object) > File "/sw/packages/python/current/lib/python2.7/inspect.py", line 690, > in getsourcelines > lines, lnum = findsource(object) > File "/sw/packages/python/current/lib/python2.7/inspect.py", line 538, > in findsource > raise IOError('could not get source code') > IOError: could not get source code > >>>> inspect.getsourcelines(func) > Traceback (most recent call last): > File "", line 1, in > File "/sw/packages/python/current/lib/python2.7/inspect.py", line 690, > in getsourcelines > lines, lnum = findsource(object) > File "/sw/packages/python/current/lib/python2.7/inspect.py", line 538, > in findsource > raise IOError('could not get source code') > IOError: could not get source code > > What is wrong? The source of func is compiled and immediately discarded by the interactive interpreter. inspect.getsource() only works if the source code is available (as a module): $ cat ham.py def spam(): return 42 $ python3 Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import ham, inspect >>> print(inspect.getsource(ham.spam)) def spam(): return 42 >>> There is an alternative interactive interpreter called ipython that allows you to retrieve a function definition: In [1]: def foo(): ...: return bar ...: In [2]: %psource foo def foo(): return bar In [3]: From steve at pearwood.info Fri Oct 3 03:55:36 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 03 Oct 2014 07:55:36 GMT Subject: How to show a dictionary sorted on a value within its data? References: <542ddce8$0$12985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <542e5677$0$2916$c3e8da3$76491128@news.astraweb.com> On Fri, 03 Oct 2014 12:44:32 +1000, Chris Angelico wrote: > On Fri, Oct 3, 2014 at 9:16 AM, Steven D'Aprano > wrote: >>> Anyway, pylint doesn't complain about a bare use of lambda, but it >>> does complain about a map applied to a lambda or a filter applied to a >>> lambda. Pylint says they could be replaced by a list comprehension, >>> with the warning "deprecated-lambda". >> >> The warning name is misleading, lambda is not deprecated. But >> stylistically, many people prefer to use a generator expression in >> place of map or filter: >> >> # instead of this >> map(lambda x: 2*x+1, values) >> >> # use this >> (2*x+1 for x in values) >> >> # instead of this >> filter(lambda x: x > 23, values) >> >> # use this >> (x for x in values if x > 23) > > Don't forget that your equivalencies are based on the Py3 map/filter, Dan did ask about Python 3.x :-) > which return non-list iterables. There's no really convenient equivalent > to the map() usage of "call this function with each of these args, and > discard the return values", as it looks very odd to do a list comp for > nothing: map doesn't discard the return values. It accumulates them in a list, or yields them in a list comp. > [print(x) for x in list_of_strings] That would be an abuse of a list comprehension, generator expression or map since it will produce a whole lot of None values. If you really want to discard the return values, put them in a for-loop: for s in list_of_strings: print(s) > Short of borrowing Pike's automap syntax: > > print(list_of_strings[*]) you mean something like this perhaps? print(*list_of_strings, sep='\n') > there's really not much that's better than the original map() call. On > the other hand, there aren't actually all that many times when I've > needed to do this, and the simple for loop generally suffices: > > for x in list_of_strings: print(x) Exactly. -- Steven From rosuav at gmail.com Fri Oct 3 04:09:50 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 3 Oct 2014 18:09:50 +1000 Subject: How to show a dictionary sorted on a value within its data? In-Reply-To: <542e5677$0$2916$c3e8da3$76491128@news.astraweb.com> References: <542ddce8$0$12985$c3e8da3$5496439d@news.astraweb.com> <542e5677$0$2916$c3e8da3$76491128@news.astraweb.com> Message-ID: On Fri, Oct 3, 2014 at 5:55 PM, Steven D'Aprano wrote: >> which return non-list iterables. There's no really convenient equivalent >> to the map() usage of "call this function with each of these args, and >> discard the return values", as it looks very odd to do a list comp for >> nothing: > > map doesn't discard the return values. It accumulates them in a list, or > yields them in a list comp. Sure, but I've seen it used in various places to call functions where you don't care about the return values. Technically it's identical to the list comp, but somehow it's seen as less of an abuse. >> Short of borrowing Pike's automap syntax: >> >> print(list_of_strings[*]) > > you mean something like this perhaps? > > print(*list_of_strings, sep='\n') Well, no. In that one specific example, it happens to be possible to pass all the args to one print() call and get the same effect, but imagine some function that doesn't have that particular feature. (I just used print for simplicity.) >> there's really not much that's better than the original map() call. On >> the other hand, there aren't actually all that many times when I've >> needed to do this, and the simple for loop generally suffices: >> >> for x in list_of_strings: print(x) > > Exactly. Yeah. That's the normal way to do things. I'm not entirely sure why I keep seeing map() for that; there's probably a justification in functional programming languages, or something. ChrisA From vhnguyenn at yahoo.com Fri Oct 3 04:16:17 2014 From: vhnguyenn at yahoo.com (Viet Nguyen) Date: Fri, 3 Oct 2014 01:16:17 -0700 (PDT) Subject: Is there a way to display source code for Python function? In-Reply-To: References: <2d5b0e56-992a-481c-9a8b-eb546cd9ac2e@googlegroups.com> Message-ID: <644f93f2-38c8-4d40-b49f-587150b0ff33@googlegroups.com> On Friday, October 3, 2014 12:48:08 AM UTC-7, Peter Otten wrote: > Viet Nguyen wrote: > > > > > On Thursday, October 2, 2014 10:34:15 PM UTC-7, Viet Nguyen wrote: > > >> Hi, > > >> > > >> > > >> > > >> When I am debug mode, is there some command which will help display the > > >> source code for a Python function of interest? Much like you'd use "info > > >> proc" to display contents of Tcl proc. > > >> > > >> > > >> > > >> Thanks, > > >> > > >> Viet > > > > > > I tried this: > > >>>> def func(a): > > > ... a = 'abcd' > > > > > > > > >>>> inspect.getsource(func) > > > Traceback (most recent call last): > > > File "", line 1, in > > > File "/sw/packages/python/current/lib/python2.7/inspect.py", line 701, > > > in getsource > > > lines, lnum = getsourcelines(object) > > > File "/sw/packages/python/current/lib/python2.7/inspect.py", line 690, > > > in getsourcelines > > > lines, lnum = findsource(object) > > > File "/sw/packages/python/current/lib/python2.7/inspect.py", line 538, > > > in findsource > > > raise IOError('could not get source code') > > > IOError: could not get source code > > > > > >>>> inspect.getsourcelines(func) > > > Traceback (most recent call last): > > > File "", line 1, in > > > File "/sw/packages/python/current/lib/python2.7/inspect.py", line 690, > > > in getsourcelines > > > lines, lnum = findsource(object) > > > File "/sw/packages/python/current/lib/python2.7/inspect.py", line 538, > > > in findsource > > > raise IOError('could not get source code') > > > IOError: could not get source code > > > > > > What is wrong? > > > > The source of func is compiled and immediately discarded by the interactive > > interpreter. inspect.getsource() only works if the source code is available > > (as a module): > > > > $ cat ham.py > > def spam(): > > return 42 > > $ python3 > > Python 3.4.0 (default, Apr 11 2014, 13:05:11) > > [GCC 4.8.2] on linux > > Type "help", "copyright", "credits" or "license" for more information. > > >>> import ham, inspect > > >>> print(inspect.getsource(ham.spam)) > > def spam(): > > return 42 > > > > >>> > > > > There is an alternative interactive interpreter called ipython that allows > > you to retrieve a function definition: > > > > In [1]: def foo(): > > ...: return bar > > ...: > > > > In [2]: %psource foo > > def foo(): > > return bar > > > > In [3]: Thanks Peter! From shivaji_tn at yahoo.com Fri Oct 3 07:35:38 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Fri, 3 Oct 2014 11:35:38 +0000 (UTC) Subject: Returning a List Message-ID: Hi All, I might be doing something really silly here, but I can't seem to spot it: def front_x(words): b=[] c=[] for a in words: if a[0] == 'x': b.append(a) else: c.append(a) b = sorted(b) c = sorted(c) d= b+c print('d = ',d) #return b+c return d front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']) Why is return d or return b+c not returning anything?? The d's value is confirmed by the print statement. Thanks, Shiva. From rosuav at gmail.com Fri Oct 3 07:38:30 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 3 Oct 2014 21:38:30 +1000 Subject: Returning a List In-Reply-To: References: Message-ID: On Fri, Oct 3, 2014 at 9:35 PM, Shiva wrote: > Why is return d or return b+c not returning anything?? > On what basis do you believe it's not returning anything? When you call it, down below, you're ignoring its return value. I expect it's returning just fine, but you then do nothing with it. ChrisA From shivaji_tn at yahoo.com Fri Oct 3 07:45:49 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Fri, 3 Oct 2014 11:45:49 +0000 (UTC) Subject: Returning a List References: Message-ID: Chris Angelico gmail.com> writes: > > On Fri, Oct 3, 2014 at 9:35 PM, Shiva > yahoo.com.dmarc.invalid> wrote: > > Why is return d or return b+c not returning anything?? > > > > On what basis do you believe it's not returning anything? When you > call it, down below, you're ignoring its return value. I expect it's > returning just fine, but you then do nothing with it. > > ChrisA > I wrongly thought calling the function was enough. Looks like the call is just a placeholder for the returned value. Need to print it out. Thanks!! From breamoreboy at yahoo.co.uk Fri Oct 3 08:04:52 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 03 Oct 2014 13:04:52 +0100 Subject: Is there a way to display source code for Python function? In-Reply-To: <644f93f2-38c8-4d40-b49f-587150b0ff33@googlegroups.com> References: <2d5b0e56-992a-481c-9a8b-eb546cd9ac2e@googlegroups.com> <644f93f2-38c8-4d40-b49f-587150b0ff33@googlegroups.com> Message-ID: On 03/10/2014 09:16, Viet Nguyen wrote: [snip normal google stuff] Would you please access this list via https://mail.python.org/mailman/listinfo/python-list or read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing and single line paragraphs, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From marco.nawijn at colosso.nl Fri Oct 3 09:02:34 2014 From: marco.nawijn at colosso.nl (marco.nawijn at colosso.nl) Date: Fri, 3 Oct 2014 06:02:34 -0700 (PDT) Subject: Recommended hosting In-Reply-To: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> References: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> Message-ID: On Thursday, October 2, 2014 3:30:38 PM UTC+2, writeson wrote: > Hi all, > > > > I'd like to build a web site for myself, essentially a "vanity" web site to show off whatever web development skills I have, and perhaps do some blogging. I'm a Python developer, so I'd like to develop the site with the following stack: > > > > web applications written with Python and Flask, running as uwsgi applications. These would support dynamic HTML where needed, but mostly it would provide REST API's. > > > > static content delivered by Nginx > > > > Can anyone give me some recommendations for a good hosting company that would allow me work with the above tool set? I'm US based if that makes a difference. > > > > Thanks in advance! > > Doug Doug, Also don't forget "the new kid on the block" Docker! So, you can build your webapp locally on your machine, deploy it (also locally) in a Docker container. Test it and then deploy it in the cloud. You have lots of options for this. I am the process of doing this myself and I like it a lot! Marco From cl at isbd.net Fri Oct 3 10:08:43 2014 From: cl at isbd.net (cl at isbd.net) Date: Fri, 3 Oct 2014 15:08:43 +0100 Subject: Egg help wanted Message-ID: I have installed (using easy_install) a little utility, it seems to have installed just the top-level python script in /usr/local/bin which in turn uses load_entry_point() to run the actual code. As far as I can see the code and support files remain in the .egg file in /usr/local/lib/python2.7/dist-packages, is this right? I.e. is the egg file unzipped 'on the fly' when the program is called? Reading the documentation for pkg_resources it sounds like it will also work if I unpack the .egg file into a directory of the same name also put in /usr/local/lib/python2.7/dist-packages. Have I understood this correctly? I want to do this to make it easy to do trivial edits to the program rather than having to move it all back into a proper development environment. -- Chris Green ? From miki.tebeka at gmail.com Fri Oct 3 12:08:15 2014 From: miki.tebeka at gmail.com (Miki Tebeka) Date: Fri, 3 Oct 2014 09:08:15 -0700 (PDT) Subject: Recommended hosting In-Reply-To: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> References: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> Message-ID: <8dd40302-adaf-4a42-913e-e95d0284de81@googlegroups.com> Greetings, > I'd like to build a web site for myself, essentially a "vanity" web site to show off whatever web development skills I have, and perhaps do some blogging. I'm a Python developer, so I'd like to develop the site with the following stack: > web applications written with Python and Flask, running as uwsgi applications. These would support dynamic HTML where needed, but mostly it would provide REST API's. IIRC you can use Flask with AppEngine (static content will be handled by AppEngine and not nginx). It's free for small-ish sites and removes a lot of operations headache. All the best, -- Miki From diarmuid.higgins at mycit.ie Fri Oct 3 13:35:38 2014 From: diarmuid.higgins at mycit.ie (diarmuid.higgins at mycit.ie) Date: Fri, 3 Oct 2014 10:35:38 -0700 (PDT) Subject: Python Basics Message-ID: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> Hi I have just started an introductory course on Python. I have never even seen a programming language before so I am struggling a bit. Our lecturer has given us a number of excercises to complete and I am stuck on the one I have listed below. Please help Q2. Implement a function called printNumTriangle. The function should ask the user to enter a single integer. It should then print a triangle of that size specified by the integer so that each row in the triangle is made up of the integer displayed. The following is a sample output Please enter an integer for triangle size: 1 22 333 4444 55555 From rosuav at gmail.com Fri Oct 3 13:42:31 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 4 Oct 2014 03:42:31 +1000 Subject: Python Basics In-Reply-To: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> Message-ID: On Sat, Oct 4, 2014 at 3:35 AM, wrote: > Our lecturer has given us a number of excercises to complete and I am stuck on the one I have listed below. Please help Sure! Show us the code you have so far, and explain what it is you're stuck on. Then we can help you. But we're not going to write the code for you. ChrisA From diarmuid.higgins at mycit.ie Fri Oct 3 13:44:57 2014 From: diarmuid.higgins at mycit.ie (diarmuid.higgins at mycit.ie) Date: Fri, 3 Oct 2014 10:44:57 -0700 (PDT) Subject: Python Basics In-Reply-To: References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> Message-ID: <2c198e3c-ddee-47a9-b744-a35c726cdfd2@googlegroups.com> def printNumTriangle(): num = input("Please enter an integer for triangle size:") for i in range(1,num+1): for j in range (i): print i Cheers!!!! On Friday, October 3, 2014 6:42:46 PM UTC+1, Chris Angelico wrote: > On Sat, Oct 4, 2014 at 3:35 AM, wrote: > > > Our lecturer has given us a number of excercises to complete and I am stuck on the one I have listed below. Please help > > > > Sure! Show us the code you have so far, and explain what it is you're > > stuck on. Then we can help you. But we're not going to write the code > > for you. > > > > ChrisA From rosuav at gmail.com Fri Oct 3 13:47:39 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 4 Oct 2014 03:47:39 +1000 Subject: Python Basics In-Reply-To: <2c198e3c-ddee-47a9-b744-a35c726cdfd2@googlegroups.com> References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <2c198e3c-ddee-47a9-b744-a35c726cdfd2@googlegroups.com> Message-ID: On Sat, Oct 4, 2014 at 3:44 AM, wrote: > def printNumTriangle(): > num = input("Please enter an integer for triangle size:") > for i in range(1,num+1): > for j in range (i): > print i > > Cheers!!!! Okay! You're very close, and I can see what's going on there. But I'd like you to learn how to ask questions, as well as how to write Python code, because both skills are important to your future. :) So I'm going to get you to take another step in asking the question: What is it that your code isn't doing right? ChrisA From diarmuid.higgins at mycit.ie Fri Oct 3 13:54:32 2014 From: diarmuid.higgins at mycit.ie (diarmuid.higgins at mycit.ie) Date: Fri, 3 Oct 2014 10:54:32 -0700 (PDT) Subject: Python Basics In-Reply-To: References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <2c198e3c-ddee-47a9-b744-a35c726cdfd2@googlegroups.com> Message-ID: On Friday, October 3, 2014 6:47:54 PM UTC+1, Chris Angelico wrote: > On Sat, Oct 4, 2014 at 3:44 AM, wrote: > > > def printNumTriangle(): > > > num = input("Please enter an integer for triangle size:") > > > for i in range(1,num+1): > > > for j in range (i): > > > print i > > > > > > Cheers!!!! > > > > Okay! You're very close, and I can see what's going on there. But I'd > > like you to learn how to ask questions, as well as how to write Python > > code, because both skills are important to your future. :) So I'm > > going to get you to take another step in asking the question: What is > > it that your code isn't doing right? > > > > ChrisA Hi Chris I can't get the code to display the output as it should. I can get it to display like this: 122333444455555 or I can get it to display like this: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 but not as has been asked in the question. Cheers Diarmuid From rosuav at gmail.com Fri Oct 3 14:04:39 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 4 Oct 2014 04:04:39 +1000 Subject: Python Basics In-Reply-To: References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <2c198e3c-ddee-47a9-b744-a35c726cdfd2@googlegroups.com> Message-ID: On Sat, Oct 4, 2014 at 3:54 AM, wrote: > Hi Chris > I can't get the code to display the output as it should. > I can get it to display like this: > 122333444455555 or I can get it to display like this: > 1 > 2 > 2 > 3 > 3 > 3 > 4 > 4 > 4 > 4 > 5 > 5 > 5 > 5 > 5 > but not as has been asked in the question. Good! (It would help if you explained how you had the two different versions, incidentally.) What you need is like the first version, only you want to break the lines every time the digit changes. That can be done pretty easily. All you need to do is print out nothing, followed by end-of-line; and you need to do this in such a way that it happens after all of one digit has been displayed, but before the next one is. Can you do that? Side point: Google Groups makes a horrible mess of your posts. Please consider switching to the mailing list, or to a better newsreader. You can join the mailing list here: https://mail.python.org/mailman/listinfo/python-list Thanks! ChrisA From toby at tobiah.org Fri Oct 3 14:34:16 2014 From: toby at tobiah.org (Tobiah) Date: Fri, 03 Oct 2014 11:34:16 -0700 Subject: Python Basics In-Reply-To: References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <2c198e3c-ddee-47a9-b744-a35c726cdfd2@googlegroups.com> Message-ID: <542EEC28.1010702@tobiah.org> > Hi Chris > I can't get the code to display the output as it should. > I can get it to display like this: > 122333444455555 or I can get it to display like this: > 1 > 2 > 2 > 3 > 3 > 3 > 4 > 4 > 4 > 4 > 5 > 5 > 5 > 5 > 5 > but not as has been asked in the question. > Cheers > Diarmuid > Hint: >>> 'a' * 4 'aaaa' From croepha at gmail.com Fri Oct 3 14:36:20 2014 From: croepha at gmail.com (Croepha) Date: Fri, 3 Oct 2014 13:36:20 -0500 Subject: "High water" Memory fragmentation still a thing? Message-ID: Question: Does python in general terms (apart from extensions or gc manipulation), exhibit a "high water" type leak of allocated memory in recent python versions (2.7+)? Background: >From the post: http://chase-seibert.github.io/blog/2013/08/03/diagnosing-memory-leaks-python.html Begin quote: Long running Python jobs that consume a lot of memory while running may not return that memory to the operating system until the process actually terminates, even if everything is garbage collected properly. That was news to me, but it's true. What this means is that processes that do need to use a lot of memory will exhibit a "high water" behavior, where they remain forever at the level of memory usage that they required at their peak. Note: this behavior may be Linux specific; there are anecdotal reports that Python on Windows does not have this problem. This problem arises from the fact that the Python VM does its own internal memory management. It's commonly know as memory fragmentation. Unfortunately, there doesn't seem to be any fool-proof method of avoiding it. End Quote However this paper seems to indicate that that is not a modern problem: http://www.evanjones.ca/memoryallocator/ --Thanks Dave Butler -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Oct 3 15:07:05 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 03 Oct 2014 15:07:05 -0400 Subject: Returning a List In-Reply-To: References: Message-ID: On 10/3/2014 7:35 AM, Shiva wrote: > Hi All, > > I might be doing something really silly here, but I can't seem to spot it: > > def front_x(words): > b=[] > c=[] > for a in words: > if a[0] == 'x': > b.append(a) > else: > c.append(a) > > b = sorted(b) > c = sorted(c) Just sort in place with b.sort() c.sort() > d= b+c > print('d = ',d) > > #return b+c > return d > > front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']) xlist = front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']) print(xlist) -- Terry Jan Reedy From antoine at python.org Fri Oct 3 15:16:57 2014 From: antoine at python.org (Antoine Pitrou) Date: Fri, 3 Oct 2014 19:16:57 +0000 (UTC) Subject: "High water" Memory fragmentation still a thing? References: Message-ID: Hello, Croepha gmail.com> writes: > > Question: > > Does python in general terms (apart from extensions or gc manipulation), exhibit a "high water" type leak of allocated memory in recent python versions (2.7+)? It is not a leak. It is a quite common pattern of memory fragmentation. The article is wrong in assuming that Python doesn't return the memory to the OS. Python does return its empty memory pools to the OS, however the OS itself may not be able to release that memory, because of heap fragmentation. As the article mentions, this was improved (mostly fixed?) in 3.3. Regards Antoine. From christian at python.org Fri Oct 3 15:51:02 2014 From: christian at python.org (Christian Heimes) Date: Fri, 03 Oct 2014 21:51:02 +0200 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: References: Message-ID: On 03.10.2014 21:16, Antoine Pitrou wrote: > It is not a leak. It is a quite common pattern of memory fragmentation. > The article is wrong in assuming that Python doesn't return the memory to > the OS. Python does return its empty memory pools to the OS, however the OS > itself may not be able to release that memory, because of heap fragmentation. The article doesn't state if the writer is referring to virtual memory or resident set size. For long-running 32bit processes it is quite common to run out of virtual address space. But that's something totally different than running out of memory. A 64bit process can have a virtual address size of several GB but only occupy a few hundred MB of physical memory. People tend to confuse the meaning of VSZ and RSS and forget about paging. From nad at acm.org Fri Oct 3 15:55:24 2014 From: nad at acm.org (Ned Deily) Date: Fri, 03 Oct 2014 12:55:24 -0700 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk References: Message-ID: In article , Christian Gollwitzer wrote: > Hmm, I'm not sure that the other projects would need an update. In Tcl > world, there is the concept of stub libraries, an extra level of > indirect linking provided by both the Tcl and Tk core. If the extensions > link to the stub library (the standard way), they can be loaded into any > later version of Tcl and do not directly depend on libtcl or libtk. If > the extensions link directly to libtcl, they are either broken or very > special (providing one's own interpreter, doing nasty stuff with > internals etc.) Even if there were no incompatibilities, on OS X with Tcl and Tk (and other) frameworks, the version number is embedded in the path to the shared library and the linker normally creates an absolute path at that. $ otool -L _tkagg.so _tkagg.so: /usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 60.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1) /Library/Frameworks/Tcl.framework/Versions/8.5/Tcl (compatibility version 8.5.0, current version 8.5.15) /Library/Frameworks/Tk.framework/Versions/8.5/Tk (compatibility version 8.5.0, current version 8.5.15) -- Ned Deily, nad at acm.org From skip.montanaro at gmail.com Fri Oct 3 16:01:50 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Fri, 3 Oct 2014 15:01:50 -0500 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: References: Message-ID: On Fri, Oct 3, 2014 at 1:36 PM, Croepha wrote: > Long running Python jobs that consume a lot of memory while > running may not return that memory to the operating system > until the process actually terminates, even if everything is > garbage collected properly. (I see Antoine replied that this is mostly fixed starting in 3.3. My response below was written with my Unix/Python 2 rose-colored glasses firmly affixed to my face.) Unless you are blessed with a long-running program which does everything exactly right, I'd be surprised if any such program behaved the way you want. Python may be extreme in this regard, since it often allcates small objects, and its special object allocator (obmalloc - is it still used?) might mitigate the problem by collecting allocations of similar size together (malloc implementations probably do some of this as well), but it's still going to have these issues. The problem boils down to how the program dynamically allocates and frees memory, and how the malloc subsystem interacts with the kernel through the brk and sbrk system calls. (Anywhere I mention "brk", you can mentally replace it with "sbrk". They do the same thing - ask for memory from or return memory to the kernel - using a different set of units, memory addresses or bytes.) In the general case, programmers call malloc (or calloc, or realloc) to allocate a chunk of storage from the heap. (I'm ignoring anything special which Python has layered on top of malloc. It can mitigate problems, but I don't think it will fundamentally change the way malloc interacts with the kernel.) The malloc subsystem maintains a free list (recently freed bits of memory) from which it can allocate memory without traipsing off to the kernel. If it can't return a chunk of memory from the free list, it will (in the most simpleminded malloc implementation) call brk to grab a new (large) chunk of memory. The system simply moves the end of the program's "break", effectively increasing or decreasing the (virtual) size of the running program. That memory is then doled out to the user by malloc. If, and only if, every chunk of memory in the last chunk allocated by a call to brk is placed on malloc's free list, *and* if the particular malloc implementation on your box is smart enough to coalesce adjacent chunks of freed memory back into brk-sized memory chunks, can brk be called once again to reduce the program's footprint. Example... I don't know how much memory malloc requests from brk, so let's make things easy, and make the following assumptions: * Assume malloc calls brk to allocate 1MB chunks. * Assume the program only ever calls malloc(1024). * Assume malloc's own overhead (free list, etc) is zero. So, starting afresh, having no free memory, the first time we call malloc(1024), it calls brk asking for 1MB, then returns its caller a pointer to that 1024-byte chunk. Now call malloc(1024) 1023 more times. We have used up that entire 1MB chunk of memory. Now free each of those chunks by calling free() 1024 times. We are left, once again, with a 1MB chunk of free memory. It might be stitched together by malloc into one single block of memory, or it might appear on the free list as 1024 chunks of memory. Should malloc return it to the system with a call to brk? Maybe. Maybe not. Maybe the malloc subsystem goes through all the necessary bookkeeping to hand that memory back to the system, only to find that the next thing the program does is make another malloc(1024) call. Whoops. Now you have to call brk again. And system calls are expensive. Now, consider a similar case. You make 1024 calls to malloc(1024). Then you free all of them except the 512th one. Now you have a 1MB chunk of memory on malloc's free list which is entirely free, except for a small chunk in the middle. That chunk is broken into three fragments, two free fragments, separated by one chunk which is still in use. Can't free that. Well, perhaps you could, but only the top half of it. And you'd have the same dilemma as before. Should you return it or not? Final consideration. Suppose your program makes 1023 calls to malloc(1024) and frees them all, but sometime during that work, a low-level library far from the programmer's view also calls malloc to get a 1KB chunk. Even if your program (e.g., the Python runtime) was perfectly well-behaved and returned all of the 1023 chunks of memory it had requested, it has no control over this low-level library. You're still stuck with a fragmented chunk of memory, free except for a hole somewhere in the middle. Long story short, there's only so much you can do to try to return memory to the system. I am not up-to-date on the latest malloc intelligence, but it's a challenging enough problem that it was a long time before any malloc implementation attempted to automatically return memory pages to the system. Finally, as this is not really Python-specific, you might want to do some reading on how malloc is implemented. It can be pretty arcane, but I'm sure it would make for fascinating cocktail party conversation. Skip From kw at codebykevin.com Fri Oct 3 17:16:19 2014 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 03 Oct 2014 17:16:19 -0400 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk In-Reply-To: References: Message-ID: On 10/3/14, 3:55 PM, Ned Deily wrote: > Even if there were no incompatibilities, on OS X with Tcl and Tk (and > other) frameworks, the version number is embedded in the path to the > shared library and the linker normally creates an absolute path at that. Is this because Python lacks the concept of stubs? A Tcl library compiled for 8.5 can be loaded into 8.6 with no re-compiling required because of stubs. -- Kevin Walzer Code by Kevin/Mobile Code by Kevin http://www.codebykevin.com http://www.wtmobilesoftware.com From dwightdhutto at gmail.com Fri Oct 3 17:35:11 2014 From: dwightdhutto at gmail.com (David Hutto) Date: Fri, 3 Oct 2014 17:35:11 -0400 Subject: Recommended hosting In-Reply-To: <8dd40302-adaf-4a42-913e-e95d0284de81@googlegroups.com> References: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> <8dd40302-adaf-4a42-913e-e95d0284de81@googlegroups.com> Message-ID: The best thing, and yes this is self promotion, is to find a "digital dealer". The server can be modularized locally, or across the server because you can work your way up with others. Just state the service(s) directly that you need, and an account can be individually modified just for you. On Fri, Oct 3, 2014 at 12:08 PM, Miki Tebeka wrote: > Greetings, > > > I'd like to build a web site for myself, essentially a "vanity" web site > to show off whatever web development skills I have, and perhaps do some > blogging. I'm a Python developer, so I'd like to develop the site with the > following stack: > > web applications written with Python and Flask, running as uwsgi > applications. These would support dynamic HTML where needed, but mostly it > would provide REST API's. > IIRC you can use Flask with AppEngine (static content will be handled by > AppEngine and not nginx). > > It's free for small-ish sites and removes a lot of operations headache. > > All the best, > -- > Miki > -- > https://mail.python.org/mailman/listinfo/python-list > -- Best Regards, David Hutto *CEO:* *Hutto Industrial Technologies Inc.http://www.zenfinite.com * http://www.payizm.com -Coming Soon! http://www.mylayawayplan.com -Coming Soon! -------------- next part -------------- An HTML attachment was scrubbed... URL: From milsonmun at gmail.com Fri Oct 3 17:43:30 2014 From: milsonmun at gmail.com (Milson Munakami) Date: Fri, 3 Oct 2014 14:43:30 -0700 (PDT) Subject: How to set the global variable so that it can be accessed and released inside other methods In-Reply-To: <3bb9f56c-eff3-472e-8239-58b58cdb16be@googlegroups.com> References: <3bb9f56c-eff3-472e-8239-58b58cdb16be@googlegroups.com> Message-ID: <4a73c7f7-b221-47da-83fc-8547a4f3d110@googlegroups.com> Hi Chris, I want to remove that CreateNet() part from the test class so that it will not create network every time in setup() because all the test cases are run and tested in same network! But the test class method also need to access the net object How can I do that? Please Help. Thanks, Milson On Thursday, October 2, 2014 9:30:21 AM UTC-6, Milson Munakami wrote: > Hi, > > > > I am newbie to Python, > > > > I am trying to use unittest and python. My python script is like this: > > > > #! /usr/bin/env python > > __author__ = 'Milson Munakami' > > __revision__ = '0.0.2' > > > > import json > > import urllib > > import httplib > > from scapy.all import * > > > > import unittest > > > > import os, sys, socket, struct, select, time > > from threading import Thread > > > > import logging > > import traceback > > > > from mininet.net import Mininet > > from mininet.node import OVSSwitch, OVSKernelSwitch, Controller, RemoteController > > from mininet.log import setLogLevel, info > > from mininet.cli import CLI > > > > class testFirewallS1( unittest.TestCase ): > > > > #I am trying to set net variable to global > > global net > > ###################### > > > > def setUp(self): > > self.controllerIp="127.0.0.1" > > self.switch = "00:00:00:00:00:00:00:01" > > self.destinationIp = "10.0.0.1" > > self.startTime_ = time.time() > > self.failed = False > > self.reportStatus_ = True > > self.name_ = "Firewall" > > self.log = logging.getLogger("unittest") > > self.CreateNet() > > self.SetPrecondition() > > > > def CreateNet(self): > > "Create an empty network and add nodes to it." > > net = Mininet( controller=RemoteController ) > > > > info( '*** Adding controller\n' ) > > net.addController( 'c0' , controller=RemoteController,ip= "127.0.0.1", port=6633) > > > > info( '*** Adding hosts\n' ) > > h1 = net.addHost( 'h1', ip='10.0.0.1' ) > > h2 = net.addHost( 'h2', ip='10.0.0.2' ) > > h3 = net.addHost( 'h3', ip='10.0.0.3' ) > > > > info( '*** Adding switch\n' ) > > s1 = net.addSwitch( 's1' ) > > > > info( '*** Creating links\n' ) > > net.addLink( h1, s1 ) > > net.addLink( h2, s1 ) > > net.addLink( h3, s1 ) > > > > info( '*** Starting network\n') > > net.start() > > > > def tearDown(self): > > if self.failed: > > return > > duration = time.time() - self.startTime_ > > self.cleanup(True) > > if self.reportStatus_: > > self.log.info("=== Test %s completed normally (%d sec)", self.name_, duration) > > > > def cleanup(self, success): > > sys.excepthook = sys.__excepthook__ > > self.SetFinalcondition() > > try: > > return > > except NameError: > > self.log.error("Exception hit during cleanup, bypassing:\n%s\n\n" % traceback.format_exc()) > > pass > > else: > > > > fail("Expected a NameError") > > > > def StatusFirewall(self): > > command = "http://%s:8080/wm/firewall/module/status/json" % self.controllerIp > > x = urllib.urlopen(command).read() > > parsedResult = json.loads(x) > > return parsedResult['result'] > > > > def CountFirewallRules(self): > > command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp > > x = urllib.urlopen(command).read() > > return x > > > > def CountFlowRules(self): > > command = "http://%s:8080/wm/core/switch/%s/flow/json" % (self.controllerIp, self.switch) > > x = urllib.urlopen(command).read() > > parsedResult = json.loads(x) > > content = parsedResult['00:00:00:00:00:00:00:01'] > > if content is None: > > return "[]" > > else: > > return str(content) > > > > def SetPrecondition(self): > > command = "http://%s:8080/wm/firewall/module/enable/json" % self.controllerIp > > urllib.urlopen(command).read() > > > > # cleanup all Firewall rules > > command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp > > x = urllib.urlopen(command).read() > > parsedResult = json.loads(x) > > for i in range(len(parsedResult)): > > params = "{\"ruleid\":\"%s\"}" % parsedResult[i]['ruleid'] > > command = "/wm/firewall/rules/json" > > url = "%s:8080" % self.controllerIp > > connection = httplib.HTTPConnection(url) > > connection.request("DELETE", command, params) > > connection.getresponse().read() > > > > # sleep for REST command to get processed to avoid racing > > time.sleep(5) > > > > def SetFinalcondition(self): > > command = "http://%s:8080/wm/firewall/module/disable/json" % self.controllerIp > > urllib.urlopen(command).read() > > > > # cleanup all Firewall rules > > command = "http://%s:8080/wm/firewall/rules/json" % self.controllerIp > > x = urllib.urlopen(command).read() > > parsedResult = json.loads(x) > > for i in range(len(parsedResult)): > > params = "{\"ruleid\":\"%s\"}" % parsedResult[i]['ruleid'] > > command = "/wm/firewall/rules/json" > > url = "%s:8080" % self.controllerIp > > connection = httplib.HTTPConnection(url) > > connection.request("DELETE", command, params) > > connection.getresponse().read() > > > > # sleep for REST command to get processed to avoid racing > > time.sleep(5) > > > > info( '*** Stopping network' ) > > net.stop() > > > > #Precondition Test > > def testPreConditionFirewall(self): > > self.assertTrue("enabled" in self.StatusFirewall()) > > self.assertTrue("[]" in self.CountFirewallRules()) > > self.assertEqual("[]",self.CountFlowRules(), "should be empty") > > > > #7 > > def testCreateFlow(self): > > > > info( '*** Testing network connecivity\n') > > net.pingAll() > > > > #Using Scapy > > #send(IP(dst="10.0.0.3")/ICMP()/"Hello World") > > > > #info( '*** Running CLI\n' ) > > #CLI( net ) > > > > # Post Conditions Validation > > self.assertTrue("enabled" in self.StatusFirewall()) > > self.assertTrue("[]" in self.CountFirewallRules()) > > self.assertNotEqual("[]",self.CountFlowRules(), "should not be empty rules cause it is added from Firewall with Action = []") > > #8 > > def testCountFlow(self): > > command = "http://%s:8080/wm/core/switch/all/flow/json" % self.controllerIp > > x = urllib.urlopen(command).read() > > self.assertEqual("[]",self.CountFlowRules(), "should be empty") > > > > # Post Conditions Validation > > self.assertTrue("enabled" in self.StatusFirewall()) > > self.assertTrue("[]" in self.CountFirewallRules()) > > self.assertEqual("[]",self.CountFlowRules(), "should be empty") > > #10 > > def testDeleteFlow(self): > > # sleep for REST command to get processed to avoid racing > > time.sleep(5) > > > > command = "http://%s:8080/wm/core/switch/all/flow/json" % self.controllerIp > > x = urllib.urlopen(command).read() > > self.assertEqual("[]",self.CountFlowRules(), "should be empty") > > > > # Post Conditions Validation > > self.assertTrue("enabled" in self.StatusFirewall()) > > self.assertTrue("[]" in self.CountFirewallRules()) > > self.assertEqual("[]",self.CountFlowRules(), "should be empty") > > > > def suite(): > > > > suite = unittest.TestSuite() > > > > suite.addTest(unittest.makeSuite(testFirewallS1)) > > > > return suite > > > > if __name__ == '__main__': > > logging.basicConfig(filename='/tmp/testfirewall.log', level=logging.DEBUG, > > format='%(asctime)s %(levelname)s %(name)s %(message)s') > > logger=logging.getLogger(__name__) > > > > suiteFew = unittest.TestSuite() > > > > # Preconditions: > > suiteFew.addTest(testFirewallS1("testPreConditionFirewall")) > > > > > > # 7. Add one Flow Entry > > suiteFew.addTest(testFirewallS1("testCreateFlow")) > > > > # 8. Count Flow rules - empty > > suiteFew.addTest(testFirewallS1("testCountFlow")) > > > > # 9. Update a Flow Rule - Not Implemented due to Controller's Constraint > > > > # 10. wait till the time-stamp period to validate the flow is deleted with that time. > > suiteFew.addTest(testFirewallS1("testDeleteFlow")) > > > > #Testing the Test Cases Begins Here > > unittest.TextTestRunner(verbosity=2).run(suiteFew) > > > > #unittest.main() > > #unittest.TextTestRunner(verbosity=2).run(suite()) > > > > > > I tired to set a globla net variable inside the class and tring to access it from another methods like from def SetFinalcondition(self): and def testCreateFlow(self): but the error says:\ > > > > > > ERROR: testPreConditionFirewall (__main__.testFirewallS1) > > ---------------------------------------------------------------------- > > Traceback (most recent call last): > > File "mm.py", line 68, in tearDown > > self.cleanup(True) > > File "mm.py", line 74, in cleanup > > self.SetFinalcondition() > > File "mm.py", line 144, in SetFinalcondition > > net.stop() > > NameError: global name 'net' is not defined > > > > ====================================================================== > > ERROR: testCreateFlow (__main__.testFirewallS1) > > ---------------------------------------------------------------------- > > Traceback (most recent call last): > > File "mm.py", line 156, in testCreateFlow > > net.pingAll() > > NameError: global name 'net' is not defined > > > > ====================================================================== > > ERROR: testCreateFlow (__main__.testFirewallS1) > > ---------------------------------------------------------------------- > > Traceback (most recent call last): > > File "mm.py", line 68, in tearDown > > self.cleanup(True) > > File "mm.py", line 74, in cleanup > > self.SetFinalcondition() > > File "mm.py", line 144, in SetFinalcondition > > net.stop() > > NameError: global name 'net' is not defined > > > > ====================================================================== > > ERROR: testCountFlow (__main__.testFirewallS1) > > ---------------------------------------------------------------------- > > Traceback (most recent call last): > > File "mm.py", line 68, in tearDown > > self.cleanup(True) > > File "mm.py", line 74, in cleanup > > self.SetFinalcondition() > > File "mm.py", line 144, in SetFinalcondition > > net.stop() > > NameError: global name 'net' is not defined > > > > ====================================================================== > > ERROR: testDeleteFlow (__main__.testFirewallS1) > > ---------------------------------------------------------------------- > > Traceback (most recent call last): > > File "mm.py", line 68, in tearDown > > self.cleanup(True) > > File "mm.py", line 74, in cleanup > > self.SetFinalcondition() > > File "mm.py", line 144, in SetFinalcondition > > net.stop() > > NameError: global name 'net' is not defined > > > > > > How to fix it! > > Thanks for any help > > - Milson From breamoreboy at yahoo.co.uk Fri Oct 3 17:55:56 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 03 Oct 2014 22:55:56 +0100 Subject: How to set the global variable so that it can be accessed and released inside other methods In-Reply-To: <4a73c7f7-b221-47da-83fc-8547a4f3d110@googlegroups.com> References: <3bb9f56c-eff3-472e-8239-58b58cdb16be@googlegroups.com> <4a73c7f7-b221-47da-83fc-8547a4f3d110@googlegroups.com> Message-ID: On 03/10/2014 22:43, Milson Munakami wrote: > Hi Chris, > I want to remove that CreateNet() part from the test class so that it will not create network every time in setup() because all the test cases are run and tested in same network! > > But the test class method also need to access the net object > > How can I do that? > > Please Help. > Thanks, > Milson You are far more likely to get answers if you don't top post and if you don't use the obnoxious google groups. I've snipped roughly 600 lines from your reply. To avoid sending the rubbish that many of us here don't want to see would you please access this list via https://mail.python.org/mailman/listinfo/python-list or read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing and single line paragraphs, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From Seymore4Head at Hotmail.invalid Fri Oct 3 18:54:13 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 03 Oct 2014 18:54:13 -0400 Subject: Python Basics References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> Message-ID: <78au2a12nlq6nipske1a327p14dvgvakug@4ax.com> On Fri, 3 Oct 2014 10:35:38 -0700 (PDT), diarmuid.higgins at mycit.ie wrote: >Hi > >I have just started an introductory course on Python. I have never even seen a programming language before so I am struggling a bit. Our lecturer has given us a number of excercises to complete and I am stuck on the one I have listed below. Please help > >Q2. Implement a function called printNumTriangle. The function should ask the user to enter a single integer. It should then print a triangle of that size specified by the integer so that each row in the triangle is made up of the integer displayed. > >The following is a sample output > >Please enter an integer for triangle size: >1 >22 >333 >4444 >55555 for i in range(1,10): print (str(i)*i) From rosuav at gmail.com Fri Oct 3 19:05:50 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 4 Oct 2014 09:05:50 +1000 Subject: Python Basics In-Reply-To: <78au2a12nlq6nipske1a327p14dvgvakug@4ax.com> References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <78au2a12nlq6nipske1a327p14dvgvakug@4ax.com> Message-ID: On Sat, Oct 4, 2014 at 8:54 AM, Seymore4Head wrote: >>Q2. Implement a function called printNumTriangle. The function should ask the user to enter a single integer. It should then print a triangle of that size specified by the integer so that each row in the triangle is made up of the integer displayed. >> >>The following is a sample output >> >>Please enter an integer for triangle size: >>1 >>22 >>333 >>4444 >>55555 > for i in range(1,10): > print (str(i)*i) Seymour, please don't do this. When you "help" someone by just giving him the answer to a homework problem, you get him past his immediate issue of "I need to submit my homework for this problem". That lets him get through his course without understanding the code he's creating (because he's not the one creating it). He'll either run into more trouble before graduating the course, or (far worse) he'll graduate successfully, without having the competence that the course is supposed to teach - and the world will be given a qualified programmer who doesn't know his stuff. That damages the world, damages the reputation of the course, and gives python-list a reputation as a homework assignment solver... none of which I want. I'm pretty sure you don't want it either. So don't do people's homework for them. PLEASE!! ChrisA From davea at davea.name Fri Oct 3 19:13:17 2014 From: davea at davea.name (Dave Angel) Date: Fri, 3 Oct 2014 19:13:17 -0400 (EDT) Subject: Python Basics References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> Message-ID: diarmuid.higgins at mycit.ie Wrote in message: > Hi > > I have just started an introductory course on Python. I have never even seen a programming language before so I am struggling a bit. Our lecturer has given us a number of excercises to complete and I am stuck on the one I have listed below. Please help > Which part are you having trouble with? > Q2. Implement a function called printNumTriangle. A function definition starts with the keyword 'def' -- DaveA From rosuav at gmail.com Fri Oct 3 19:26:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 4 Oct 2014 09:26:40 +1000 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: References: Message-ID: On Sat, Oct 4, 2014 at 4:36 AM, Croepha wrote: > What this means is that processes that do need to use a lot of memory will > exhibit a "high water" behavior, where they remain forever at the level of > memory usage that they required at their peak. This is almost never true. What you will see, though, is something like Christian described; pages get allocated, and then partially used, and you don't always get all that memory back. In theory, a high level language like Python would be allowed to move objects around to compact memory, but CPython doesn't do this, and there's no proof that it'd really help anything anyway. (Look at Christian's comments about "Should you return it or not?" and the cost of system calls... now consider the orders-of-magnitude worse cost of actually moving memory around.) This is why a lot of long-duration processes are built to be restarted periodically. It's not strictly necessary, but it can be the most effective way of solving a problem. I tend to ignore that, though, and let my processes just keep on running... for 88 wk 4d 23:56:27 so far, on one of those processes. It's consuming less than half a gig of virtual memory, quarter gig resident, and it's been doing a fair bit (it keeps all sorts of things in memory to avoid re-decoding from disk). So don't worry too much about memory usage until you see that there's actually a problem; with most Python processes, you'll restart them to deploy new code sooner than you'll restart them to fix memory problems. (The above example isn't a Python process, and code updates happen live.) In fact, I'd advise that as a general policy: Don't panic about any Python limitation until you've proven that it's actually a problem. :) ChrisA From steve+comp.lang.python at pearwood.info Fri Oct 3 21:02:02 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 04 Oct 2014 11:02:02 +1000 Subject: "High water" Memory fragmentation still a thing? References: Message-ID: <542f470b$0$13003$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > In theory, a high > level language like Python would be allowed to move objects around to > compact memory, but CPython doesn't do this, and there's no proof that > it'd really help anything anyway. I welcome correction, but I understand that both the JVM and the CLR memory managers move memory around. That's why Jython and IronPython use sequential integers as object IDs, since memory locations are not fixed. Way back in the mid 1980s, Apple Macintoshes used a memory manager which could move memory around. Given that the Macs of the day had 128K of RAM, of which something like a third or a half was used for the screen, being able to move blocks of memory around to avoid fragmentation was critical, so I guess that proves that it would help at least one thing. > (Look at Christian's comments about > "Should you return it or not?" and the cost of system calls... now > consider the orders-of-magnitude worse cost of actually moving memory > around.) > > This is why a lot of long-duration processes are built to be restarted > periodically. Ironically, the cost of restarting the process periodically is likely to be orders of magnitude more expensive than that of moving a few blocks of memory around from time to time. Especially on Windows, where starting processes is expensive, but even on Linux you have to shut the running application down, then start it up again and rebuild all the internal data structures that you just tore down... -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 3 21:09:58 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 04 Oct 2014 11:09:58 +1000 Subject: Python Basics References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <78au2a12nlq6nipske1a327p14dvgvakug@4ax.com> Message-ID: <542f48e7$0$13014$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Sat, Oct 4, 2014 at 8:54 AM, Seymore4Head > wrote: >> for i in range(1,10): >> print (str(i)*i) > > Seymour, please don't do this. When you "help" someone by just giving > him the answer to a homework problem, you get him past his immediate > issue of "I need to submit my homework for this problem". That lets > him get through his course without understanding the code he's > creating [...] In fairness to Seymour, at this extremely basic level, it's really hard to explain to somebody how to solve a problem without giving them the answer. While I don't condone mindless parroting of work that others have done, remember that for tens of thousands of years, being shown how to do something, then imitating that, has been the most effective way for people to learn. Dropping hints is typically the least effective learning method. -- Steven From rosuav at gmail.com Fri Oct 3 22:22:38 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 4 Oct 2014 12:22:38 +1000 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: <542f470b$0$13003$c3e8da3$5496439d@news.astraweb.com> References: <542f470b$0$13003$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Oct 4, 2014 at 11:02 AM, Steven D'Aprano wrote: > Chris Angelico wrote: > >> In theory, a high >> level language like Python would be allowed to move objects around to >> compact memory, but CPython doesn't do this, and there's no proof that >> it'd really help anything anyway. > > I welcome correction, but I understand that both the JVM and the CLR memory > managers move memory around. That's why Jython and IronPython use > sequential integers as object IDs, since memory locations are not fixed. Right; I should have made it clearer that there's no proof that it'd help anything *in CPython*. Removing the GIL is periodically proposed, too, but there's no proof that its removal would benefit CPython; it's not just that nobody's gotten around to writing a memory compactor for CPython. > Ironically, the cost of restarting the process periodically is likely to be > orders of magnitude more expensive than that of moving a few blocks of > memory around from time to time. Especially on Windows, where starting > processes is expensive, but even on Linux you have to shut the running > application down, then start it up again and rebuild all the internal data > structures that you just tore down... Maybe. But you deal with a number of things all at once: 1) Code updates (including interpreter updates) 2) Compaction of Python objects 3) Disposal of anything that got "high level leaked" - unintended longevity caused by a global reference of some sort 4) Cleanup of low-level allocations that don't go through the Python memory manager etc etc etc. So, yes, it's expensive. And sometimes it's not even possible (there's no way to retain socket connections across a restart, AFAIK). But it's there if you want it. Personally, I like to keep processes running, but that's me. :) ChrisA From rosuav at gmail.com Fri Oct 3 22:24:14 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 4 Oct 2014 12:24:14 +1000 Subject: Python Basics In-Reply-To: <542f48e7$0$13014$c3e8da3$5496439d@news.astraweb.com> References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <78au2a12nlq6nipske1a327p14dvgvakug@4ax.com> <542f48e7$0$13014$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Oct 4, 2014 at 11:09 AM, Steven D'Aprano wrote: > In fairness to Seymour, at this extremely basic level, it's really hard to > explain to somebody how to solve a problem without giving them the answer. > > While I don't condone mindless parroting of work that others have done, > remember that for tens of thousands of years, being shown how to do > something, then imitating that, has been the most effective way for people > to learn. Dropping hints is typically the least effective learning method. Maybe. I'd still like to see the student's existing code before just giving the answer. Providing code in response to the copy/pasted problem definition invites the answer to be copy/pasted, which creates the situation I described. ChrisA From orgnut at yahoo.com Fri Oct 3 22:21:27 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Fri, 03 Oct 2014 19:21:27 -0700 Subject: Returning a List In-Reply-To: References: Message-ID: On 10/03/2014 04:35 AM, Shiva wrote: > Hi All, > > I might be doing something really silly here, but I can't seem to spot it: > > def front_x(words): > b=[] > c=[] > for a in words: > if a[0] == 'x': > b.append(a) > else: > c.append(a) > > b = sorted(b) > c = sorted(c) > d= b+c > print('d = ',d) > > #return b+c > return d > > front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']) > > > > Why is return d or return b+c not returning anything?? > > The d's value is confirmed by the print statement. > > Thanks, > Shiva. > Works fine for me... For a quickie test, I copy/pasted this code into Idle, and it works. I suspect you are trying to run this as a script -- but remember, when running interactively (directly in Python or in Idle) the return values are displayed automatically. This is NOT true when running as a program, you have to specifically print the return values (or save them in a variable to access them later). Change your calling line to: print(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa'])) -=- Larry -=- From steve+comp.lang.python at pearwood.info Sat Oct 4 01:48:22 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 04 Oct 2014 15:48:22 +1000 Subject: "High water" Memory fragmentation still a thing? References: <542f470b$0$13003$c3e8da3$5496439d@news.astraweb.com> Message-ID: <542f8a27$0$12998$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Sat, Oct 4, 2014 at 11:02 AM, Steven D'Aprano > wrote: >> Chris Angelico wrote: >> >>> In theory, a high >>> level language like Python would be allowed to move objects around to >>> compact memory, but CPython doesn't do this, and there's no proof that >>> it'd really help anything anyway. >> >> I welcome correction, but I understand that both the JVM and the CLR >> memory managers move memory around. That's why Jython and IronPython use >> sequential integers as object IDs, since memory locations are not fixed. > > Right; I should have made it clearer that there's no proof that it'd > help anything *in CPython*. Removing the GIL is periodically proposed, > too, but there's no proof that its removal would benefit CPython; it's > not just that nobody's gotten around to writing a memory compactor for > CPython. I think that you're conflating a couple of different issues, although I welcome correction. I don't think that removing the GIL is a requirement for a memory compactor, or vice versa. I think that PyPy is capable of plugging in various different garbage collectors, including some without the GIL, which may or may not include memory compactors. So as far as I can tell, the two are independent. As far as the GIL in CPython goes, there have been at least two attempts to remove it, and they do show strong improvements for multi-threaded code running on multi-core machines. Alas, they also show significant *slowdown* for single-core machines, and very little improvement on dual-core machines. [Aside: The thing that people fail to understand is that the GIL is not in fact something which *prevents* multi-tasking, but it *enables* cooperative multi-tasking: http://www.dabeaz.com/python/GIL.pdf although that's not to say that there aren't some horrible performance characteristics of the GIL. David Beazley has identified issues with the GIL which suggest room for improving the GIL and avoiding "GIL battles" which are responsible for much of the overhead of CPU-bound threads. Any C programmers who want to hack on the interpreter core?] Nevertheless, you're right that since nobody has actually built a version of CPython with memory compactor, there's no *proof* that it would help anything. -- Steven From nad at acm.org Sat Oct 4 01:53:23 2014 From: nad at acm.org (Ned Deily) Date: Fri, 03 Oct 2014 22:53:23 -0700 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk References: Message-ID: In article , Kevin Walzer wrote: > On 10/3/14, 3:55 PM, Ned Deily wrote: > > Even if there were no incompatibilities, on OS X with Tcl and Tk (and > > other) frameworks, the version number is embedded in the path to the > > shared library and the linker normally creates an absolute path at that. > > Is this because Python lacks the concept of stubs? > > A Tcl library compiled for 8.5 can be loaded into 8.6 with no > re-compiling required because of stubs. It has nothing to do with Python per se; that's just the way linking with OS frameworks work. Both Apple and ActiveState install their versions of Tcl and Tk as frameworks. What gets installed and what the OS X compilers and linkers expect is something like this: $ cd /Library/Frameworks/Tk.framework/Versions/8.5 $ ls -l total 5720 drwxr-xr-x+ 3 root wheel 272 Nov 24 2013 Headers drwxr-xr-x+ 2 root wheel 340 Nov 24 2013 PrivateHeaders drwxr-xr-x+ 4 root wheel 272 Nov 24 2013 Resources -rw-r--r--+ 1 root wheel 2905000 Oct 27 2013 Tk -rw-r--r--+ 1 root wheel 12240 Oct 27 2013 libtkstub8.5.a -rw-r--r--+ 1 root wheel 4622 Oct 27 2013 tkConfig.sh $ file Tk Tk: Mach-O universal binary with 2 architectures Tk (for architecture x86_64): Mach-O 64-bit dynamically linked shared library x86_64 Tk (for architecture i386): Mach-O dynamically linked shared library i386 $ file libtkstub8.5.a libtkstub8.5.a: Mach-O universal binary with 2 architectures libtkstub8.5.a (for architecture x86_64): current ar archive random library libtkstub8.5.a (for architecture i386): current ar archive random library $ otool -D Tk Tk: /Library/Frameworks/Tk.framework/Versions/8.5/Tk When Python or other programs link with a framework, they use the cc or ld -framework option, rather than -l: -framework Tcl -framework Tk That causes the linker to look in the default search paths for frameworks, /Library/Frameworks followed by /System/Library/Frameworks. The install names of the framework shared libraries used are embedded in the Mach-O file (executable, bundle, or shared library) produced by ld. So the stub library archive is there but is not used, AFAIK. There may be other ways to do it but that's how Python has always linked to Tcl and Tk. FWIW, that's how both Apple's and ActiveState's wish executables are linked as well: $ more /usr/local/bin/wish8.5 #!/bin/sh "$(dirname $0)/../../../Library/Frameworks/Tk.framework/Versions/8.5/Resources/Wish. app/Contents/MacOS/Wish" "$@" $ otool -L /Library/Frameworks/Tk.framework/Versions/8.5/Resources/Wish.app/Contents /MacOS/Wish /Library/Frameworks/Tk.framework/Versions/8.5/Resources/Wish.app/Contents /MacOS/Wish: /Library/Frameworks/Tk.framework/Versions/8.5/Tk (compatibility version 8.5.0, current version 8.5.15) /Library/Frameworks/Tcl.framework/Versions/8.5/Tcl (compatibility version 8.5.0, current version 8.5.15) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.2.0) /System/Library/Frameworks/Cocoa.framework/Versions/A/Cocoa (compatibility version 1.0.0, current version 15.0.0) /System/Library/Frameworks/Carbon.framework/Versions/A/Carbon (compatibility version 2.0.0, current version 152.0.0) /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit (compatibility version 1.0.0, current version 275.0.0) /usr/lib/libgcc_s.1.dylib (compatibility version 1.0.0, current version 625.0.0) There's more info about frameworks in various Apple developer docs and in the man pages for ld, otool, and install_name_tool. -- Ned Deily, nad at acm.org From rosuav at gmail.com Sat Oct 4 01:57:02 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 4 Oct 2014 15:57:02 +1000 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: <542f8a27$0$12998$c3e8da3$5496439d@news.astraweb.com> References: <542f470b$0$13003$c3e8da3$5496439d@news.astraweb.com> <542f8a27$0$12998$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Oct 4, 2014 at 3:48 PM, Steven D'Aprano wrote: > I think that you're conflating a couple of different issues, although I > welcome correction. > > I don't think that removing the GIL is a requirement for a memory compactor, > or vice versa. I think that PyPy is capable of plugging in various > different garbage collectors, including some without the GIL, which may or > may not include memory compactors. So as far as I can tell, the two are > independent. > > As far as the GIL in CPython goes, there have been at least two attempts to > remove it, and they do show strong improvements for multi-threaded code > running on multi-core machines. Alas, they also show significant *slowdown* > for single-core machines, and very little improvement on dual-core > machines. Not conflating, comparing. In both cases, it's perfectly possible *in theory* to build a CPython with this change. (GIL removal is clearly possible in theory, as it's been done in practice.) And *in theory*, there's some benefit to be gained by doing so. But it's not a case of "why doesn't python-dev just knuckle down and do it already", as there's no evidence that it's a real improvement. (A "compile to machine code" feature might well be purely beneficial, and that's simply a matter of work - how much work, for how many CPU architectures, to get how much benefit. But at least that's going to have a fairly good expectation of performance improvement.) A memory compactor might well help a narrow set of Python programs (namely, those which allocate heaps and heaps of memory, then throw away most of it, and keep running for a long time), but the complexity cost will make it unlikely to be of benefit. ChrisA From dieter at handshake.de Sat Oct 4 02:33:07 2014 From: dieter at handshake.de (dieter) Date: Sat, 04 Oct 2014 08:33:07 +0200 Subject: "High water" Memory fragmentation still a thing? References: Message-ID: <87a95cz6n0.fsf@handshake.de> Croepha writes: > Does python in general terms (apart from extensions or gc manipulation), > exhibit a "high water" type leak of allocated memory in recent python > versions (2.7+)? Likely because it is very difficult to avoid. Would you need to definitely prevent it is "memory compaction": not only is garbage collected and freed but in addition, the used memory is also relocated to form contigous blocks of used and free memory. Without memory compaction, long running processes tend to suffer from "memory fragmentation": while sufficient free memory is available, it is available only in small blocks, not large enough for some memory requests and those requests then call for more memory from the operating system. When this memory is later released, it may become split up in smaller blocks and when another large memory request arrives, new memory may be requested from the operating system (even though the original block would have been large enough). Python tries hard to limit the effect of fragmentation (maintaining the free blocks in bins of given size) but cannot eliminate it completely. In order to support memory compaction, all C extensions must adhere to a strict memory access protocol: they cannot freely use C pointers to access the memory (as the compaction may invalidate those pointers at any time) but must beforehand announce "I will now be using this pointer" (such that the compaction does not move the memory) and afterwards announce "I am no longer using this pointer" (such that memory compaction becomes again possible for this memory). As you see from the description, memory compaction presents a heavy burden for all extension writers. From marko at pacujo.net Sat Oct 4 04:27:01 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 04 Oct 2014 11:27:01 +0300 Subject: "High water" Memory fragmentation still a thing? References: Message-ID: <87d2a8s0iy.fsf@elektro.pacujo.net> dieter : > Without memory compaction, long running processes tend to suffer from > "memory fragmentation": while sufficient free memory is available, it > is available only in small blocks, not large enough for some memory > requests Now this is a question for the computer scientists. The problem is quite amenable to purely mathematical/statistical treatment. No doubt they've been at it for decades. My personal hunch is that GC in general works best with an ample amount of RAM, where "ample" means, say, ten times the minimum amount needed. As a bonus, I'm guessing the ample room would also all but remove the memory fragmentation issue. Marko From shivaji_tn at yahoo.com Sat Oct 4 05:11:43 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Sat, 4 Oct 2014 09:11:43 +0000 (UTC) Subject: Issue in printing top 20 dictionary items by dictionary value Message-ID: Hi All, I have written a function that -reads a file -splits the words and stores it in a dictionary as word(key) and the total count of word in file (value). I want to print the words with top 20 occurrences in the file in reverse order - but can't figure it out. Here is my function: def print_top(filename): #Open a file path = '/home/BCA/Documents/LearnPython/ic/' fname = path + filename print ('filename: ',fname) filetext = open(fname) #Read the file textstorage={} #print(type(textstorage)) readall = filetext.read().lower() eachword = set(readall.split()) #store split words as keys in dictionary for w in eachword: textstorage[w] = readall.count(w) #print top 20 items in dictionary by decending order of val # This bit is what I can't figure out. for dkey in (textstorage.keys()): print(dkey,sorted(textstorage[dkey]))?? From alister.nospam.ware at ntlworld.com Sat Oct 4 05:10:30 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Sat, 04 Oct 2014 09:10:30 GMT Subject: Python Basics References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <78au2a12nlq6nipske1a327p14dvgvakug@4ax.com> <542f48e7$0$13014$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, 04 Oct 2014 11:09:58 +1000, Steven D'Aprano wrote: > Chris Angelico wrote: > >> On Sat, Oct 4, 2014 at 8:54 AM, Seymore4Head >> wrote: > >>> for i in range(1,10): >>> print (str(i)*i) >> >> Seymour, please don't do this. When you "help" someone by just giving >> him the answer to a homework problem, you get him past his immediate >> issue of "I need to submit my homework for this problem". That lets him >> get through his course without understanding the code he's creating > [...] > > In fairness to Seymour, at this extremely basic level, it's really hard > to explain to somebody how to solve a problem without giving them the > answer. > > While I don't condone mindless parroting of work that others have done, > remember that for tens of thousands of years, being shown how to do > something, then imitating that, has been the most effective way for > people to learn. Dropping hints is typically the least effective > learning method. I think Chris as demonstrated that you even at this basic level you can help without giving the answer, by asking a series of leading questions that result in the student providing the answer. -- One possible reason that things aren't going according to plan is that there never was a plan in the first place. From sachin.tiwari50 at gmail.com Sat Oct 4 06:05:17 2014 From: sachin.tiwari50 at gmail.com (Sachin Tiwari) Date: Sat, 4 Oct 2014 03:05:17 -0700 (PDT) Subject: pyqt darg and drop Message-ID: <54356bfb-b05c-4f18-a855-9276297b0eee@googlegroups.com> Hi I want to drag and drop push multiple push buttons but its working for only for last button. And I want to connect them by a wire. Please help. import sys from PyQt4 import QtGui, QtCore class Button(QtGui.QPushButton): def mouseMoveEvent(self, e): if e.buttons() != QtCore.Qt.RightButton: return mimeData = QtCore.QMimeData() mimeData.setText('%d,%d' % (e.x(), e.y())) pixmap = QtGui.QPixmap.grabWidget(self) painter = QtGui.QPainter(pixmap) painter.setCompositionMode(painter.CompositionMode_DestinationIn) painter.fillRect(pixmap.rect(), QtGui.QColor(0, 0, 0, 127)) painter.end() drag = QtGui.QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) drag.setHotSpot(e.pos()) if drag.exec_(QtCore.Qt.CopyAction & QtCore.Qt.MoveAction) == QtCore.Qt.MoveAction: print 'moved' else: print 'copied' def mousePressEvent(self, e): QtGui.QPushButton.mousePressEvent(self, e) if e.button() == QtCore.Qt.LeftButton: print 'press' class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): self.setAcceptDrops(True) button = Button('Button', self) button1 = Button('Button1', self) button.move(100, 65) button1.move(200, 65) self.buttons = [button] self.setWindowTitle('Copy or Move') self.setGeometry(300, 300, 280, 150) def dragEnterEvent(self, e): e.accept() def dropEvent(self, e): mime = e.mimeData().text() x, y = map(int, mime.split(',')) if e.keyboardModifiers() & QtCore.Qt.ShiftModifier: button = Button('Button', self) button1 = Button('Button1', self) button.move(e.pos()-QtCore.QPoint(x, y)) button1.move(e.pos()-QtCore.QPoint(x, y)) button.show() button1.show() self.buttons.append(button) self.buttons.append(button1) e.setDropAction(QtCore.Qt.CopyAction) else: e.source().move(e.pos()-QtCore.QPoint(x, y)) e.setDropAction(QtCore.Qt.MoveAction) e.accept() if __name__ == '__main__': app = QtGui.QApplication(sys.argv) ex = Example() ex.show() From __peter__ at web.de Sat Oct 4 06:20:07 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 04 Oct 2014 12:20:07 +0200 Subject: Issue in printing top 20 dictionary items by dictionary value References: Message-ID: Shiva wrote: > Hi All, > > I have written a function that > -reads a file > -splits the words and stores it in a dictionary as word(key) and the total > count of word in file (value). > > I want to print the words with top 20 occurrences in the file in reverse > order - but can't figure it out. Here is my function: > > def print_top(filename): > > #Open a file > path = '/home/BCA/Documents/LearnPython/ic/' > fname = path + filename > print ('filename: ',fname) > filetext = open(fname) > > #Read the file > textstorage={} > > #print(type(textstorage)) > readall = filetext.read().lower() > eachword = set(readall.split()) > > #store split words as keys in dictionary > for w in eachword: > textstorage[w] = readall.count(w) Using count() here is very inefficient. A better approach is to increment the dict value: for w in readall.split(): textstorage[w] = textstorage.get(w, 0) + 1 > > #print top 20 items in dictionary by decending order of val > # This bit is what I can't figure out. > > for dkey in (textstorage.keys()): > print(dkey,sorted(textstorage[dkey]))?? Apart from the fact that you are sorting characters in the word at that point the sorting effort is already too late -- you need to sort the dict keys by the corresponding dict values. It is possible to write a get_value() function such that sorted(textstorage, key=get_value, reverse=True) gives the keys in the right order, but perhaps it is simpler to convert textstorage into a list of (count, word) pairs first, something like pairs = [(42, "blue"), (17, "red"), (77, "black"), ...] When you sort that list most_common_words = sorted(pairs, reverse=True) you automatically get (count, word) pairs in the right order and can print the first 20 with for count, word in most_common_words[:20]: print(word, count) PS: Once you have it all working have a look at collections.Counter... From news at blinne.net Sat Oct 4 06:28:43 2014 From: news at blinne.net (Alexander Blinne) Date: Sat, 04 Oct 2014 12:28:43 +0200 Subject: Issue in printing top 20 dictionary items by dictionary value References: Message-ID: Am 04.10.2014 um 11:11 schrieb Shiva: > Hi All, > > I have written a function that > -reads a file > -splits the words and stores it in a dictionary as word(key) and the total > count of word in file (value). > > I want to print the words with top 20 occurrences in the file in reverse > order - but can't figure it out. As python is a high-level language with a comprehensive standard library, there ought to be a built-in method to sort stuff... Wait, but there ist: sorted(iterable[, key][, reverse]) The tricky part is: a dictionary is not storing the order of its entries. But you could just go with the list of your keys, sorted by the count of your words and then go from there. > Here is my function: > > def print_top(filename): > > #Open a file > path = '/home/BCA/Documents/LearnPython/ic/' > fname = path + filename > print ('filename: ',fname) > filetext = open(fname) > > #Read the file > textstorage={} > > #print(type(textstorage)) > readall = filetext.read().lower() > eachword = set(readall.split()) > > #store split words as keys in dictionary > for w in eachword: > textstorage[w] = readall.count(w) > > #print top 20 items in dictionary by decending order of val > # This bit is what I can't figure out. orderedwords = sorted(textstorage.keys(), key=textstorage.get, reverse=True) toptwenty = orderedwords[:20] for dkey in toptwenty: print(dkey,textstorage[dkey]) The interesting part is the "key=textstorage.get"-portion. This defines according to what "key" two values of the iterable (the keys of the dict) should be compared. The method textstorage.get will accept a word and return the count of that word. This count is used to sort the words - in reverse order. Another remark: Your algorithm works, but imagine this: Your text could be more than a few lines long and contain more than a few different words. When you convert your text into the set of alle the words you have to walk through it once. You only type one line into python, but this is what python has to do at that point. Afterwards, for every single word, you use the count-method of the complete text. This also walks through the whole text - each time. So if your text has N different words you walk through it N+2 times (your readall line also walks completely through it!). It is possible to solve your problem while only walking through the text only a few (independent of N) times or even only a single time! And the larger your text gets, the more important this gets. This is not an issue in python but in all of computer science. So try and rethink your algorithm with that goal in mind: Only walk through the text once. Python makes strong use on iterators, also file objects can be used as iterators. The count in your dictionary can be updated while you walk through the text. The get-method has a keyword argument for creating default values, which might be useful here. Another thing worth of mentioning is, that python has exactly this kind of machinery already built-in (collections.Counter), but you should try and implement a simple version of it yourself as exercise. Alexander From sachin.tiwari50 at gmail.com Sat Oct 4 06:32:35 2014 From: sachin.tiwari50 at gmail.com (Sachin Tiwari) Date: Sat, 4 Oct 2014 03:32:35 -0700 (PDT) Subject: pyqt darg and drop In-Reply-To: <54356bfb-b05c-4f18-a855-9276297b0eee@googlegroups.com> References: <54356bfb-b05c-4f18-a855-9276297b0eee@googlegroups.com> Message-ID: <57535a33-01ef-4b19-8b00-2e24b0ae8ae7@googlegroups.com> On Saturday, October 4, 2014 3:35:33 PM UTC+5:30, Sachin Tiwari wrote: > Hi > > > > I want to drag and drop push multiple push buttons but its working for only for last button. And I want to connect them by a wire. > > > > Please help. > > > > import sys > > from PyQt4 import QtGui, QtCore > > > > > > class Button(QtGui.QPushButton): > > def mouseMoveEvent(self, e): > > if e.buttons() != QtCore.Qt.RightButton: > > return > > > > mimeData = QtCore.QMimeData() > > mimeData.setText('%d,%d' % (e.x(), e.y())) > > > > pixmap = QtGui.QPixmap.grabWidget(self) > > > > painter = QtGui.QPainter(pixmap) > > painter.setCompositionMode(painter.CompositionMode_DestinationIn) > > painter.fillRect(pixmap.rect(), QtGui.QColor(0, 0, 0, 127)) > > painter.end() > > > > drag = QtGui.QDrag(self) > > drag.setMimeData(mimeData) > > drag.setPixmap(pixmap) > > drag.setHotSpot(e.pos()) > > if drag.exec_(QtCore.Qt.CopyAction & QtCore.Qt.MoveAction) == QtCore.Qt.MoveAction: > > print 'moved' > > else: > > print 'copied' > > > > def mousePressEvent(self, e): > > QtGui.QPushButton.mousePressEvent(self, e) > > if e.button() == QtCore.Qt.LeftButton: > > print 'press' > > > > > > > > class Example(QtGui.QWidget): > > def __init__(self): > > super(Example, self).__init__() > > self.initUI() > > > > > > def initUI(self): > > self.setAcceptDrops(True) > > > > button = Button('Button', self) > > button1 = Button('Button1', self) > > button.move(100, 65) > > button1.move(200, 65) > > > > self.buttons = [button] > > > > self.setWindowTitle('Copy or Move') > > self.setGeometry(300, 300, 280, 150) > > > > > > def dragEnterEvent(self, e): > > e.accept() > > > > > > def dropEvent(self, e): > > mime = e.mimeData().text() > > x, y = map(int, mime.split(',')) > > > > if e.keyboardModifiers() & QtCore.Qt.ShiftModifier: > > button = Button('Button', self) > > button1 = Button('Button1', self) > > button.move(e.pos()-QtCore.QPoint(x, y)) > > button1.move(e.pos()-QtCore.QPoint(x, y)) > > button.show() > > button1.show() > > self.buttons.append(button) > > self.buttons.append(button1) > > e.setDropAction(QtCore.Qt.CopyAction) > > else: > > e.source().move(e.pos()-QtCore.QPoint(x, y)) > > e.setDropAction(QtCore.Qt.MoveAction) > > e.accept() > > > > > > if __name__ == '__main__': > > app = QtGui.QApplication(sys.argv) > > ex = Example() > > ex.show() Change this line, if drag.exec_(QtCore.Qt.CopyAction | QtCore.Qt.MoveAction) == QtCore.Qt.MoveAction: From georg at python.org Sat Oct 4 09:21:47 2014 From: georg at python.org (Georg Brandl) Date: Sat, 04 Oct 2014 15:21:47 +0200 Subject: [RELEASED] Python 3.2.6rc1, Python 3.3.6rc1 Message-ID: <542FF46B.2040109@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the release of Python 3.2.6rc1 and 3.3.6rc1. Both are release candidates for security-fix releases, which are provide source-only on python.org. The list of security-related issues fixed in the releases is given in the changelogs: https://hg.python.org/cpython/raw-file/v3.2.6rc1/Misc/NEWS https://hg.python.org/cpython/raw-file/v3.3.6rc1/Misc/NEWS To download the pre-releases visit one of: https://www.python.org/downloads/release/python-326rc1/ https://www.python.org/downloads/release/python-336rc1/ These are pre-releases, please report any bugs to http://bugs.python.org/ The final releases are scheduled one week from now. Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and contributors) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2 iEYEARECAAYFAlQv9GsACgkQN9GcIYhpnLC93gCfVm74lhOysPYCO0fy9/l5LUfJ bUYAn2u1EygfsPw2oa4CSoj5t0TYUJq7 =HnOK -----END PGP SIGNATURE----- From Seymore4Head at Hotmail.invalid Sat Oct 4 10:58:52 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sat, 04 Oct 2014 10:58:52 -0400 Subject: A little more: decimal_portion Message-ID: <2p203aldkhli65bd9crd4ljbfuab0u90oc@4ax.com> A little more: decimal_portion Write a function that takes two number parameters and returns a float that is the decimal portion of the result of dividing the first parameter by the second. (For example, if the parameters are 5 and 2, the result of 5/2 is 2.5, so the return value would be 0.5) http://imgur.com/a0Csi43 def decimal_portion(a,b): return float((b/a)-((b//a))) print (decimal_portion(5,2)) I get 0.4 and the answer is supposed to be 0.5. From rosuav at gmail.com Sat Oct 4 11:07:39 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 5 Oct 2014 01:07:39 +1000 Subject: A little more: decimal_portion In-Reply-To: <2p203aldkhli65bd9crd4ljbfuab0u90oc@4ax.com> References: <2p203aldkhli65bd9crd4ljbfuab0u90oc@4ax.com> Message-ID: On Sun, Oct 5, 2014 at 12:58 AM, Seymore4Head wrote: > A little more: decimal_portion > > Write a function that takes two number parameters and returns a float > that is the decimal portion of the result of dividing the first > parameter by the second. (For example, if the parameters are 5 and 2, > the result of 5/2 is 2.5, so the return value would be 0.5) > > http://imgur.com/a0Csi43 > > def decimal_portion(a,b): > return float((b/a)-((b//a))) > > print (decimal_portion(5,2)) > > I get 0.4 and the answer is supposed to be 0.5. Work out exactly what your program is doing, step by step. Print out the intermediate steps in the calculation, and compare what the program's doing to what you expect to be happening. What's (b/a)? What's (b//a)? What's (b/a)-((b//a))? ChrisA From Seymore4Head at Hotmail.invalid Sat Oct 4 11:16:50 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sat, 04 Oct 2014 11:16:50 -0400 Subject: A little more: decimal_portion References: <2p203aldkhli65bd9crd4ljbfuab0u90oc@4ax.com> Message-ID: <7j303a9e0g7ipe7se3s5qc364nurjrcknp@4ax.com> On Sun, 5 Oct 2014 01:07:39 +1000, Chris Angelico wrote: >On Sun, Oct 5, 2014 at 12:58 AM, Seymore4Head > wrote: >> A little more: decimal_portion >> >> Write a function that takes two number parameters and returns a float >> that is the decimal portion of the result of dividing the first >> parameter by the second. (For example, if the parameters are 5 and 2, >> the result of 5/2 is 2.5, so the return value would be 0.5) >> >> http://imgur.com/a0Csi43 >> >> def decimal_portion(a,b): >> return float((b/a)-((b//a))) >> >> print (decimal_portion(5,2)) >> >> I get 0.4 and the answer is supposed to be 0.5. > >Work out exactly what your program is doing, step by step. Print out >the intermediate steps in the calculation, and compare what the >program's doing to what you expect to be happening. What's (b/a)? >What's (b//a)? What's (b/a)-((b//a))? > >ChrisA I did. I included a screenshot of me doing just that. The formula seems to work in the shell, but does not work as a function, or I am missing something subtle again. From rosuav at gmail.com Sat Oct 4 11:24:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 5 Oct 2014 01:24:40 +1000 Subject: A little more: decimal_portion In-Reply-To: <7j303a9e0g7ipe7se3s5qc364nurjrcknp@4ax.com> References: <2p203aldkhli65bd9crd4ljbfuab0u90oc@4ax.com> <7j303a9e0g7ipe7se3s5qc364nurjrcknp@4ax.com> Message-ID: On Sun, Oct 5, 2014 at 1:16 AM, Seymore4Head wrote: > I did. I included a screenshot of me doing just that. > The formula seems to work in the shell, but does not work as a > function, or I am missing something subtle again. Ah, I don't generally click screenshots. Have the function print out exactly what it's doing at each step. See how that compares to your hand-worked version. You'll see the problem. ChrisA From Seymore4Head at Hotmail.invalid Sat Oct 4 11:38:52 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sat, 04 Oct 2014 11:38:52 -0400 Subject: A little more: decimal_portion References: <2p203aldkhli65bd9crd4ljbfuab0u90oc@4ax.com> <7j303a9e0g7ipe7se3s5qc364nurjrcknp@4ax.com> Message-ID: On Sun, 5 Oct 2014 01:24:40 +1000, Chris Angelico wrote: >On Sun, Oct 5, 2014 at 1:16 AM, Seymore4Head > wrote: >> I did. I included a screenshot of me doing just that. >> The formula seems to work in the shell, but does not work as a >> function, or I am missing something subtle again. > >Ah, I don't generally click screenshots. > >Have the function print out exactly what it's doing at each step. See >how that compares to your hand-worked version. You'll see the problem. > >ChrisA That worked. Thanks From steve+comp.lang.python at pearwood.info Sat Oct 4 11:46:03 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 05 Oct 2014 01:46:03 +1000 Subject: A little more: decimal_portion References: <2p203aldkhli65bd9crd4ljbfuab0u90oc@4ax.com> Message-ID: <5430163c$0$12998$c3e8da3$5496439d@news.astraweb.com> Seymore4Head wrote: > A little more: decimal_portion > > Write a function that takes two number parameters and returns a float > that is the decimal portion of the result of dividing the first > parameter by the second. (For example, if the parameters are 5 and 2, > the result of 5/2 is 2.5, so the return value would be 0.5) > > http://imgur.com/a0Csi43 > > def decimal_portion(a,b): > return float((b/a)-((b//a))) > > print (decimal_portion(5,2)) > > I get 0.4 and the answer is supposed to be 0.5. Hint: given arguments a=5, b=2, you want 5/2. What do you calculate? Look at the order of the arguments a and b in the function def line, and in the calculations you perform. Once you fix that, I can suggest a more efficient way of calculating the answer: use the modulo operator % Given arguments 5 and 2, you want 0.5 == 1/2, and 5%2 returns 1. Given arguments 6 and 2, you want 0.0 == 0/2, and 6%2 returns 0. Given arguments 8 and 3, you want 0.6666... == 2/3, and 8%3 returns 2. P.S. the usual name for this function is "fraction part", sometimes "fp". -- Steven From th982a at googlemail.com Sat Oct 4 11:52:18 2014 From: th982a at googlemail.com (Tamer Higazi) Date: Sat, 04 Oct 2014 17:52:18 +0200 Subject: Looking for volunteers developing wsgi Webmailer Application! Message-ID: <543017B2.80707@googlemail.com> Hi people! I am planing to develop on longer time a n open source Webmailer written in Python (not 2.7.x) with: bottle.py zca, zope.interface Mail sasl and/or dovecot python-slimta-piperelay a wsgi webmailer which could be easily added in uWSGI. I am looking for people, who'd like to contribute got some time... Cheers, Tamer From Seymore4Head at Hotmail.invalid Sat Oct 4 12:11:41 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sat, 04 Oct 2014 12:11:41 -0400 Subject: A little more: decimal_portion References: <2p203aldkhli65bd9crd4ljbfuab0u90oc@4ax.com> <5430163c$0$12998$c3e8da3$5496439d@news.astraweb.com> Message-ID: <1q603apbgntesrvcjd9t0ieq5nqa4rs1es@4ax.com> On Sun, 05 Oct 2014 01:46:03 +1000, Steven D'Aprano wrote: >Seymore4Head wrote: > >> A little more: decimal_portion >> >> Write a function that takes two number parameters and returns a float >> that is the decimal portion of the result of dividing the first >> parameter by the second. (For example, if the parameters are 5 and 2, >> the result of 5/2 is 2.5, so the return value would be 0.5) >> >> http://imgur.com/a0Csi43 >> >> def decimal_portion(a,b): >> return float((b/a)-((b//a))) >> >> print (decimal_portion(5,2)) >> >> I get 0.4 and the answer is supposed to be 0.5. > >Hint: given arguments a=5, b=2, you want 5/2. What do you calculate? Look at >the order of the arguments a and b in the function def line, and in the >calculations you perform. > >Once you fix that, I can suggest a more efficient way of calculating the >answer: use the modulo operator % > >Given arguments 5 and 2, you want 0.5 == 1/2, and 5%2 returns 1. > >Given arguments 6 and 2, you want 0.0 == 0/2, and 6%2 returns 0. > >Given arguments 8 and 3, you want 0.6666... == 2/3, and 8%3 returns 2. > > >P.S. the usual name for this function is "fraction part", sometimes "fp". Yeah, I caught my mistake. Thanks for the suggestions. I was expecting a lesson in rounding errors, so I had ruled out the error was on my part. (Something I should never do) From shivaji_tn at yahoo.com Sat Oct 4 13:36:52 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Sat, 4 Oct 2014 17:36:52 +0000 (UTC) Subject: Issue in printing top 20 dictionary items by dictionary value References: Message-ID: It works : orderedwords = sorted(textstorage.keys(), key=textstorage.get) The method textstorage.get will accept a word and return it's value which in this instance is the count. What I don't understand is: for w in eachword: textstorage[w]=textstorage.get(w, 0) + 1 How does textstorage.get(w,0)+1 give the count of the word?? Thanks, Shiva From pkpearson at nowhere.invalid Sat Oct 4 13:42:41 2014 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 4 Oct 2014 17:42:41 GMT Subject: Python Basics References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <78au2a12nlq6nipske1a327p14dvgvakug@4ax.com> <542f48e7$0$13014$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, 04 Oct 2014 11:09:58 +1000, Steven D'Aprano wrote: > Chris Angelico wrote: > >> On Sat, Oct 4, 2014 at 8:54 AM, Seymore4Head >> wrote: > >>> for i in range(1,10): >>> print (str(i)*i) >> >> Seymour, please don't do this. When you "help" someone by just giving >> him the answer to a homework problem, you get him past his immediate >> issue of "I need to submit my homework for this problem". That lets >> him get through his course without understanding the code he's >> creating > [...] > > In fairness to Seymour, at this extremely basic level, it's really hard to > explain to somebody how to solve a problem without giving them the answer. > > While I don't condone mindless parroting of work that others have done, > remember that for tens of thousands of years, being shown how to do > something, then imitating that, has been the most effective way for people > to learn. Dropping hints is typically the least effective learning method. This has gotta be the most civilised newsgroup on the Net. Kudos to you stalwarts who keep it that way. Personally, I thought Tobiah's hint, printing 'a'*4, would be just what the OP needed. -- To email me, substitute nowhere->runbox, invalid->com. From sturla.molden at gmail.com Sat Oct 4 13:51:28 2014 From: sturla.molden at gmail.com (Sturla Molden) Date: Sat, 4 Oct 2014 17:51:28 +0000 (UTC) Subject: "High water" Memory fragmentation still a thing? References: <542f8a27$0$12998$c3e8da3$5496439d@news.astraweb.com> Message-ID: <2052462891434137817.308933sturla.molden-gmail.com@news.gmane.org> Steven D'Aprano wrote: > [Aside: The thing that people fail to understand is that the GIL is not in > fact something which *prevents* multi-tasking, but it *enables* cooperative > multi-tasking: > > http://www.dabeaz.com/python/GIL.pdf > > although that's not to say that there aren't some horrible performance > characteristics of the GIL. David Beazley has identified issues with the > GIL which suggest room for improving the GIL and avoiding "GIL battles" > which are responsible for much of the overhead of CPU-bound threads. Any C > programmers who want to hack on the interpreter core?] Didn't the "new GIL" fix some of these problems? Sturla From denismfmcmahon at gmail.com Sat Oct 4 13:52:45 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sat, 4 Oct 2014 17:52:45 +0000 (UTC) Subject: Looking for volunteers developing wsgi Webmailer Application! References: Message-ID: On Sat, 04 Oct 2014 17:52:18 +0200, Tamer Higazi wrote: > I am planing to develop on longer time a n open source Webmailer written > in Python (not 2.7.x) with: Because the world really needs another webmailer spamengine. -- Denis McMahon, denismfmcmahon at gmail.com From drsalists at gmail.com Sat Oct 4 15:29:51 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Sat, 4 Oct 2014 12:29:51 -0700 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: References: Message-ID: On Fri, Oct 3, 2014 at 1:01 PM, Skip Montanaro wrote: > On Fri, Oct 3, 2014 at 1:36 PM, Croepha > wrote: > >> Long running Python jobs that consume a lot of memory while >> running may not return that memory to the operating system >> until the process actually terminates, even if everything is >> garbage collected properly. > The problem boils down to how the program dynamically allocates > and frees memory, and how the malloc subsystem interacts with > the kernel through the brk and sbrk system calls. (Anywhere I > mention "brk", you can mentally replace it with "sbrk". They do > the same thing - ask for memory from or return memory to the > kernel - using a different set of units, memory addresses or > bytes.) In the general case, programmers call malloc (or > calloc, or realloc) to allocate a chunk of storage from the > heap. (I'm ignoring anything special which Python has layered > on top of malloc. It can mitigate problems, but I don't think > it will fundamentally change the way malloc interacts with the > kernel.) The malloc subsystem maintains a free list (recently > freed bits of memory) from which it can allocate memory without > traipsing off to the kernel. If it can't return a chunk of > memory from the free list, it will (in the most simpleminded > malloc implementation) call brk to grab a new (large) chunk of > memory. The system simply moves the end of the program's > "break", effectively increasing or decreasing the (virtual) size > of the running program. That memory is then doled out to the > user by malloc. If, and only if, every chunk of memory in the > last chunk allocated by a call to brk is placed on malloc's free > list, *and* if the particular malloc implementation on your box > is smart enough to coalesce adjacent chunks of freed memory back > into brk-sized memory chunks, can brk be called once again to > reduce the program's footprint. Actually, ISTR hearing that glibc's malloc+free will use mmap+munmap to allocate and release chunks of memory, to avoid fragmentation. Digging around on the 'net a bit, it appears that glibc's malloc does do this (so on most Linux systems), but only for contiguous chunks of memory above 128K in size. Here's a pair of demonstration programs (one in C, one in CPython 3.4), which when run under strace on a Linux system, appear to show that mmap and munmap are being used: http://stromberg.dnsalias.org/~strombrg/malloc-and-sbrk.html HTH From python at mrabarnett.plus.com Sat Oct 4 15:40:18 2014 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 04 Oct 2014 20:40:18 +0100 Subject: Issue in printing top 20 dictionary items by dictionary value In-Reply-To: References: Message-ID: <54304D22.6030209@mrabarnett.plus.com> On 2014-10-04 18:36, Shiva wrote: > It works : > orderedwords = sorted(textstorage.keys(), key=textstorage.get) > > The method textstorage.get will accept a word and return it's value > which in this instance is the count. > > What I don't understand is: > > for w in eachword: > textstorage[w]=textstorage.get(w, 0) + 1 > > How does textstorage.get(w,0)+1 give the count of the word?? > What textstorage.get(w, 0) says is: if the word is in the dict, return its count, else return 0. From th982a at googlemail.com Sat Oct 4 16:04:16 2014 From: th982a at googlemail.com (Tamer Higazi) Date: Sat, 04 Oct 2014 22:04:16 +0200 Subject: Looking for volunteers developing wsgi Webmailer Application! In-Reply-To: References: Message-ID: <543052C0.6040803@googlemail.com> Because the world really needs this crap that is developed in php5, or big Personal Information Management Systems like Horde, what often nobody needs..... Am 04.10.2014 um 19:52 schrieb Denis McMahon: > On Sat, 04 Oct 2014 17:52:18 +0200, Tamer Higazi wrote: > >> I am planing to develop on longer time a n open source Webmailer written >> in Python (not 2.7.x) with: > > Because the world really needs another webmailer spamengine. > From orgnut at yahoo.com Sat Oct 4 17:44:20 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Sat, 04 Oct 2014 14:44:20 -0700 Subject: Issue in printing top 20 dictionary items by dictionary value In-Reply-To: References: Message-ID: On 10/04/2014 10:36 AM, Shiva wrote: > > What I don't understand is: > > for w in eachword: > textstorage[w]=textstorage.get(w, 0) + 1 > > How does textstorage.get(w,0)+1 give the count of the word?? > Very long-winded explanation: (But to shorten it a bit, I'm going to use ts in place of textstorage. Also lhs = left-hand-side and rhs = right-hand-side.) What we're trying to do here is to update the word count. We could (erroneously) write it as: ts[w] = ts[w] + 1 If w already exists in the ts dictionary, this works fine. But if it does not it will abort with a KeyError when it comes to the ts[w] on the rhs of the assignment. The get() method is an alternate way of accessing the value of a key in a dictionary, but with a default value given as well. Now let's break down the statement ts[w] = ts.get(w, 0) + 1 Case 1: w already exists in the ts dictionary: ts.get(w, 0) gets the value of ts[w] (the current word count), adds 1, which is then used to update the word-count value of ts[w] (on the lhs of the assignment). case2: w does not exist in the ts dictionary: ts.get(w, 0) gives the default value of 0, and 1 is added to that. ts[w] on the lhs of the assignment does not exist, so a new entry is created in the ts dictionary with the given w as the key, and the value is initialized with the 1 from the get()+1. Make sense? -=- Larry -=- From antoine at python.org Sat Oct 4 20:10:38 2014 From: antoine at python.org (Antoine Pitrou) Date: Sun, 5 Oct 2014 00:10:38 +0000 (UTC) Subject: "High water" Memory fragmentation still a thing? References: Message-ID: Christian Heimes python.org> writes: > > The article doesn't state if the writer is referring to virtual memory > or resident set size. Actually the article mentions the following recipe: resource.getrusage(resource.RUSAGE_SELF).ru_maxrss which means the author is probably looking at resident set size. Regards Antoine. From denismfmcmahon at gmail.com Sat Oct 4 21:11:40 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sun, 5 Oct 2014 01:11:40 +0000 (UTC) Subject: Issue in printing top 20 dictionary items by dictionary value References: Message-ID: On Sat, 04 Oct 2014 09:11:43 +0000, Shiva wrote: > I have written a function that -reads a file -splits the words and > stores it in a dictionary as word(key) and the total count of word in > file (value). > > I want to print the words with top 20 occurrences in the file in reverse > order - but can't figure it out. Here is my function: Once you've generated your dictionary, use a list comprehension to turn it into a list of tuples of ( word, count ). Sort the list of tuples according to the count element. Select the top 20. copy it to a new list and reverse that list. now loop through the second list and print results. -- Denis McMahon, denismfmcmahon at gmail.com From python at mrabarnett.plus.com Sat Oct 4 21:41:07 2014 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 05 Oct 2014 02:41:07 +0100 Subject: Issue in printing top 20 dictionary items by dictionary value In-Reply-To: References: Message-ID: <5430A1B3.9030509@mrabarnett.plus.com> On 2014-10-05 02:11, Denis McMahon wrote: > On Sat, 04 Oct 2014 09:11:43 +0000, Shiva wrote: > >> I have written a function that -reads a file -splits the words and >> stores it in a dictionary as word(key) and the total count of word >> in file (value). >> >> I want to print the words with top 20 occurrences in the file in >> reverse order - but can't figure it out. Here is my function: > > Once you've generated your dictionary, use a list comprehension to > turn it into a list of tuples of ( word, count ). Sort the list of > tuples according to the count element. Select the top 20. copy it to > a new list and reverse that list. now loop through the second list > and print results. > You don't need a list comprehension to turn it into a list of tuples, and you don't need to sort and reverse as separate steps. In fact, there's a class in the collections module that'll do virtually all of the work for you! From b3mb4m at gmail.com Sat Oct 4 22:41:48 2014 From: b3mb4m at gmail.com (Dymond Simon) Date: Sat, 4 Oct 2014 19:41:48 -0700 (PDT) Subject: How donwnload youtube videos? Message-ID: <70bfe236-94e7-4d21-8fc9-50b701ae80c5@googlegroups.com> Hi guys .. Uhm, ? have to download youtube videos ? was tried urlretrive but doesn't work ? have no idea that's why.So there is my question, "we cant donwload youtube videos directly ? ". From rosuav at gmail.com Sat Oct 4 22:49:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 5 Oct 2014 13:49:01 +1100 Subject: How donwnload youtube videos? In-Reply-To: <70bfe236-94e7-4d21-8fc9-50b701ae80c5@googlegroups.com> References: <70bfe236-94e7-4d21-8fc9-50b701ae80c5@googlegroups.com> Message-ID: On Sun, Oct 5, 2014 at 1:41 PM, Dymond Simon wrote: > Uhm, ? have to download youtube videos ? was tried urlretrive but doesn't work ? have no idea that's why.So there is my question, "we cant donwload youtube videos directly ? ". > Look up youtube-dl - it's written in Python. :) ChrisA From shivaji_tn at yahoo.com Sun Oct 5 02:58:50 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Sun, 5 Oct 2014 06:58:50 +0000 (UTC) Subject: Issue in printing top 20 dictionary items by dictionary value References: Message-ID: Larry Hudson yahoo.com.dmarc.invalid> writes: > > On 10/04/2014 10:36 AM, Shiva wrote: > > > > What I don't understand is: > > > > for w in eachword: > > textstorage[w]=textstorage.get(w, 0) + 1 > > > > How does textstorage.get(w,0)+1 give the count of the word?? > > > > Very long-winded explanation: (But to shorten it a bit, I'm going to use ts in place of > textstorage. Also lhs = left-hand-side and rhs = right-hand-side.) > > What we're trying to do here is to update the word count. We could (erroneously) write it as: > > ts[w] = ts[w] + 1 > > If w already exists in the ts dictionary, this works fine. But if it does not it will abort > with a KeyError when it comes to the ts[w] on the rhs of the assignment. > > The get() method is an alternate way of accessing the value of a key in a dictionary, but with a > default value given as well. Now let's break down the statement > > ts[w] = ts.get(w, 0) + 1 > > Case 1: w already exists in the ts dictionary: > > ts.get(w, 0) gets the value of ts[w] (the current word count), adds 1, which is then used to > update the word-count value of ts[w] (on the lhs of the assignment). > > case2: w does not exist in the ts dictionary: > > ts.get(w, 0) gives the default value of 0, and 1 is added to that. ts[w] on the lhs of the > assignment does not exist, so a new entry is created in the ts dictionary with the given w as > the key, and the value is initialized with the 1 from the get()+1. > > Make sense? > > -=- Larry -=- > > Hi Larry, Thanks for the explanation - I was a bit confused as get() operation in this case would have got None for words occurring the first time. Now I understand by writing a small example in the interpreter: >>> dt={} >>> splitw=('aa','bb','cc') >>> for w in splitw: ... dt[w]=dt.get(w,0) ... >>> dt {'cc': 0, 'bb': 0, 'aa': 0} So we just increment 0 to 1 for count. Thanks, Pradeep From wxjmfauth at gmail.com Sun Oct 5 03:14:59 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sun, 5 Oct 2014 00:14:59 -0700 (PDT) Subject: A little more: decimal_portion In-Reply-To: <1q603apbgntesrvcjd9t0ieq5nqa4rs1es@4ax.com> References: <2p203aldkhli65bd9crd4ljbfuab0u90oc@4ax.com> <5430163c$0$12998$c3e8da3$5496439d@news.astraweb.com> <1q603apbgntesrvcjd9t0ieq5nqa4rs1es@4ax.com> Message-ID: <47dfa759-6e6b-41c8-9d90-cb974fff43e0@googlegroups.com> Le samedi 4 octobre 2014 18:13:27 UTC+2, Seymore4Head a ?crit?: > On Sun, 05 Oct 2014 01:46:03 +1000, Steven D'Aprano > > wrote: > > > > >Seymore4Head wrote: > > > > > >> A little more: decimal_portion > > >> > > >> Write a function that takes two number parameters and returns a float > > >> that is the decimal portion of the result of dividing the first > > >> parameter by the second. (For example, if the parameters are 5 and 2, > > >> the result of 5/2 is 2.5, so the return value would be 0.5) > > >> > > >> http://imgur.com/a0Csi43 > > >> > > >> def decimal_portion(a,b): > > >> return float((b/a)-((b//a))) > > >> > > >> print (decimal_portion(5,2)) > > >> > > >> I get 0.4 and the answer is supposed to be 0.5. > > > > > >Hint: given arguments a=5, b=2, you want 5/2. What do you calculate? Look at > > >the order of the arguments a and b in the function def line, and in the > > >calculations you perform. > > > > > >Once you fix that, I can suggest a more efficient way of calculating the > > >answer: use the modulo operator % > > > > > >Given arguments 5 and 2, you want 0.5 == 1/2, and 5%2 returns 1. > > > > > >Given arguments 6 and 2, you want 0.0 == 0/2, and 6%2 returns 0. > > > > > >Given arguments 8 and 3, you want 0.6666... == 2/3, and 8%3 returns 2. > > > > > > > > >P.S. the usual name for this function is "fraction part", sometimes "fp". > > > > Yeah, I caught my mistake. Thanks for the suggestions. > > I was expecting a lesson in rounding errors, so I had ruled out the > > error was on my part. (Something I should never do) %%%%% >>> # hints >>> a = 5 / 2 >>> a - floor(a) 0.5 >>> >>> import math >>> math.modf(a) (0.5, 2.0) >>> math.modf(pi) (0.14159265358979312, 3.0) >>> From shivaji_tn at yahoo.com Sun Oct 5 05:36:53 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Sun, 5 Oct 2014 09:36:53 +0000 (UTC) Subject: re search through a text Vs line Message-ID: Hi, I am doing a regular expression search for a year through a file. fileextract = open(fullfilename,'r') line = fileextract.read() texts = re.search(r'1\d\d\d', line) print(texts.group()) The above works. However if I do: fileextract = open(fullfilename,'r') line = fileextract.readlines() for l in line: texts = re.search(r'1\d\d\d', line) print(texts.group()) None is returned. Why is it not iterating through each line of the file and doing a search? - It seems to return none. Thanks, Shiva From steve+comp.lang.python at pearwood.info Sun Oct 5 06:28:49 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 05 Oct 2014 21:28:49 +1100 Subject: How donwnload youtube videos? References: <70bfe236-94e7-4d21-8fc9-50b701ae80c5@googlegroups.com> Message-ID: <54311d62$0$12994$c3e8da3$5496439d@news.astraweb.com> Dymond Simon wrote: > Hi guys .. > > Uhm, ? have to download youtube videos ? was tried urlretrive but doesn't > work ? have no idea that's why.So there is my question, "we cant donwload > youtube videos directly ? ". "Doesn't work". Could you be more specific? Although some of us are very smart, or at least like to think we are very smart, none of us can read your mind. There could easily be a dozen or more reasons why it "doesn't work". - Your disk is full and you can't save the downloaded video. - You're trying to save to a folder that doesn't exist. - Or one that you don't have permission to write to. - Or to read-only media. - Or your hard drive has developed a fault. - Youtube is down. - Youtube is blocked on your network. - You have a virus which is redirecting http:///youtube.com to somewhere else. - Somebody accidentally unplugged the network cable. - Your ISP is having routing difficulties. - You accidentally got the URL wrong and are trying to download from yuotube.com. - Youtube is blocking your IP address. - Youtube is blocking your user-agent. - You don't understand the process for getting the URL of the actual video file. - You don't have Python installed. - Your script is buggy. - Or you simply forgot to press Enter and the script is just sitting there, waiting. -- Steven From davea at davea.name Sun Oct 5 07:57:50 2014 From: davea at davea.name (Dave Angel) Date: Sun, 5 Oct 2014 07:57:50 -0400 (EDT) Subject: re search through a text Vs line References: Message-ID: Shiva Wrote in message: > Hi, > > I am doing a regular expression search for a year through a file. > I think you are being confused in part by your choice of names. Let's go through and describe the variable contents. > fileextract = open(fullfilename,'r') > line = fileextract.read() 'line' is a single string containing all the lines in the file. > texts = re.search(r'1\d\d\d', line) > print(texts.group()) > > The above works. > > However if I do: > fileextract = open(fullfilename,'r') > line = fileextract.readlines() Now, 'line' is a list, with each item of the list being a string. The name is very misleading, and should be something like 'lines' > > for l in line: > texts = re.search(r'1\d\d\d', line) The second argument here is a list, not a string. You probably meant to search the variable named 'l' . Of course if you renamed things, then you might have a loop of for line in lines: And after that change, your search call would be correct again. > print(texts.group()) Here you look only at the last result. You probably want this line indented., so it's part of the loop. > > > None is returned. Why is it not iterating through each line of the file and > doing a search? - It seems to return none. > re.search only searches strings. Other comments. You neglected to close the files. Doesn?t hurt here, but it's best to get into good habits. Look up the with statement. The readlines call was unnecessary, as you could have iterated oner the file object. for line in fileextract: Your regexp won't match recent years. And it will match numbers like 51420, 1994333, and so on. Perhaps you want to restrict where in the line those four digits may be. When asking questions, it is frequently useful to specify Python version. -- DaveA From shivaji_tn at yahoo.com Sun Oct 5 13:08:49 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Sun, 5 Oct 2014 17:08:49 +0000 (UTC) Subject: re search through a text Vs line References: Message-ID: OK, Hi Dave, I modified it as below and it works....(If there is a way to make this more efficient please let me know) By the way I am using Python 3.4 import sys import re def extract_names(filename): path = '/home/LearnPython/exercises/' fullfilename = path+filename print('fullfilename: ',fullfilename) fileextract = open(fullfilename,'r') #line = fileextract.readlines() #print(line) for l in fileextract: #print(l) texts = re.search(r'\d\d\d\d', l) if texts: print(texts.group()) #print(texts.group()) #return texts.group() fileextract.close() extract_names('NOTICE.txt') Thanks, Shiva From none at mailinator.com Sun Oct 5 15:23:42 2014 From: none at mailinator.com (mm0fmf) Date: Sun, 05 Oct 2014 20:23:42 +0100 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: <542f470b$0$13003$c3e8da3$5496439d@news.astraweb.com> References: <542f470b$0$13003$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4VgYv.348787$NQ4.188655@fx26.am4> On 04/10/2014 02:02, Steven D'Aprano wrote: > Way back in the mid 1980s, Apple Macintoshes used a memory manager which > could move memory around. But the memory manager didn't return a pointer to memory the way malloc does. It returned a pointer to the pointer and you had to double dereference it to get the heap address (ISTR, 30 years ago now). The advantage being the memory manager could shuffle the memory about and update the pointers. Your pointer to a pointer would still point to the same block after a shuffle. Of course you couldn't hold on to a partial dereference across system calls... can you guess why? :-) Linux has (had) a allocation scheme where blocks came from different sized areas depending on the size requested. So all requests below 4k came from one heap area, and so on for 16k, 64k 256k, 1M etc. Meaning that code requesting a freeing up small amounts fragged the small allocation zone and so a big allocation would die due to fragmentation of small amounts. That was in kernel 2.4 days, sorry I'm off the bleeding edge now with how the allocator works in modern kernels. Andy From auriocus at gmx.de Sun Oct 5 15:26:35 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sun, 05 Oct 2014 21:26:35 +0200 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk In-Reply-To: References: Message-ID: Am 04.10.14 07:53, schrieb Ned Deily: > In article , > Kevin Walzer wrote: >> A Tcl library compiled for 8.5 can be loaded into 8.6 with no >> re-compiling required because of stubs. > > It has nothing to do with Python per se; that's just the way linking > with OS frameworks work. > [...] > > When Python or other programs link with a framework, they use the cc or > ld -framework option, rather than -l: > -framework Tcl -framework Tk > > That causes the linker to look in the default search paths for > frameworks, /Library/Frameworks followed by /System/Library/Frameworks. > The install names of the framework shared libraries used are embedded in > the Mach-O file (executable, bundle, or shared library) produced by ld. > So the stub library archive is there but is not used, AFAIK. Then it is done in a non-optimal way, though admittedly in the case of Tkinter, which is a hybrid Python/Tcl extension, the optimal way is not obvious. In the Tcl world, there are two different ways to link to Tcl (and analogously to Tk): A) you can link directly to libtcl.dylib (.so, .dll) B) you can define USE_TCL_STUBS during compilation and link to libtclstub.a If you embed an interpreter, you must do A. So for Tkinter, linking directly to the dynamic lib (== -framework in OSX) is correct. If you extend an interpreter by defining new commands, new Tcl_Obj, new Tk image types etc., you can do either A or B, but the recommended way is always B because this makes it possible to load an extension into any later interpreter than the one it was compiled against. The magic behind stubs are macros which replace function calls by invocations of an index into a function pointer table; that table is initialized at runtime, when the extension calls Tcl_InitStubs(). Now, tkagg is not loaded by the Tcl load() command. This means that after loading via Pythons import, the stub table should be initialized. Obviously this is not the case; if I'm not mistaken, just before this line https://github.com/matplotlib/matplotlib/blob/master/src/_tkagg.cpp#L252 if you insert Tcl_InitStubs(interp, TCL_VERSION, 0); Tk_InitStubs(interp, TCL_VERSION, 0); then it should be possible to compile tkagg with -DUSE_TCL_STUBS -DUSE_TK_STUBS, link to tclstub and tkstub and load the resulting tkagg into any Tkinter that links to an interpreter at least as new as TCL_VERSION. (If the result of either call is NULL, the interpreter is too old). Admittedly I'm too lazy to setup a build environment for matplotlib to try if this actually works. > > There may be other ways to do it but that's how Python has always linked > to Tcl and Tk. FWIW, that's how both Apple's and ActiveState's wish > executables are linked as well: wish is a type A program, it creates an interpreter and therefore must link to the actual library. So is Tkinter. But Tkagg is not, it extends a preexisting interpreter. Christian From davea at davea.name Sun Oct 5 16:12:52 2014 From: davea at davea.name (Dave Angel) Date: Sun, 5 Oct 2014 16:12:52 -0400 (EDT) Subject: re search through a text Vs line References: Message-ID: Shiva Wrote in message: > OK, > Hi Dave, > > I modified it as below and it works....(If there is a way to make this more > efficient please let me know) > Deends on what you mean by efficiency. The big memory efficiency gain was when you got rid of either the read or readlines. Performance is pretty irrelevant, since disk I/O, unicode processing, and terminal processing are likely to dominate. Programmer efficiency is usually more important than either of those. First thing is to pick better names, and/or comment what the cryptic names mean. And avoid any names that look like numbers. Next are to add in the shebang and encoding commands. You could replace fileextract = open(fullfilename,'r') With with open(fullfilename,'r') as fileextract: And indent the code that uses the file. That way it's clearer, you don't need the separate close, and it will be closed no matter how you leave that scope, whether a return statement or exception. Finally you could indent by 4 spaces instead of 1. HTH -- DaveA From nad at acm.org Sun Oct 5 16:33:30 2014 From: nad at acm.org (Ned Deily) Date: Sun, 05 Oct 2014 13:33:30 -0700 Subject: Python 3.4.1 installer on Mac links Python to old Tcl/Tk References: Message-ID: In article , Christian Gollwitzer wrote: [... much good stuff deleted ... ] > wish is a type A program, it creates an interpreter and therefore must > link to the actual library. So is Tkinter. But Tkagg is not, it extends > a preexisting interpreter. Thanks, Christian. That's a good summary, I think. After some more research, I agree with your conclusion that the stubs library approach does not apply to the case of embedding Tcl ("type A") which is what Python tkinter does. As far as matplotlib or PIL/Pillow or other third-party packages that may extend Tck/Tk, it might be helpful to open an issue with suggested code on the various projects' issue trackers if someone cares to pursue this. -- Ned Deily, nad at acm.org From Seymore4Head at Hotmail.invalid Sun Oct 5 17:17:32 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 05 Oct 2014 17:17:32 -0400 Subject: Timezones Message-ID: This is not a new video, but it is new to me. https://www.youtube.com/watch?v=-5wpm-gesOY Any links to some easy to follow time zone math? From breamoreboy at yahoo.co.uk Sun Oct 5 18:15:18 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 05 Oct 2014 23:15:18 +0100 Subject: Timezones In-Reply-To: References: Message-ID: On 05/10/2014 22:17, Seymore4Head wrote: > This is not a new video, but it is new to me. > https://www.youtube.com/watch?v=-5wpm-gesOY > > Any links to some easy to follow time zone math? > My advice is to avoid time zones, they're a real pain, seriously. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From Seymore4Head at Hotmail.invalid Sun Oct 5 19:02:31 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 05 Oct 2014 19:02:31 -0400 Subject: Practice question Message-ID: For the record, I don't want a hint. I want the answer. I see a practice question is similar to this. 15 <= x < 30 And it wants a similar expression that is equivalent. So the right answer is 15<= x or x <30 but one of the other answers is not (15<= x and x <30) But it says.....remember you can try this out in the Python shell. How? From roy at panix.com Sun Oct 5 19:06:31 2014 From: roy at panix.com (Roy Smith) Date: Sun, 05 Oct 2014 19:06:31 -0400 Subject: Practice question References: Message-ID: In article , Seymore4Head wrote: > For the record, I don't want a hint. I want the answer. 42. From ned at nedbatchelder.com Sun Oct 5 19:14:27 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 05 Oct 2014 19:14:27 -0400 Subject: Practice question In-Reply-To: References: Message-ID: On 10/5/14 7:02 PM, Seymore4Head wrote: > For the record, I don't want a hint. I want the answer. > I see a practice question is similar to this. > 15 <= x < 30 And it wants a similar expression that is equivalent. > So the right answer is 15<= x or x <30 No, "15 <= x < 30" is equivalent to "15 <= x and x < 30". > but one of the other answers is > not (15<= x and x <30) You are speaking ambiguously. Which did you mean: a) one of the other answers isn't "15 <= x and x < 30", or: b) one of the other answers is "not (15 <= x and x < 30)" ? -- Ned Batchelder, http://nedbatchelder.com From skip.montanaro at gmail.com Sun Oct 5 19:33:49 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Sun, 5 Oct 2014 18:33:49 -0500 Subject: Practice question In-Reply-To: References: Message-ID: On Oct 5, 2014 6:07 PM, "Seymore4Head" wrote: > > For the record, I don't want a hint. I want the answer. > I see a practice question is similar to this. > 15 <= x < 30 And it wants a similar expression that is equivalent. Maybe 30 > x >= 15 ? Seems more "similar" to the original expression than the other possibilities. As to how to try it out, bring up the Python prompt, assign various values to x, and keep evaluating the possibilities. To simplify evaluation off a bunch of alternatives, consider defining a function which takes x add a parameter and print out the various expression values. I'd give a concrete example, but don't has a prompt available on my phone... Just my 2?... Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Oct 5 19:47:40 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 05 Oct 2014 19:47:40 -0400 Subject: Practice question In-Reply-To: References: Message-ID: On 10/5/2014 7:02 PM, Seymore4Head wrote: > For the record, I don't want a hint. I want the answer. > I see a practice question is similar to this. > 15 <= x < 30 And it wants a similar expression that is equivalent. > So the right answer is 15<= x or x <30 > but one of the other answers is > not (15<= x and x <30) > > But it says.....remember you can try this out in the Python shell. > How? For instance, for x in (10, 20, 30, 40): print((15 <= x < 30) == (15<= x and x <30)) -- Terry Jan Reedy From Seymore4Head at Hotmail.invalid Sun Oct 5 20:07:50 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 05 Oct 2014 20:07:50 -0400 Subject: Practice question References: Message-ID: On Sun, 05 Oct 2014 19:14:27 -0400, Ned Batchelder wrote: >On 10/5/14 7:02 PM, Seymore4Head wrote: >> For the record, I don't want a hint. I want the answer. >> I see a practice question is similar to this. >> 15 <= x < 30 And it wants a similar expression that is equivalent. >> So the right answer is 15<= x or x <30 > >No, "15 <= x < 30" is equivalent to "15 <= x and x < 30". > >> but one of the other answers is >> not (15<= x and x <30) > >You are speaking ambiguously. Which did you mean: >a) one of the other answers isn't "15 <= x and x < 30", or: >b) one of the other answers is "not (15 <= x and x < 30)" ? Here is the exact question, I was trying to post something similar. I failed. http://i.imgur.com/iUGh4xf.jpg From Seymore4Head at Hotmail.invalid Sun Oct 5 20:18:13 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 05 Oct 2014 20:18:13 -0400 Subject: Practice question References: Message-ID: On Sun, 05 Oct 2014 19:47:40 -0400, Terry Reedy wrote: >On 10/5/2014 7:02 PM, Seymore4Head wrote: >> For the record, I don't want a hint. I want the answer. >> I see a practice question is similar to this. >> 15 <= x < 30 And it wants a similar expression that is equivalent. >> So the right answer is 15<= x or x <30 >> but one of the other answers is >> not (15<= x and x <30) >> >> But it says.....remember you can try this out in the Python shell. >> How? > >For instance, >for x in (10, 20, 30, 40): > print((15 <= x < 30) == (15<= x and x <30)) I think I get it now. You are using a sample of answers. So you could actually just run through them all. (I haven't tried this yet) for x in range(lo,hi) print((15 <= x < 30) == (15<= x and x <30)) Thanks From 4kir4.1i at gmail.com Sun Oct 5 21:10:26 2014 From: 4kir4.1i at gmail.com (Akira Li) Date: Mon, 06 Oct 2014 05:10:26 +0400 Subject: Timezones References: Message-ID: <87d2a6q9z1.fsf@gmail.com> Seymore4Head writes: > This is not a new video, but it is new to me. > https://www.youtube.com/watch?v=-5wpm-gesOY > > Any links to some easy to follow time zone math? The point of the video is that you should not do it yourself, use already written tools. It is quite comprehensive video. Here's how the mentioned issues could be resolved: - erratic UTC offset changes by politicians in different countries -- *use UTC timezone* for calculations, in addition (if necessary) store both the local time and timezone info. *Use pytz module* that provides access to the tz database to convert between timezones (many people get it wrong but it is not a rocket science). As said in the video, it won't help if the rules change a day before the DST transition but at least most [1] systems will be consistent. It also doesn't support some exotic timezone rules such as in Saudi Arabia (sunrise and/or sunset at the fixed local time every day [2]) or many timezones before 1970. - julian, gregorian calendars, proleptic UT (past dates): *use proleptic gregorian calendar (datetime module)* unless you know that you need otherwise (then you could investigate what JD means in a particular document given multiple possible interpretations) - leap seconds (posix, Mills, Windows(ntp), smear (google, java)), "right" timezones, and the difference between UT1, UTC(BIMP), GPS, TT(TAI), TCB, etc time scales: *ignore them* unless you know that you need otherwise e.g., legally elapsed seconds [3]. Here's some pictures to illustrate the difference between time scales [4]. [1] http://www.iana.org/time-zones/repository/tz-link.html [2] https://github.com/eggert/tz/blob/master/asia#L2439 [3] http://www.ucolick.org/~sla/leapsecs/epochtime.html [4] http://www.ucolick.org/~sla/leapsecs/deltat.html -- Akira From ned at nedbatchelder.com Sun Oct 5 21:25:16 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 05 Oct 2014 21:25:16 -0400 Subject: Practice question In-Reply-To: References: Message-ID: On 10/5/14 8:07 PM, Seymore4Head wrote: > On Sun, 05 Oct 2014 19:14:27 -0400, Ned Batchelder > wrote: > >> On 10/5/14 7:02 PM, Seymore4Head wrote: >>> For the record, I don't want a hint. I want the answer. >>> I see a practice question is similar to this. >>> 15 <= x < 30 And it wants a similar expression that is equivalent. >>> So the right answer is 15<= x or x <30 >> >> No, "15 <= x < 30" is equivalent to "15 <= x and x < 30". >> >>> but one of the other answers is >>> not (15<= x and x <30) >> >> You are speaking ambiguously. Which did you mean: >> a) one of the other answers isn't "15 <= x and x < 30", or: >> b) one of the other answers is "not (15 <= x and x < 30)" ? > > Here is the exact question, I was trying to post something similar. I > failed. > > http://i.imgur.com/iUGh4xf.jpg > Why isn't the fourth one correct? -- Ned Batchelder, http://nedbatchelder.com From rustompmody at gmail.com Sun Oct 5 22:37:47 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 5 Oct 2014 19:37:47 -0700 (PDT) Subject: Timezones In-Reply-To: References: Message-ID: <90928119-0c8d-4c85-baca-99af580ca227@googlegroups.com> On Monday, October 6, 2014 3:45:44 AM UTC+5:30, Mark Lawrence wrote: > On 05/10/2014 22:17, Seymore4Head wrote: > > This is not a new video, but it is new to me. > > https://www.youtube.com/watch?v=-5wpm-gesOY > > Any links to some easy to follow time zone math? > My advice is to avoid time zones, they're a real pain, seriously. What say we send an application to the UN to declare the world flat? From rosuav at gmail.com Sun Oct 5 22:48:58 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 6 Oct 2014 13:48:58 +1100 Subject: Timezones In-Reply-To: <90928119-0c8d-4c85-baca-99af580ca227@googlegroups.com> References: <90928119-0c8d-4c85-baca-99af580ca227@googlegroups.com> Message-ID: On Mon, Oct 6, 2014 at 1:37 PM, Rustom Mody wrote: >> My advice is to avoid time zones, they're a real pain, seriously. > > What say we send an application to the UN to declare the world flat? Easier to simply start scheduling things in UTC. I run an international Dungeons & Dragons campaign with sessions every Sunday at 02:00 UTC, and nobody needs to be confused by time zones. (The server displays UTC time, so it's easy for anyone to see; for instance, it's now Mon 02:48:09, so session time was about this time yesterday.) Civil time can do whatever it likes, just as long as everyone knows that the meeting is based on UTC. ChrisA From rustompmody at gmail.com Sun Oct 5 22:47:04 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 5 Oct 2014 19:47:04 -0700 (PDT) Subject: Practice question In-Reply-To: References: Message-ID: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> On Monday, October 6, 2014 5:04:11 AM UTC+5:30, Skip Montanaro wrote: > On Oct 5, 2014 6:07 PM, Seymore4Head wrote: > > For the record, I don't want a hint.? I want the answer. > > I see a practice question is similar to this. > > 15 <= x < 30? And it wants a similar expression that is equivalent. > Maybe > ??? 30 > x >= 15 > ? Seems more "similar" to the original expression than the other possibilities. > As to how to try it out, bring up the Python prompt, assign various > values to x, and keep evaluating the possibilities. To simplify > evaluation off a bunch of alternatives, consider defining a function > which takes x add a parameter and print out the various expression > values. I'd give a concrete example, but don't has a prompt > available on my phone... An interesting data-point. We have a here a poster who's asked some 20 or so python questions and still seems not to know how to use the interpreter interactively. Sorry Seymore if this sounds condescending -- its not a complaint against you but against those who treat the print statement/expression as kosher for newbies. Imagine someone who has driven a car for a month but has no clue about the basic rule of keep-left (or right). From ignat99 at gmail.com Sun Oct 5 23:08:08 2014 From: ignat99 at gmail.com (ignat99 at gmail.com) Date: Sun, 5 Oct 2014 20:08:08 -0700 (PDT) Subject: compile python 3.3 with bz2 support In-Reply-To: References: Message-ID: <4626f279-1844-4176-b7f7-27e0709bebb8@googlegroups.com> sudo apt-get install libbz2-dev Python-3.4.1$ ./configure --with-pydebug --with-bz2 --prefix=/usr && make -j2 On Saturday, 22 December 2012 17:06:51 UTC+1, Benjamin Kaplan wrote: > On Dec 21, 2012 1:31 AM, "Isml" <7606... at qq.com> wrote: > > > > > > hi, everyone: > > > ? ? I want to compile python 3.3 with bz2 support on RedHat 5.5 but fail to do that. Here is how I do it: > > > ? ? 1. download bzip2 and compile it(make?make -f Makefile_libbz2_so?make install) > > > ? ? 2.chang to python 3.3 source directory : ./configure --with-bz2=/usr/local/include > > > ? ? 3. make > > > ? ? 4. make install > > > ? > > > ? ? after installation complete, I test it? > > > ? ? [root at localhost Python-3.3.0]# python3 -c "import bz2" > > > Traceback (most recent call last): > > > ? File "", line 1, in > > > ? File "/usr/local/lib/python3.3/bz2.py", line 21, in > > > ? ? from _bz2 import BZ2Compressor, BZ2Decompressor > > > ImportError: No module named '_bz2' > > > By the way, RedHat 5.5 has a built-in python 2.4.3. Would it be a problem? > > > ? > > > > > > -- > > What is the output of configure? The last thing it does is list which modules are not going to be built. Is bz2 on the list? What does configure say when it's looking for bz2? From illusiontechniques at gmail.com Sun Oct 5 19:24:03 2014 From: illusiontechniques at gmail.com (C Smith) Date: Sun, 5 Oct 2014 16:24:03 -0700 Subject: Practice question In-Reply-To: References: Message-ID: 14 wrote: > On 10/5/14 7:02 PM, Seymore4Head wrote: >> >> For the record, I don't want a hint. I want the answer. >> I see a practice question is similar to this. >> 15 <= x < 30 And it wants a similar expression that is equivalent. >> So the right answer is 15<= x or x <30 > > > No, "15 <= x < 30" is equivalent to "15 <= x and x < 30". > >> but one of the other answers is >> not (15<= x and x <30) > > > You are speaking ambiguously. Which did you mean: > a) one of the other answers isn't "15 <= x and x < 30", or: > b) one of the other answers is "not (15 <= x and x < 30)" ? > > -- > Ned Batchelder, http://nedbatchelder.com > > -- > https://mail.python.org/mailman/listinfo/python-list From maxim at redwerk.com Fri Oct 3 11:33:13 2014 From: maxim at redwerk.com (Maxim Lesnichenko) Date: Fri, 3 Oct 2014 18:33:13 +0300 Subject: article posting Message-ID: <007201cfdf1f$58990fc0$09cb2f40$@redwerk.com> Dear Python community members, I would be very appreciate you if somebody could give me the contacts of responsible person for posting articles on python.org resource. It could be chief editor`s or administrator`s name and e-mail, Thank you very much advance, Best Regards Maxim Lesnichenko Business Development Manager Redwerk phone: +1 (347) 329-1444 email: maxim at redwerk.com skype: redwerk.com web: http://redwerk.com -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.gif Type: image/gif Size: 4002 bytes Desc: not available URL: From palacreide-general at yahoo.com Sun Oct 5 20:04:04 2014 From: palacreide-general at yahoo.com (Pal Acreide) Date: Sun, 5 Oct 2014 17:04:04 -0700 Subject: Python 3.4.1 on W2K? Message-ID: <1412553844.20683.YahooMailNeo@web181605.mail.ne1.yahoo.com> Hi, I'm a lurker here and enjoy the back-and-forth, especially among the experts among you. My question is this: I have Python 3.4.1 installed on 64-bit Win 7 Home Premium, and on 32-bit Win 7 Pro running on a virtual machine (Oracle VirtualBox). Now I'm trying to install it on Windows 2000 Pro also running under VBox. However, at some point near the end of the Python installation I get an error message to the effect that a program required for Win Installer is missing and the installation aborts. I'm running W2K SP4 + (undocumented) SP5.1. I guess it comes down to: Can Python 3.4.1 be installed on W2K? BTW, the reason I run VBox is that I belong to a group of diehard users of the classic DOS word-processor XyWrite. I've devised a way to use Python as an extension of XyWrite's built-in Programming Language (XPL): http://users.datarealm.com/xywwweb/xypydoc.htm Although it works well on virtual Win 7 Pro, I'd like to get it going in W2K if possible. Thanks. -- Pal A. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at pearwood.info Mon Oct 6 03:20:12 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 06 Oct 2014 07:20:12 GMT Subject: "High water" Memory fragmentation still a thing? References: <542f470b$0$13003$c3e8da3$5496439d@news.astraweb.com> <4VgYv.348787$NQ4.188655@fx26.am4> Message-ID: <543242ac$0$2916$c3e8da3$76491128@news.astraweb.com> On Sun, 05 Oct 2014 20:23:42 +0100, mm0fmf wrote: > On 04/10/2014 02:02, Steven D'Aprano wrote: >> Way back in the mid 1980s, Apple Macintoshes used a memory manager >> which could move memory around. > > But the memory manager didn't return a pointer to memory the way malloc > does. It returned a pointer to the pointer and you had to double > dereference it to get the heap address (ISTR, 30 years ago now). Correct. > The > advantage being the memory manager could shuffle the memory about and > update the pointers. Your pointer to a pointer would still point to the > same block after a shuffle. Of course you couldn't hold on to a partial > dereference across system calls... can you guess why? :-) Because system calls might trigger a memory compaction or move. Before the move, you have a managed "pointer to pointer" (handle) pointing to a managed point which points to a block of memory: handle -----> pointer -----> "Some stuff here" Grab a copy of the pointer with a partial deref: myPtr := handle^; (*I'm an old Pascal guy.*) So we have this: handle -----> pointer -----> "Some stuff here" myPtr -----------------------^ Then you call a system routine that moves memory, and the memory manager moves the block, updating the pointer, but leaving myPtr pointing at garbage: handle -----> pointer ----------------------------> "Some stuff here" myPtr -----------------------^ and as soon as you try using myPtr, you likely get the dreaded Bomb dialog box: http://www.macobserver.com/tmo/article/happy-birthday-mac-how-to-recover-from-the-dreaded-bomb-box-error-message I'm not suggesting that a 1984 memory manager is the solution to all our problems. I'm just pointing it out as proof that the concept works. If I knew more about Java and .Net, I could use them as examples instead :-) -- Steven From mail at timgolden.me.uk Mon Oct 6 03:31:08 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 06 Oct 2014 08:31:08 +0100 Subject: Python 3.4.1 on W2K? In-Reply-To: <1412553844.20683.YahooMailNeo@web181605.mail.ne1.yahoo.com> References: <1412553844.20683.YahooMailNeo@web181605.mail.ne1.yahoo.com> Message-ID: <5432453C.9070204@timgolden.me.uk> On 06/10/2014 01:04, Pal Acreide wrote: > Hi, I'm a lurker here and enjoy the back-and-forth, especially among the > experts among you. > > My question is this: I have Python 3.4.1 installed on 64-bit Win 7 Home > Premium, and on 32-bit Win 7 Pro running on a virtual machine (Oracle > VirtualBox). Now I'm trying to install it on Windows 2000 Pro also > running under VBox. However, at some point near the end of the Python > installation I get an error message to the effect that a program > required for Win Installer is missing and the installation aborts. I'm > running W2K SP4 + (undocumented) SP5.1. > > I guess it comes down to: Can Python 3.4.1 be installed on W2K? I'm afraid we formally dropped support for Win 2000 at least one version ago. You can see the official schedule here: http://legacy.python.org/dev/peps/pep-0011/#unsupporting-platforms and you'll note that Win2K was unsupported from 3.3. In the first instance, all this means is that we no longer go out of our way to use backwards-compatible APIs (ie to avoid newer APIs). At that stage, it's quite possible that much or all Python code will still work on an older platform. But at a certain point, we may decide to de-clutter the codebase by removing particular #ifdefs and workarounds which exist to support a now-unsupported platform. At that point, you would expect Python to no longer be usable on that platform in some way or another. Of course, if you're happy to work with a slightly older version of Python, such as 3.2, then you should be fine. TJG From wxjmfauth at gmail.com Mon Oct 6 03:46:19 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Mon, 6 Oct 2014 00:46:19 -0700 (PDT) Subject: re search through a text Vs line In-Reply-To: References: Message-ID: <5cae320b-b2ba-41e0-a4b1-3f9a3361777f@googlegroups.com> Le dimanche 5 octobre 2014 22:10:56 UTC+2, Dave Angel a ?crit?: > > Performance is pretty irrelevant, since disk I/O, unicode > > processing, and terminal processing are likely to > > dominate. > If unicode is so important, why does Python do the opposite of the implementation of the coding schemes endorsed by Unicode.org (memory and performance). jmf From rosuav at gmail.com Mon Oct 6 03:54:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 6 Oct 2014 18:54:24 +1100 Subject: Python 3.4.1 on W2K? In-Reply-To: <1412553844.20683.YahooMailNeo@web181605.mail.ne1.yahoo.com> References: <1412553844.20683.YahooMailNeo@web181605.mail.ne1.yahoo.com> Message-ID: On Mon, Oct 6, 2014 at 11:04 AM, Pal Acreide wrote: > BTW, the reason I run VBox is that I belong to a group of diehard users of > the classic DOS word-processor XyWrite. I've devised a way to use Python as > an extension of XyWrite's built-in Programming Language (XPL): > http://users.datarealm.com/xywwweb/xypydoc.htm > Although it works well on virtual Win 7 Pro, I'd like to get it going in W2K > if possible. Wow. I wonder, since you're already poking around with extremely legacy stuff, would it be easier for you to use OS/2 instead of Win2K? Paul Smedley still produces OS/2 builds of Python, and OS/2 itself runs happily under VirtualBox (we have an OS/2 VM still on our network here, and I use Python to manage its backups). Might not end up any better than your current system, but it might be! ChrisA From jakubo at example.org Mon Oct 6 05:05:17 2014 From: jakubo at example.org (jakubo) Date: Mon, 6 Oct 2014 09:05:17 +0000 (UTC) Subject: Clearing globals in CPython References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2014-10-01, Peter Otten <__peter__ at web.de> wrote: > Steven D'Aprano wrote: > >> Out of curiosity, I ran: >> >> globals().clear() >> >> Oops. >> >> So, with no built-ins available, import no longer works. That makes things >> rather tricky. >> >> Obviously the easiest way to recover is to exit the current session and >> restart it, but as a challenge, can we recover from this state? > > $ python3 > Python 3.4.0 (default, Apr 11 2014, 13:05:11) > [GCC 4.8.2] on linux > Type "help", "copyright", "credits" or "license" for more information. >>>> globals().clear() >>>> import that > Traceback (most recent call last): > File "", line 1, in > ImportError: __import__ not found >>>> object = 1 .__class__.__bases__[0] >>>> Quitter = [c for c in object.__subclasses__() if c.__name__ == > "Quitter"][0] >>>> __builtins__ = Quitter.__call__.__globals__["__builtins__"] >>>> import this > The Zen of Python, by Tim Peters > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > Complex is better than complicated. > Flat is better than nested. > Sparse is better than dense. > Readability counts. > Special cases aren't special enough to break the rules. > Although practicality beats purity. > Errors should never pass silently. > Unless explicitly silenced. > In the face of ambiguity, refuse the temptation to guess. > There should be one-- and preferably only one --obvious way to do it. > Although that way may not be obvious at first unless you're Dutch. > Now is better than never. > Although never is often better than *right* now. > If the implementation is hard to explain, it's a bad idea. > If the implementation is easy to explain, it may be a good idea. > Namespaces are one honking great idea -- let's do more of those! I have funnier one :) $ python3 Python 3.4.1 (default, Sep 10 2014, 22:21:18) [GCC 4.9.1] on linux Type "help", "copyright", "credits" or "license" for more information. >>> globals().clear() >>> import this Traceback (most recent call last): File "", line 1, in ImportError: __import__ not found >>> True.__ True.__abs__( True.__dir__( True.__format__( True.__init__( True.__mul__( True.__radd__( True.__rlshift__( True.__rshift__( True.__sub__( True.__add__( True.__divmod__( True.__ge__( True.__int__( True.__ne__( True.__rand__( True.__rmod__( True.__rsub__( True.__subclasshook__( True.__and__( True.__doc__ True.__getattribute__( True.__invert__( True.__neg__( True.__rdivmod__( True.__rmul__( True.__rtruediv__( True.__truediv__( True.__bool__( True.__eq__( True.__getnewargs__( True.__le__( True.__new__( True.__reduce__( True.__ror__( True.__rxor__( True.__trunc__( True.__ceil__( True.__float__( True.__gt__( True.__lshift__( True.__or__( True.__reduce_ex__( True.__round__( True.__setattr__( True.__xor__( True.__class__( True.__floor__( True.__hash__( True.__lt__( True.__pos__( True.__repr__( True.__rpow__( True.__sizeof__( True.__delattr__( True.__floordiv__( True.__index__( True.__mod__( True.__pow__( True.__rfloordiv__( True.__rrshift__( True.__str__( >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! >>> After invoking autocompletion (.__ and hitting tab), session has been automagically healed. -- jakubo From steve at pearwood.info Mon Oct 6 05:08:46 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 06 Oct 2014 09:08:46 GMT Subject: Clearing globals in CPython References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> Message-ID: <54325c1e$0$2916$c3e8da3$76491128@news.astraweb.com> On Mon, 06 Oct 2014 09:05:17 +0000, jakubo wrote: > After invoking autocompletion (.__ and hitting tab), session has been > automagically healed. That's ... um ... I have no words. Can you confirm that autocompletion modifies globals()? I don't have 3.4 installed here. -- Steven From rosuav at gmail.com Mon Oct 6 05:30:30 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 6 Oct 2014 20:30:30 +1100 Subject: Clearing globals in CPython In-Reply-To: <54325c1e$0$2916$c3e8da3$76491128@news.astraweb.com> References: <542c2527$0$13013$c3e8da3$5496439d@news.astraweb.com> <54325c1e$0$2916$c3e8da3$76491128@news.astraweb.com> Message-ID: On Mon, Oct 6, 2014 at 8:08 PM, Steven D'Aprano wrote: > On Mon, 06 Oct 2014 09:05:17 +0000, jakubo wrote: > >> After invoking autocompletion (.__ and hitting tab), session has been >> automagically healed. > > > That's ... um ... > > I have no words. > > > Can you confirm that autocompletion modifies globals()? I don't have 3.4 > installed here. I can confirm that the trick does work. That's... extremely weird. ChrisA From rorocodeath at gmail.com Mon Oct 6 06:00:27 2014 From: rorocodeath at gmail.com (roro codeath) Date: Mon, 6 Oct 2014 03:00:27 -0700 (PDT) Subject: ruby instance variable in python Message-ID: for instance in ruby i can write following code: module M def ins_var @ins_var ||= nil end def m @ins_var = "val" end def m2 ins_var # => "val" end end in py # m.py # how to def a ins_var? def m: # how to set a ins_var? def m2: # how to get a ins_var? From rorocodeath at gmail.com Mon Oct 6 06:06:33 2014 From: rorocodeath at gmail.com (roro codeath) Date: Mon, 6 Oct 2014 18:06:33 +0800 Subject: ruby instance variable in python Message-ID: in ruby: module M def ins_var @ins_var ||= nil end def m @ins_var = 'val' end def m2 m ins_var # => 'val' end end in py: # m.py # how to def ins_var def m: # how to set ins_var def m2: m() # how to get ins var -------------- next part -------------- An HTML attachment was scrubbed... URL: From dpalao.python at gmail.com Mon Oct 6 06:45:40 2014 From: dpalao.python at gmail.com (David Palao) Date: Mon, 6 Oct 2014 12:45:40 +0200 Subject: ruby instance variable in python In-Reply-To: References: Message-ID: Hello, If you explain what the ruby code does, I think much more people will be able to help you. Don't forget, this is a Python list. Not everybody knows Ruby here. Best 2014-10-06 12:06 GMT+02:00 roro codeath : > in ruby: > > module M > def ins_var > @ins_var ||= nil > end > > def m > @ins_var = 'val' > end > > def m2 > m > ins_var # => 'val' > end > end > > in py: > > # m.py > > # how to def ins_var > > def m: > # how to set ins_var > > def m2: > m() > # how to get ins var > > -- > https://mail.python.org/mailman/listinfo/python-list > From varun7rs at gmail.com Mon Oct 6 07:13:42 2014 From: varun7rs at gmail.com (varun7rs at gmail.com) Date: Mon, 6 Oct 2014 04:13:42 -0700 (PDT) Subject: Representing mathematical equations Message-ID: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> Hello, I am working on a mathematical equation which I'm finding really hard to express in python. Could any of you spare some time to help me out? The equation looks like this b(i,x) = [?(l?L) [bd(l) * dist(l) * hc(l)]] / ?(l?L) l I have a problem in representing the above equation. I don't know how to use teh loops over here to express b(i,x) i,x,l are sets with different numbers Thank You I'm sorry if the equation is not expressed in a standard form. I don't have LateX From davea at davea.name Mon Oct 6 08:50:48 2014 From: davea at davea.name (Dave Angel) Date: Mon, 6 Oct 2014 08:50:48 -0400 (EDT) Subject: Representing mathematical equations References: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> Message-ID: varun7rs at gmail.com Wrote in message: > Hello, > > I am working on a mathematical equation which I'm finding really hard to express in python. Could any of you spare some time to help me out? > > The equation looks like this > > b(i,x) = [?(l?L) [bd(l) * dist(l) * hc(l)]] / ?(l?L) l > > I have a problem in representing the above equation. I don't know how to use teh loops over here to express b(i,x) > > i,x,l are sets with different numbers > Perhaps you meant L is a set of numbers, none repeated. If you really meant l, I have no clue. As for i and x, they don't appear on the right side so they're a red herring. I also don't know what bd, dist, and hc are. Are they each a function of a single number? Or are they vectors, indexed by int? If so, then presumably L is a set of ints. How about you express some sample data that you'd like to evaluate. For example, start with L = set (1, 4, 3) bd = [4.3, 12.11, 93, -0.9, 42] ..... > I'm sorry if the equation is not expressed in a standard form. I don't have LateX No problem, you did a good job expressing it in unicode in a text message. Ii Ll 1 -- DaveA From skip.montanaro at gmail.com Mon Oct 6 09:04:12 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Mon, 6 Oct 2014 08:04:12 -0500 Subject: Practice question In-Reply-To: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> Message-ID: On Sun, Oct 5, 2014 at 9:47 PM, Rustom Mody wrote: > Sorry Seymore if this sounds condescending -- its not a complaint > against you but against those who treat the print statement/expression as > kosher for newbies. So if you're not griping about Seymore's original post, are you griping about my response? It was the one you quoted. And what's with the comparison between use of the print statement and driving on the wrong side of the road? Skip From varun7rs at gmail.com Mon Oct 6 09:03:29 2014 From: varun7rs at gmail.com (varun7rs at gmail.com) Date: Mon, 6 Oct 2014 06:03:29 -0700 (PDT) Subject: Representing mathematical equations In-Reply-To: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> References: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> Message-ID: <09669ac4-1aeb-48fa-8cc9-7f741f7fe6b3@googlegroups.com> On Monday, 6 October 2014 13:14:04 UTC+2, varu... at gmail.com wrote: > Hello, > > > > I am working on a mathematical equation which I'm finding really hard to express in python. Could any of you spare some time to help me out? > > > > The equation looks like this > > > > b(i,x) = [?(l?L) [bd(l) * dist(l) * hc(l)]] / ?(l?L) l > > > > I have a problem in representing the above equation. I don't know how to use teh loops over here to express b(i,x) > > > > i,x,l are sets with different numbers > > > > Thank You > > I'm sorry if the equation is not expressed in a standard form. I don't have LateX Okay, I forgot to explain them. L is a set of links, dist is a number (distance), bd is the bandwidth and hc is a number as well (hopcount)...different bandwidths, hopcounts and distances for different links... b(i,x) is what i intend to calculate out of these details...here 'i' could be the head or tail of the link l and x is a node that hosts i Thank You From varun7rs at gmail.com Mon Oct 6 09:07:11 2014 From: varun7rs at gmail.com (varun7rs at gmail.com) Date: Mon, 6 Oct 2014 06:07:11 -0700 (PDT) Subject: Representing mathematical equations In-Reply-To: <09669ac4-1aeb-48fa-8cc9-7f741f7fe6b3@googlegroups.com> References: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> <09669ac4-1aeb-48fa-8cc9-7f741f7fe6b3@googlegroups.com> Message-ID: <28aeb1c6-2a2f-4452-862d-c98b204eab34@googlegroups.com> On Monday, 6 October 2014 15:03:44 UTC+2, varu... at gmail.com wrote: > On Monday, 6 October 2014 13:14:04 UTC+2, varu... at gmail.com wrote: > > > Hello, > > > > > > > > > > > > I am working on a mathematical equation which I'm finding really hard to express in python. Could any of you spare some time to help me out? > > > > > > > > > > > > The equation looks like this > > > > > > > > > > > > b(i,x) = [?(l?L) [bd(l) * dist(l) * hc(l)]] / ?(l?L) l > > > > > > > > > > > > I have a problem in representing the above equation. I don't know how to use teh loops over here to express b(i,x) > > > > > > > > > > > > i,x,l are sets with different numbers > > > > > > > > > > > > Thank You > > > > > > I'm sorry if the equation is not expressed in a standard form. I don't have LateX > > > > Okay, I forgot to explain them. L is a set of links, dist is a number (distance), bd is the bandwidth and hc is a number as well (hopcount)...different bandwidths, hopcounts and distances for different links... > > b(i,x) is what i intend to calculate out of these details...here 'i' could be the head or tail of the link l and x is a node that hosts i > > > > Thank You Unbelievable. I again forgot to express them L = [(1,3), (5,7), .....] bd = [23, 34,43.44.....] dist = [3,7,5,7, ....] hc = [2,3,4,1,2,2,...] for every l belonging to L, i could be either 1 or 3 for L[0], similarly for L[1] it could be 5 or 7 From breamoreboy at yahoo.co.uk Mon Oct 6 10:06:31 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 06 Oct 2014 15:06:31 +0100 Subject: ruby instance variable in python In-Reply-To: References: Message-ID: On 06/10/2014 11:45, David Palao wrote: > Hello, > If you explain what the ruby code does, I think much more people will > be able to help you. Don't forget, this is a Python list. Not > everybody knows Ruby here. > > Best > > 2014-10-06 12:06 GMT+02:00 roro codeath : >> in ruby: >> Please don't top post here, thank you. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From Sas.Parmar at servicebirmingham.co.uk Mon Oct 6 09:52:04 2014 From: Sas.Parmar at servicebirmingham.co.uk (Sas Parmar) Date: Mon, 6 Oct 2014 13:52:04 +0000 Subject: Python 2.76 Message-ID: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> Dear Sirs I am working on a project at Service Birmingham to migrate our applications from Windows Server 2003 over to Windows Server 2008 R2 Can you confirm if Python 2.76 is compatible with Server 2008 R2? If not can you confirm if any changes can be made to make it work on Server 2008 R2 (ie. Version updates or configuration changes) Kind Regards, Sas Parmar Contractor for Server 2003 to 2008 Migration Service Birmingham | Units 2&3 B1 | 50 Summer Hill Road | Birmingham | B1 3RB Sas.Parmar at servicebirmingham.co.uk *********************************************************************** The information contained within this e-mail (and any attachment) sent by Service Birmingham Ltd. is confidential and may be legally privileged. It is intended only for the named recipient or entity to whom it is addressed. If you are not the intended recipient, please notify the sender and delete the e-mail immediately. Unauthorised access, use, disclosure, storage or copying is not permitted and may be unlawful. Any e-mail including its content may be monitored and used by Service Birmingham Ltd. for reasons of security and for monitoring internal compliance with Security Policy. E-mail blocking software will also be used. Any views or opinions expressed are solely those of the originator and do not necessarily represent those of Service Birmingham Ltd. Although Service Birmingham Ltd. has made every reasonable effort to ensure that this message and any attachments contain no viruses and have not been intercepted or amended, it can not make any assurances to this effect. Service Birmingham Ltd., Registered in England & Wales under Company No. 05660977 Registered Office: Units 2&3, B1, 50 Summer Hill Road, Birmingham, B1 3BZ. *********************************************************************** -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Oct 6 10:10:47 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 06 Oct 2014 15:10:47 +0100 Subject: Representing mathematical equations In-Reply-To: <28aeb1c6-2a2f-4452-862d-c98b204eab34@googlegroups.com> References: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> <09669ac4-1aeb-48fa-8cc9-7f741f7fe6b3@googlegroups.com> <28aeb1c6-2a2f-4452-862d-c98b204eab34@googlegroups.com> Message-ID: On 06/10/2014 14:07, varun7rs at gmail.com wrote: [snip 69 lines] > L = [(1,3), (5,7), .....] > bd = [23, 34,43.44.....] > dist = [3,7,5,7, ....] > hc = [2,3,4,1,2,2,...] > for every l belonging to L, i could be either 1 or 3 for L[0], similarly for L[1] it could be 5 or 7 > Would you please access this list via https://mail.python.org/mailman/listinfo/python-list or read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing the double line spacing and single line paragraphs that I've snipped above, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From joel.goldstick at gmail.com Mon Oct 6 10:18:38 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 6 Oct 2014 10:18:38 -0400 Subject: Python 2.76 In-Reply-To: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> References: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> Message-ID: On Mon, Oct 6, 2014 at 9:52 AM, Sas Parmar wrote: > Dear Sirs > > > > I am working on a project at Service Birmingham to migrate our applications > from Windows Server 2003 over to Windows Server 2008 R2 > > > > Can you confirm if Python 2.76 is compatible with Server 2008 R2? > > > > If not can you confirm if any changes can be made to make it work on Server > 2008 R2 (ie. Version updates or configuration changes) > > Look Here: http://ampps.com/download > > Kind Regards, > > > > Sas Parmar > > Contractor for Server 2003 to 2008 Migration > > > > Service Birmingham | Units 2&3 B1 | 50 Summer Hill Road | Birmingham | B1 > 3RB > > Sas.Parmar at servicebirmingham.co.uk > > > > > *********************************************************************** > The information contained within this e-mail (and any attachment) sent by > Service Birmingham Ltd. is confidential and may be legally privileged. It is > intended only for the named recipient or entity to whom it is addressed. If > you are not the intended recipient, please notify the sender and delete the > e-mail immediately. Unauthorised access, use, disclosure, storage or copying > is not permitted and may be unlawful. Any e-mail including its content may > be monitored and used by Service Birmingham Ltd. for reasons of security and > for monitoring internal compliance with Security Policy. E-mail blocking > software will also be used. Any views or opinions expressed are solely those > of the originator and do not necessarily represent those of Service > Birmingham Ltd. > > Although Service Birmingham Ltd. has made every reasonable effort to ensure > that this message and any attachments contain no viruses and have not been > intercepted or amended, it can not make any assurances to this effect. > > Service Birmingham Ltd., Registered in England & Wales under Company No. > 05660977 > Registered Office: Units 2&3, B1, 50 Summer Hill Road, Birmingham, B1 3BZ. > *********************************************************************** > > -- > https://mail.python.org/mailman/listinfo/python-list > -- Joel Goldstick http://joelgoldstick.com From rosuav at gmail.com Mon Oct 6 10:27:19 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 7 Oct 2014 01:27:19 +1100 Subject: Python 2.76 In-Reply-To: References: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> Message-ID: On Tue, Oct 7, 2014 at 1:18 AM, Joel Goldstick wrote: > Look Here: http://ampps.com/download Any particular reason for using this third-party build of Python? I note that they distribute some slightly old builds (2.7.2 on Windows, 2.7.6 on other platforms), so unless they have some strong justification, I'd prefer to recommend the official python.org installers and all the bugfixes they incorporate. ChrisA From joel.goldstick at gmail.com Mon Oct 6 10:30:56 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 6 Oct 2014 10:30:56 -0400 Subject: Python 2.76 In-Reply-To: References: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> Message-ID: On Mon, Oct 6, 2014 at 10:27 AM, Chris Angelico wrote: > On Tue, Oct 7, 2014 at 1:18 AM, Joel Goldstick wrote: >> Look Here: http://ampps.com/download > > Any particular reason for using this third-party build of Python? I > note that they distribute some slightly old builds (2.7.2 on Windows, > 2.7.6 on other platforms), so unless they have some strong > justification, I'd prefer to recommend the official python.org > installers and all the bugfixes they incorporate. > No, I just meant to point out that these people are using a version of 2.7 with the OS the OP is using. Maybe that is helpful to know. > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From rosuav at gmail.com Mon Oct 6 10:25:32 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 7 Oct 2014 01:25:32 +1100 Subject: Python 2.76 In-Reply-To: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> References: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> Message-ID: On Tue, Oct 7, 2014 at 12:52 AM, Sas Parmar wrote: > I am working on a project at Service Birmingham to migrate our applications > from Windows Server 2003 over to Windows Server 2008 R2 > > Can you confirm if Python 2.76 is compatible with Server 2008 R2? > > If not can you confirm if any changes can be made to make it work on Server > 2008 R2 (ie. Version updates or configuration changes) It should be fully supported. However, unless you have a particular reason for using 2.7.6 (it's normally written in three parts, by the way), you'll probably want to use the latest bug-fix release, 2.7.8; there've been a number of bugs fixed, including some SSL improvements. Where do you normally download Python from? There are a number of different sources, and some of them may offer different promises of support (ActiveState, for instance, supports some older versions of Python), but this is the primary place to get the official installers: https://www.python.org/download/releases/2.7.8/ ChrisA From rosuav at gmail.com Mon Oct 6 10:41:44 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 7 Oct 2014 01:41:44 +1100 Subject: Python 2.76 In-Reply-To: References: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> Message-ID: On Tue, Oct 7, 2014 at 1:30 AM, Joel Goldstick wrote: > No, I just meant to point out that these people are using a version of > 2.7 with the OS the OP is using. > Maybe that is helpful to know. Sure. A little extra verbiage could have made that clearer :) Unfortunately it's not proof; they seem to be doing their own builds, so it's actually possible that they've changed something to make it work on those platforms (which, if it were true, would explain the lag on versions - it takes work to maintain something like that, and it's often not worth redoing that for each bugfix release). So while it may be helpful, it's certainly not conclusive. I did a bit of quick poking around, and didn't find anywhere a simple list of the officially-supported platforms for each Python release. PEP 11 links it to Microsoft's support lifecycle, which means you have to go pointer-chasing a bit to figure out what's supported. So there's this: http://support2.microsoft.com/lifecycle/?p1=14134 Now, Python 2.7.0 came out in 2010: https://www.python.org/download/releases/2.7 Which means Server 2008 R2 was around when it was first released. I'm not entirely sure what "Service Pack Support End Date" means, but in any case, there's mainstream support for Server 2008 R2 until 2015, ergo Python 2.7.8 should be supported. But it's a smidge complicated to look this all up, and I'm not confident that my lookups have been entirely correct. Feel free to do your own pointer chase and verify or disprove my results. ChrisA From kwpolska at gmail.com Mon Oct 6 10:42:24 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Mon, 6 Oct 2014 16:42:24 +0200 Subject: Python 2.76 In-Reply-To: References: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> Message-ID: On Mon, Oct 6, 2014 at 4:30 PM, Joel Goldstick wrote: > [?] > No, I just meant to point out that these people are using a version of > 2.7 with the OS the OP is using. > Maybe that is helpful to know. This would have assumed those people bothered keeping their Python version up-to-date. Now: Windows Server 2008 R2 is the server counterpart of Windows 7. Which pretty much HAS to support recently released software (py2.7.6 was released 2013-11-10). Nevertheless, it?d be nice to upgrade to Python 2.7.8, which also supports the system, and features new capabilities, bug fixes and security fixes (including Heartbleed?) without breaking backwards compatibility. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From torriem at gmail.com Mon Oct 6 10:42:01 2014 From: torriem at gmail.com (Michael Torrie) Date: Mon, 06 Oct 2014 08:42:01 -0600 Subject: Representing mathematical equations In-Reply-To: <28aeb1c6-2a2f-4452-862d-c98b204eab34@googlegroups.com> References: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> <09669ac4-1aeb-48fa-8cc9-7f741f7fe6b3@googlegroups.com> <28aeb1c6-2a2f-4452-862d-c98b204eab34@googlegroups.com> Message-ID: <5432AA39.4090407@gmail.com> On 10/06/2014 07:07 AM, varun7rs at gmail.com wrote: >> Okay, I forgot to explain them. L is a set of links, dist is a >> number (distance), bd is the bandwidth and hc is a number as well >> (hopcount)...different bandwidths, hopcounts and distances for different >> links... b(i,x) is what i intend to calculate out of these details...here >> 'i'could be the head or tail of the link l and x is a node that hosts i >> Thank You > > Unbelievable. I again forgot to express them > L = [(1,3), (5,7), .....] > bd = [23, 34,43.44.....] > dist = [3,7,5,7, ....] > hc = [2,3,4,1,2,2,...] > for every l belonging to L, i could be either 1 or 3 for L[0], similarly for L[1] it could be 5 or 7 You might want to ask on the scipy mailing list[1]. I'm sure the folks over there deal with complex sums and math all the time. Numpy (standalone, or as part of scipy) has some facilities for working with vectors, products, and summations in an efficient manner. [1] http://mail.scipy.org/mailman/listinfo/scipy-user From kwpolska at gmail.com Mon Oct 6 11:38:14 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Mon, 6 Oct 2014 17:38:14 +0200 Subject: Python 2.76 In-Reply-To: <12E3ADFE8ADEDA4E9FF28E92C724928964F7E7@SVWVAP416.addm.ads.brm.pri> References: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> <12E3ADFE8ADEDA4E9FF28E92C724928964F7E7@SVWVAP416.addm.ads.brm.pri> Message-ID: CC'ing the mailing list. On Mon, Oct 6, 2014 at 5:29 PM, Sas Parmar wrote: > Hi Chris > > I need to get in contact with the actual manufacturer of Python. > > Do you have an email address or phone number? This is a very problematic question. Why do you need to contact ?the manufacturer?? Python is an open-source language with multiple people involved. Depending on what your query is, you may want the Python Software Foundation, a release manager, tons of other people? State your question here and you may receive an answer or a pointer to someone with an answer. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From bryanjugglercryptographer at yahoo.com Mon Oct 6 12:21:50 2014 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: Mon, 6 Oct 2014 09:21:50 -0700 (PDT) Subject: "High water" Memory fragmentation still a thing? In-Reply-To: References: Message-ID: <7ac186c3-2dbc-4cfa-ab58-37854aeb59d1@googlegroups.com> Chris Angelico wrote: > This is why a lot of long-duration processes are built to be restarted > periodically. It's not strictly necessary, but it can be the most > effective way of solving a problem. I tend to ignore that, though, and > let my processes just keep on running... for 88 wk 4d 23:56:27 so far, > on one of those processes. It's consuming less than half a gig of > virtual memory, quarter gig resident, and it's been doing a fair bit [...] A shipping product has to meet a higher standard. Planned process mortality is a reasonably simple strategy for building robust services from tools that have flaws in resource management. It assumes only that the operating system reliably reclaims resources from dead processes. The usual pattern is to have one or two parent processes that keep several worker processes running but do not themselves directly serve clients. The workers do the heavy lifting and are programmed to eventually die, letting younger workers take over. For an example see the Apache HTTP daemon, particularly the classic pre-forking server. There's a configuration parameter, "MaxRequestsPerChild", that sets how many requests a process should answer before terminating. From rustompmody at gmail.com Mon Oct 6 12:23:54 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 6 Oct 2014 09:23:54 -0700 (PDT) Subject: Practice question In-Reply-To: References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> Message-ID: On Monday, October 6, 2014 6:34:27 PM UTC+5:30, Skip Montanaro wrote: > On Sun, Oct 5, 2014 at 9:47 PM, Rustom Mody wrote: > > Sorry Seymore if this sounds condescending -- its not a complaint > > against you but against those who treat the print statement/expression as > > kosher for newbies. > So if you're not griping about Seymore's original post, are you > griping about my response? It was the one you quoted. It so happened you were the person to note that here was a question(er) needing instruction about using the interpreter. Nothing wrong with the answer (or the question). Something wrong with the point at which it emerges. > And what's with the comparison between use of the print statement > and driving on the wrong side of the road? Consider the sequence: 1. Drives on the wrong side of the road 2. Has no clue that there's such a concept as 'wrong side of road' 3. Teaches people to drive without conveying anything about 'wrong side of road' Hopefully you will agree that 1 < 2 < 3?? My gripe is with 3 From rosuav at gmail.com Mon Oct 6 12:43:13 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 7 Oct 2014 03:43:13 +1100 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: <7ac186c3-2dbc-4cfa-ab58-37854aeb59d1@googlegroups.com> References: <7ac186c3-2dbc-4cfa-ab58-37854aeb59d1@googlegroups.com> Message-ID: On Tue, Oct 7, 2014 at 3:21 AM, wrote: > Chris Angelico wrote: >> This is why a lot of long-duration processes are built to be restarted >> periodically. It's not strictly necessary, but it can be the most >> effective way of solving a problem. I tend to ignore that, though, and >> let my processes just keep on running... for 88 wk 4d 23:56:27 so far, >> on one of those processes. It's consuming less than half a gig of >> virtual memory, quarter gig resident, and it's been doing a fair bit [...] > > A shipping product has to meet a higher standard. Planned process mortality is a reasonably simple strategy for building robust services from tools that have flaws in resource management. It assumes only that the operating system reliably reclaims resources from dead processes. > Sure, and that's all well and good. But what I just cited there *is* a shipping product. That's a live server that runs a game that I'm admin of. So it's possible to do without the resource safety net of periodic restarts. > For an example see the Apache HTTP daemon, particularly the classic pre-forking server. There's a configuration parameter, "MaxRequestsPerChild", that sets how many requests a process should answer before terminating. > That assumes that requests can be handled equally by any server process - and more so, that there are such things as discrete requests. That's true of HTTP, but not of everything. And even with HTTP, if you do "long polls" [1] then clients might remain connected for arbitrary lengths of time; either you have to cut them off when you terminate the server process (hopefully that isn't too often, or you lose the benefit of long polling), or you retain processes for much longer. Restarting isn't necessary. It's like rebooting a computer: people get into the habit of doing it, because it "fixes problems", but all that means is that it allows you to get sloppy with resource management. Working under the constraint that your one process will remain running for at least a year forces you to be careful, and IMO results in better code overall. ChrisA [1] https://en.wikipedia.org/wiki/Push_technology#Long_polling From pkpearson at nowhere.invalid Mon Oct 6 12:45:07 2014 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 6 Oct 2014 16:45:07 GMT Subject: Representing mathematical equations References: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> <09669ac4-1aeb-48fa-8cc9-7f741f7fe6b3@googlegroups.com> <28aeb1c6-2a2f-4452-862d-c98b204eab34@googlegroups.com> Message-ID: On Mon, 06 Oct 2014 08:42:01 -0600, Michael Torrie wrote: > On 10/06/2014 07:07 AM, varun7rs at gmail.com wrote: >>> Okay, I forgot to explain them. L is a set of links, dist is a >>> number (distance), bd is the bandwidth and hc is a number as well >>> (hopcount)...different bandwidths, hopcounts and distances for different >>> links... b(i,x) is what i intend to calculate out of these details...here >>> 'i'could be the head or tail of the link l and x is a node that hosts i >>> Thank You >> >> Unbelievable. I again forgot to express them >> L = [(1,3), (5,7), .....] >> bd = [23, 34,43.44.....] >> dist = [3,7,5,7, ....] >> hc = [2,3,4,1,2,2,...] >> for every l belonging to L, i could be either 1 or 3 for L[0], similarly >> for L[1] it could be 5 or 7 > > You might want to ask on the scipy mailing list[1]. I'm sure the folks > over there deal with complex sums and math all the time. Numpy > (standalone, or as part of scipy) has some facilities for working with > vectors, products, and summations in an efficient manner. I don't think the OP is interested in complex numbers. I think this is a question about organizing loops. But I can't tell for sure. My guess is that l is one of the pairs in L, and that i is one of the elements in l, or perhaps both in succession. OP hints that "x is a node that hosts i", but how that affects the right-hand side of the equation defining the quantity to be computed, which is lost in the history of this thread, is unclear. There's a lesson here for the OP, varun7rs: If your initial query had been clear and complete, you would have your answer by now. -- To email me, substitute nowhere->runbox, invalid->com. From rosuav at gmail.com Mon Oct 6 12:52:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 7 Oct 2014 03:52:08 +1100 Subject: Practice question In-Reply-To: References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> Message-ID: On Tue, Oct 7, 2014 at 3:23 AM, Rustom Mody wrote: > Consider the sequence: > > 1. Drives on the wrong side of the road > 2. Has no clue that there's such a concept as 'wrong side of road' > 3. Teaches people to drive without conveying anything about 'wrong side of road' > > Hopefully you will agree that 1 < 2 < 3?? > > My gripe is with 3 No, I don't agree. Teaching people to drive is separate from teaching road rules, which vary by legislature. I can draw the exact same analogy: 1. Fails to follow proper protocol at a hook turn intersection 2. Has no clue that there's such a concept as a hook turn 3. Teaches people to drive without conveying anything about hook turns. Most of you are probably in state 2, and your instructors were probably in state 3. Neither's a problem, because hook turns don't matter until you come to an intersection where they're used. (And even then, there's often signage.) The complaints you're making are about something that does not matter. There are multiple usage patterns for Python; one is to eschew the interactive interpreter and run everything from scripts. That's fine, there's nothing wrong with it. And then, the nuances of interactive Python are completely insignificant. I don't see that your complaints about print and interactive mode have anything at all to do with this thread. ChrisA From rustompmody at gmail.com Mon Oct 6 13:05:40 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 6 Oct 2014 10:05:40 -0700 (PDT) Subject: Practice question In-Reply-To: References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> Message-ID: On Monday, October 6, 2014 10:22:27 PM UTC+5:30, Chris Angelico wrote: > On Tue, Oct 7, 2014 at 3:23 AM, Rustom Mody wrote: > > Consider the sequence: > > 1. Drives on the wrong side of the road > > 2. Has no clue that there's such a concept as 'wrong side of road' > > 3. Teaches people to drive without conveying anything about 'wrong side of road' > > Hopefully you will agree that 1 < 2 < 3?? > > My gripe is with 3 > No, I don't agree. Interesting So you dont agree with: "1<2<3" ? Or with "My gripe is 3" ? The second would be quite bizarre: "I have a headache..." "Sorry. But I dont agree with that" From rosuav at gmail.com Mon Oct 6 13:13:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 7 Oct 2014 04:13:17 +1100 Subject: Practice question In-Reply-To: References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> Message-ID: On Tue, Oct 7, 2014 at 4:05 AM, Rustom Mody wrote: > On Monday, October 6, 2014 10:22:27 PM UTC+5:30, Chris Angelico wrote: >> On Tue, Oct 7, 2014 at 3:23 AM, Rustom Mody wrote: >> > Consider the sequence: >> > 1. Drives on the wrong side of the road >> > 2. Has no clue that there's such a concept as 'wrong side of road' >> > 3. Teaches people to drive without conveying anything about 'wrong side of road' >> > Hopefully you will agree that 1 < 2 < 3?? >> > My gripe is with 3 > >> No, I don't agree. > > Interesting > > So you dont agree with: "1<2<3" ? > > Or with "My gripe is 3" ? > > The second would be quite bizarre: > > "I have a headache..." > > "Sorry. But I dont agree with that" Well, hey, I've eaten things that disagreed with me. You'd think that would be purely factual. "I ate you!" "I disagree!". But no, it was the "1 < 2 < 3" part that I disagreed with... as I'm sure you were aware. Never let the obvious truth of something get in the way of a good joke :) ChrisA From bryanjugglercryptographer at yahoo.com Mon Oct 6 13:10:46 2014 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: Mon, 6 Oct 2014 10:10:46 -0700 (PDT) Subject: "High water" Memory fragmentation still a thing? In-Reply-To: References: Message-ID: dieter wrote: > As you see from the description, memory compaction presents a heavy burden > for all extension writers. Particularly because many CPython extensions are actually interfaces to pre-existing libraries. To leverage the system's facilities CPython has to follow the system's conventions, which memory compaction would break. From davea at davea.name Mon Oct 6 13:24:58 2014 From: davea at davea.name (Dave Angel) Date: Mon, 6 Oct 2014 13:24:58 -0400 (EDT) Subject: Representing mathematical equations References: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> <09669ac4-1aeb-48fa-8cc9-7f741f7fe6b3@googlegroups.com> <28aeb1c6-2a2f-4452-862d-c98b204eab34@googlegroups.com> Message-ID: varun7rs at gmail.com Wrote in message: > On Monday, 6 October 2014 15:03:44 UTC+2, varu... at gmail.com wrote: > (Deleted all the 8-space quoting. Either use a better email client or remove the extra 7 lines between every line you quote.) >> >> Okay, I forgot to explain them. L is a set of links, dist is a number (distance), bd is the bandwidth and hc is a number as well (hopcount)...different bandwidths, hopcounts and distances for different links... >> >> b(i,x) is what i intend to calculate out of these details...here 'i' could be the head or tail of the link l and x is a node that hosts i > > Unbelievable. I again forgot to express them > > L = [(1,3), (5,7), .....] > bd = [23, 34,43.44.....] > dist = [3,7,5,7, ....] > hc = [2,3,4,1,2,2,...] > for every l belonging to L, i could be either 1 or 3 for L[0], similarly for L[1] it could be 5 or 7 Now it's clear I don't have a clue. L is either a set or a list. Little l is an element of that set, and is either a tuple or is mysteriously subscripted by a boolean at the other end of the expression. .. -- DaveA From doug.farrell at gmail.com Mon Oct 6 13:28:24 2014 From: doug.farrell at gmail.com (writeson) Date: Mon, 6 Oct 2014 10:28:24 -0700 (PDT) Subject: Recommended hosting In-Reply-To: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> References: <7ff10d72-fb50-4413-aa79-444a52cfd9dd@googlegroups.com> Message-ID: <8dc82760-e5ad-4edc-9220-d54f4e323124@googlegroups.com> Hi all, OP here, thanks for all your reply's, all very useful. I'm going to check out a couple and see what works for the project I have in mind. Thanks again! Doug From joel.goldstick at gmail.com Mon Oct 6 13:31:59 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 6 Oct 2014 13:31:59 -0400 Subject: Python 2.76 In-Reply-To: References: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> <12E3ADFE8ADEDA4E9FF28E92C724928964F7E7@SVWVAP416.addm.ads.brm.pri> Message-ID: On Mon, Oct 6, 2014 at 11:38 AM, Chris ?Kwpolska? Warrick wrote: > CC'ing the mailing list. > > On Mon, Oct 6, 2014 at 5:29 PM, Sas Parmar > wrote: >> Hi Chris >> >> I need to get in contact with the actual manufacturer of Python. >> >> Do you have an email address or phone number? > > This is a very problematic question. Why do you need to contact ?the > manufacturer?? Python is an open-source language with multiple people > involved. Depending on what your query is, you may want the Python > Software Foundation, a release manager, tons of other people? State > your question here and you may receive an answer or a pointer to > someone with an answer. > > -- > Chris ?Kwpolska? Warrick > PGP: 5EAAEA16 > stop html mail | always bottom-post | only UTF-8 makes sense > -- > https://mail.python.org/mailman/listinfo/python-list Assuming you have a relationship with microsoft, you might try asking them if they support the version of python you want to use. -- Joel Goldstick http://joelgoldstick.com From rustompmody at gmail.com Mon Oct 6 13:48:39 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 6 Oct 2014 10:48:39 -0700 (PDT) Subject: Representing mathematical equations In-Reply-To: References: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> <09669ac4-1aeb-48fa-8cc9-7f741f7fe6b3@googlegroups.com> <28aeb1c6-2a2f-4452-862d-c98b204eab34@googlegroups.com> Message-ID: <381deb51-46e8-480c-9c9b-cf63ebe303c5@googlegroups.com> On Monday, October 6, 2014 10:52:40 PM UTC+5:30, Dave Angel wrote: > varun7rs Wrote in message: > > On Monday, 6 October 2014 15:03:44 UTC+2, Varun wrote: > (Deleted all the 8-space quoting. Either use a better email client > or remove the extra 7 lines between every line you > quote.) > >> Okay, I forgot to explain them. L is a set of links, dist is a number (distance), bd is the bandwidth and hc is a number as well (hopcount)...different bandwidths, hopcounts and distances for different links... > >> b(i,x) is what i intend to calculate out of these details...here 'i' could be the head or tail of the link l and x is a node that hosts i > > Unbelievable. I again forgot to express them > > L = [(1,3), (5,7), .....] > > bd = [23, 34,43.44.....] > > dist = [3,7,5,7, ....] > > hc = [2,3,4,1,2,2,...] > > for every l belonging to L, i could be either 1 or 3 for L[0], similarly for L[1] it could be 5 or 7 > Now it's clear I don't have a clue. L is either a set or a list. > Little l is an element of that set, and is either a tuple or is > mysteriously subscripted by a boolean at the other end of the > expression. .. As Dave says there are too many loose ends in your spec to make much sense. Anyway heres a small start to help you start off -- both for cleaning up your spec as well as moving towards an implementation Take your denominator term: ?(l?L) l You also say "i could be head or tail of l" Dunno what to make of that 'or'... Toss a coin and choose?? So here are two version that will calculate the denominator for head and for tail >>> L = [(1,3), (5,7)] >>> sum(x for (x,y) in L) 6 >>> sum(y for (x,y) in L) 10 If you need to examine the sub-expressions (always a good idea!), use >>> (x for (x,y) in L) at 0x7fe04025c730> Whazzat? >>> list(x for (x,y) in L) [1, 5] Or just simply >>> [x for (x,y) in L] [1, 5] You can use that literally in the sum >>> sum([x for (x,y) in L]) 6 >>> sum([(x,y) for (x,y) in L]) Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'tuple' Python just expressing that you are goofing off by trying to add tuples rather than numbers >>> sum([l for l in L]) Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'tuple' Same as above From rosuav at gmail.com Mon Oct 6 13:50:34 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 7 Oct 2014 04:50:34 +1100 Subject: Python 2.76 In-Reply-To: References: <12E3ADFE8ADEDA4E9FF28E92C724928964F765@SVWVAP416.addm.ads.brm.pri> <12E3ADFE8ADEDA4E9FF28E92C724928964F7E7@SVWVAP416.addm.ads.brm.pri> Message-ID: On Tue, Oct 7, 2014 at 4:31 AM, Joel Goldstick wrote: > Assuming you have a relationship with microsoft, you might try asking > them if they support the version of python you want to use. I'm not sure there's any official Microsoft support for existing versions of Python. With Steve Dower of Microsoft joining the Python dev team, that will be changing as of 3.5 (though the full extent of his input may not be visible until 3.6), but I don't know what's happening with 2.7. In any case, I doubt you'll get anywhere by asking MS to support the application; much better to simply ask the application vendor... which is exactly what the OP did. ChrisA From rustompmody at gmail.com Mon Oct 6 14:06:17 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 6 Oct 2014 11:06:17 -0700 (PDT) Subject: Representing mathematical equations In-Reply-To: <381deb51-46e8-480c-9c9b-cf63ebe303c5@googlegroups.com> References: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> <09669ac4-1aeb-48fa-8cc9-7f741f7fe6b3@googlegroups.com> <28aeb1c6-2a2f-4452-862d-c98b204eab34@googlegroups.com> <381deb51-46e8-480c-9c9b-cf63ebe303c5@googlegroups.com> Message-ID: On Monday, October 6, 2014 11:18:55 PM UTC+5:30, Rustom Mody wrote: > >>> sum([(x,y) for (x,y) in L]) > Traceback (most recent call last): > TypeError: unsupported operand type(s) for +: 'int' and 'tuple' > Python just expressing that you are goofing off by trying to add tuples > rather than numbers I forgot to mention that this comes from just taking your denominator term "?(l?L) l" literally. From steve+comp.lang.python at pearwood.info Mon Oct 6 14:54:17 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 07 Oct 2014 05:54:17 +1100 Subject: ruby instance variable in python References: Message-ID: <5432e55b$0$12995$c3e8da3$5496439d@news.astraweb.com> roro codeath wrote: > in ruby: > > module M > def ins_var > @ins_var ||= nil > end > > def m > @ins_var = 'val' > end > > def m2 > m > ins_var # => 'val' > end > end I admit that my Ruby skills are admittedly pretty lousy. Still, I used to think that Ruby was pretty readable, but I find the above completely meaningless. So I'm going to guess what you want, sorry if I guess wrong. > in py: > > # m.py > > # how to def ins_var > > def m: > # how to set ins_var > > def m2: > m() > # how to get ins var Please explain what you mean by "instance variable". There are two standard things which it could be. (1) A string variable is a variable holding a string. A float variable is a variable holding a float. A list variable is a variable holding a list. So an instance variable must be a variable holding an instance. ins_var = NameOfTheClass(arg) You just instantiate the class, passing whatever arguments it expects. (2) In the Java world, "instance variable" doesn't mean a variable at all, but an attribute of classes which is stored on the instance. (As opposed to those attributes stored on the class itself, which they refer to as "static", since in Java they are known to the compiler.) To define "instance variables" (attributes), you have to have a class to define them in. Remember that Python uses the "Offside Rule" (significant indentation). class MyClass(object): # subclass of object def __init__(self, arg): # Initialise the instance. self.ins_var = arg def method(self, arg): return self.ins_var == arg: instance = MyClass("some value") print(instance.ins_var) # prints "some value" instance.method("spam and eggs") # returns False instance.method("some value") # returns True Does this help? -- Steven From steve at pearwood.info Mon Oct 6 16:49:19 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 06 Oct 2014 20:49:19 GMT Subject: Practice question References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> Message-ID: <5433004e$0$2916$c3e8da3$76491128@news.astraweb.com> On Mon, 06 Oct 2014 10:05:40 -0700, Rustom Mody wrote: > On Monday, October 6, 2014 10:22:27 PM UTC+5:30, Chris Angelico wrote: >> On Tue, Oct 7, 2014 at 3:23 AM, Rustom Mody wrote: >> > Consider the sequence: >> > 1. Drives on the wrong side of the road 2. Has no clue that there's >> > such a concept as 'wrong side of road' 3. Teaches people to drive >> > without conveying anything about 'wrong side of road' Hopefully you >> > will agree that 1 < 2 < 3?? My gripe is with 3 > >> No, I don't agree. > > Interesting > > So you dont agree with: "1<2<3" ? I can't speak for Chris, by my answer is neither Yes nor No, but Mu. http://en.wikipedia.org/wiki/Mu_%28negative%29#In_popular_culture I don't understand what semantics you are giving the < symbol. It's not "less than", since statements 1, 2 and 3 above don't have a total order or even a partial order. What does it mean to say that "Drives on the wrong side of the road" is less than "Teaches people to drive without conveying anything about 'wrong side of road'"? Less than in what sense? Alphabetical order? Less dangerous? Less competent? Less annoying? Less expensive? So, no, I don't agree. Nor do I disagree. I have fewer issues with your conclusion and analogy than I do with the basic premise that there is a connection between Seymore's problem here and the use, or non-use, of print in the interactive interpreter. I don't see how replacing interactive use and/or the use of print with functions containing return statements would help Seymore. > Or with "My gripe is 3" ? > > The second would be quite bizarre: If it's bizarre, why do you consider that Chris may mean that? The reasonable thing would be to reject it from contention. > "I have a headache..." > > "Sorry. But I dont agree with that" "I don't agree that you have a headache. You're obviously lying, acting, delusional, an insentient robot programmed to repeat the words 'I have a headache', a zombie (not the brain eating kind, the philosophical kind), a sophisticated bot (but not sophisticated enough to pass the Turing test), or otherwise faking it." I'm just sayin'... -- Steven From sohcahtoa82 at gmail.com Mon Oct 6 17:37:36 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Mon, 6 Oct 2014 14:37:36 -0700 (PDT) Subject: Assignment Operators? In-Reply-To: <9669f493-cfa4-4a84-9f4a-ce3009926ca3@googlegroups.com> References: <9669f493-cfa4-4a84-9f4a-ce3009926ca3@googlegroups.com> Message-ID: On Thursday, October 2, 2014 6:24:37 AM UTC-7, Didymus wrote: > Hi All, > > > > I was wondering if someone could explain an assignment operator that I'm seeing in some code. As an example: > > > > >>> errors = False > > >>> errors |= 3 > > >>> errors > > 3 > > >>> errors |= 4 > > >>> errors > > 7 > > > > The '|=' operator, I read should be like a = a | b, but this appears to add the two numbers as long as it's more than the previous: > > > > >>> errors |= 5 > > >>> errors > > 7 > > > > Is there anywhere I can read up more on this and the other assignment operators and what/how they work. I got this off > > > > http://rgruet.free.fr/PQR27/PQR2.7.html > > > > > > I'm using: > > % python > > Python 2.7.5 (default, Sep 25 2014, 13:57:38) > > [GCC 4.8.3 20140911 (Red Hat 4.8.3-7)] on linux2 > > > > > > Thanks for any help in advance. > > > > Tom As others have said, the | operator is a bit-wise 'or', as opposed to a boolean 'or'. False, when evaluated as an integer, converts to 0. So False | 3 is equal to 3, and so your errors variable is now 3. On the next step, you did | again with 4. Now, | didn't ADD 3 and 4 like you think it did. It did a bit-wise or. 3 in binary is 11. 4 in binary is 100. OR them together and you get 111, which is 7. The fact that the two numbers you chose have the same result whether you add them or 'or' them is a coincidence. 5 in binary is 101. When you OR that with 111, you get 111, which is still 7. If you're confused by this, read up on the binary number system and AND/OR/XOR/NAND logic. -DJ From versalytics at gmail.com Mon Oct 6 20:54:42 2014 From: versalytics at gmail.com (Redge @ Versalytics.com) Date: Mon, 6 Oct 2014 20:54:42 -0400 Subject: Practice question In-Reply-To: <5433004e$0$2916$c3e8da3$76491128@news.astraweb.com> References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> <5433004e$0$2916$c3e8da3$76491128@news.astraweb.com> Message-ID: <127D28ED-4BBB-49E8-8E03-EDC84ECF8311@gmail.com> > On Oct 6, 2014, at 4:49 PM, Steven D'Aprano wrote: > >> On Mon, 06 Oct 2014 10:05:40 -0700, Rustom Mody wrote: >> >>> On Monday, October 6, 2014 10:22:27 PM UTC+5:30, Chris Angelico wrote: >>>> On Tue, Oct 7, 2014 at 3:23 AM, Rustom Mody wrote: >>>> Consider the sequence: >>>> 1. Drives on the wrong side of the road 2. Has no clue that there's >>>> such a concept as 'wrong side of road' 3. Teaches people to drive >>>> without conveying anything about 'wrong side of road' Hopefully you >>>> will agree that 1 < 2 < 3?? My gripe is with 3 >> >>> No, I don't agree. >> >> Interesting >> >> So you dont agree with: "1<2<3" ? > > I can't speak for Chris, by my answer is neither Yes nor No, but Mu. > > http://en.wikipedia.org/wiki/Mu_%28negative%29#In_popular_culture > > > I don't understand what semantics you are giving the < symbol. It's not > "less than", since statements 1, 2 and 3 above don't have a total order > or even a partial order. What does it mean to say that "Drives on the > wrong side of the road" is less than "Teaches people to drive without > conveying anything about 'wrong side of road'"? Less than in what sense? > Alphabetical order? Less dangerous? Less competent? Less annoying? Less > expensive? > > So, no, I don't agree. Nor do I disagree. > > I have fewer issues with your conclusion and analogy than I do with the > basic premise that there is a connection between Seymore's problem here > and the use, or non-use, of print in the interactive interpreter. I don't > see how replacing interactive use and/or the use of print with functions > containing return statements would help Seymore. > > > >> Or with "My gripe is 3" ? >> >> The second would be quite bizarre: > > If it's bizarre, why do you consider that Chris may mean that? The > reasonable thing would be to reject it from contention. > > >> "I have a headache..." >> >> "Sorry. But I dont agree with that" > > > "I don't agree that you have a headache. You're obviously lying, acting, > delusional, an insentient robot programmed to repeat the words 'I have a > headache', a zombie (not the brain eating kind, the philosophical kind), > a sophisticated bot (but not sophisticated enough to pass the Turing > test), or otherwise faking it." > > I'm just sayin'... > > > > -- > Steven > -- > I agree that 1<2<3. From a numerical point of view this is correct. The distraction here is the inference that the numbers somehow relate to the statements preceding this conclusion. From denismfmcmahon at gmail.com Mon Oct 6 21:46:37 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 7 Oct 2014 01:46:37 +0000 (UTC) Subject: Practice question References: Message-ID: On Sun, 05 Oct 2014 19:02:31 -0400, Seymore4Head wrote: > For the record, I don't want a hint. I want the answer. > I see a practice question is similar to this. > 15 <= x < 30 And it wants a similar expression that is equivalent. I think part of the problem here is that you don't understand the expression. The expression: 15 <= x < 30 contains two conditions: 15 <= x x < 30 For the whole expression to be true, both conditions must be true, hence the equivalence is: (15 <= x) and (x < 30) to test this in python command line, see if the two different expressions give the same result for a suitable range of values of x: for x in range(50): if not (15 <= x < 30) == ((15 <= x) and (x < 30)): print "discrepancy" or for x in range(50): if (15 <= x < 30) == ((15 <= x) and (x < 30)): print "ok" -- Denis McMahon, denismfmcmahon at gmail.com From torriem at gmail.com Mon Oct 6 22:07:06 2014 From: torriem at gmail.com (Michael Torrie) Date: Mon, 06 Oct 2014 20:07:06 -0600 Subject: Representing mathematical equations In-Reply-To: References: <9ea5c61c-9f06-4bcb-982e-2be0a910b817@googlegroups.com> <09669ac4-1aeb-48fa-8cc9-7f741f7fe6b3@googlegroups.com> <28aeb1c6-2a2f-4452-862d-c98b204eab34@googlegroups.com> Message-ID: <54334ACA.8010405@gmail.com> On 10/06/2014 10:45 AM, Peter Pearson wrote: > I don't think the OP is interested in complex numbers. I think this > is a question about organizing loops. But I can't tell for sure. Poor choice of words on my part. I meant complicated. This is exactly the kind of thing that people use numpy and other libraries to assist with. Right up scipy's alley. From Seymore4Head at Hotmail.invalid Mon Oct 6 22:06:09 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 06 Oct 2014 22:06:09 -0400 Subject: Practice question References: Message-ID: On Tue, 7 Oct 2014 01:46:37 +0000 (UTC), Denis McMahon wrote: >On Sun, 05 Oct 2014 19:02:31 -0400, Seymore4Head wrote: > >> For the record, I don't want a hint. I want the answer. >> I see a practice question is similar to this. >> 15 <= x < 30 And it wants a similar expression that is equivalent. > >I think part of the problem here is that you don't understand the >expression. > >The expression: > >15 <= x < 30 > >contains two conditions: > >15 <= x > >x < 30 > >For the whole expression to be true, both conditions must be true, hence >the equivalence is: > >(15 <= x) and (x < 30) > >to test this in python command line, see if the two different expressions >give the same result for a suitable range of values of x: > >for x in range(50): > if not (15 <= x < 30) == ((15 <= x) and (x < 30)): > print "discrepancy" > >or > >for x in range(50): > if (15 <= x < 30) == ((15 <= x) and (x < 30)): > print "ok" All of the practice questions up to this question had 4 answers. With each question you could verify the correct answers by just copy and pasting each choice into Python. So when the instructions said I could verify this with Python I assumed there might be some way to test if the question was == to each answer. From nicholascannon1 at gmail.com Tue Oct 7 01:35:50 2014 From: nicholascannon1 at gmail.com (Nicholas Cannon) Date: Mon, 6 Oct 2014 22:35:50 -0700 (PDT) Subject: Syntax Highlighting in a tkinter Text widget Message-ID: <43fe05d3-2892-44d0-9a1c-da6e7b7be2e5@googlegroups.com> Hey guys Im working on an open source text editor(https://github.com/nicodasiko/Text-Config-2) and I would like to add syntax highlighting(mainly for python code). I have built the editor in python and the text input is a Text tkinter widget. I know how to add tags and highlight things but Im not sure on how to constantly update the highlighting. From auriocus at gmx.de Tue Oct 7 01:49:44 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Tue, 07 Oct 2014 07:49:44 +0200 Subject: Syntax Highlighting in a tkinter Text widget In-Reply-To: <43fe05d3-2892-44d0-9a1c-da6e7b7be2e5@googlegroups.com> References: <43fe05d3-2892-44d0-9a1c-da6e7b7be2e5@googlegroups.com> Message-ID: Am 07.10.14 07:35, schrieb Nicholas Cannon: > Hey guys Im working on an open source text > editor(https://github.com/nicodasiko/Text-Config-2) and I would like > to add syntax highlighting(mainly for python code). I have built the > editor in python and the text input is a Text tkinter widget. I know > how to add tags and highlight things but Im not sure on how to > constantly update the highlighting. How long do you expect the input to be? If it will be short pieces, just run your regexps at every keystroke. You can also cheat and use an existing tool for syntax highlighting. One possibility is the ctext widget, which is based on the text widget and is part of tcllib: http://tcllib.sourceforge.net/doc/ctext.html All you need to do is to wrap it for the use in Tkinter. Another alternative would be ScintillaTk http://sourceforge.net/projects/scintillatk/ Scintilla is a full-blown editor component, which is used in many code editors as the basic building block. Since this is a compiled extension, I have no idea how hard it will be to interface it with Python, however. Christian From gelonida at gmail.com Tue Oct 7 02:10:05 2014 From: gelonida at gmail.com (Gelonida N) Date: Tue, 07 Oct 2014 08:10:05 +0200 Subject: Pythonic way to iterate through multidimensional space? In-Reply-To: <20140806063923.750b81d6@bigbox.christie.dr> References: <20140806063923.750b81d6@bigbox.christie.dr> Message-ID: On 8/6/2014 1:39 PM, Tim Chase wrote: > On 2014-08-06 11:04, Gayathri J wrote: >> Below is the code I tried to check if itertools.product() was >> faster than normal nested loops... >> >> they arent! arent they supposed to be...or am i making a mistake? > > I believe something like this was discussed a while ago and there was > a faster-but-uglier solution so you might want to consult this thread: > > https://mail.python.org/pipermail/python-list/2008-January/516109.html > > I believe this may have taken place before itertools.product() came > into existence. > Disadvantage of itertools.product() is, that it makes a copy in memory. Reason ist, that itertools also makes products of generators (meaning of objects, that one can't iterate several times through) There are two use cases, that I occasionaly stumble over: One is making the product over lists(), product( list_of_lists ) ex: product( [ [1,2,3], ['A','B'], ['a', 'b', 'c'] ] ) the other one making a product over a list of functions, which will create generators ex: product( [ lambda: [ 'A', 'B' ], lambda: xrange(3) ] ) I personally would also be interested in a fast generic solution that can iterate through an N-dimensional array and which does not duplicate the memory or iterate through a list of generator-factories or however this would be called. From calderon.christian760 at gmail.com Mon Oct 6 18:58:03 2014 From: calderon.christian760 at gmail.com (Christian Calderon) Date: Mon, 6 Oct 2014 15:58:03 -0700 Subject: Interesting socket behavior Message-ID: I noticed that if I make a listening socket using SOCK_STREAM | SOCK_NONBLOCK, that the sockets I get after calling listener.accept() don't have the O_NONBLOCK flag set, but checking the result of gettimeout() on the same sockets gives me 0.0, which means they are non blocking. Why is this the case? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nicholascannon1 at gmail.com Tue Oct 7 04:18:28 2014 From: nicholascannon1 at gmail.com (Nicholas Cannon) Date: Tue, 7 Oct 2014 01:18:28 -0700 (PDT) Subject: Syntax Highlighting in a tkinter Text widget In-Reply-To: <43fe05d3-2892-44d0-9a1c-da6e7b7be2e5@googlegroups.com> References: <43fe05d3-2892-44d0-9a1c-da6e7b7be2e5@googlegroups.com> Message-ID: Sweet thanks for the help many I am defiantly going to use these. From steve at pearwood.info Tue Oct 7 04:41:24 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 07 Oct 2014 08:41:24 GMT Subject: Practice question References: Message-ID: <5433a734$0$2916$c3e8da3$76491128@news.astraweb.com> On Sun, 05 Oct 2014 20:07:50 -0400, Seymore4Head wrote: > Here is the exact question, I was trying to post something similar. I > failed. > > http://i.imgur.com/iUGh4xf.jpg Please don't post screen shots if you can avoid it. You almost certainly can copy and paste the text from the web page. And if you can't, you can usually re-type the question. It's good practice to strength your typing skills. Screen shots cannot be read by people using a screen reader, or who don't have access to the web (but are reading their mail), or if the host site (in this case, imgur) is down or blocked. -- Steven From steve at pearwood.info Tue Oct 7 04:48:55 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 07 Oct 2014 08:48:55 GMT Subject: Practice question References: Message-ID: <5433a8f7$0$2916$c3e8da3$76491128@news.astraweb.com> On Sun, 05 Oct 2014 20:18:13 -0400, Seymore4Head wrote: > I think I get it now. You are using a sample of answers. So you could > actually just run through them all. (I haven't tried this yet) > > for x in range(lo,hi) > print((15 <= x < 30) == (15<= x and x <30)) Yes, except using print is probably not the best idea, since you might have dozens of True True True True ... printed, one per line, and if you blink the odd False might have scrolled off screen before you notice. With two numbers, 15 and 30, all you really need is five test cases: - a number lower than the smaller of the two numbers (say, 7); - a number equal to the smaller of the two numbers (that is, 15); - a number between the two numbers (say, 21); - a number equal to the larger of the two numbers (that is, 30); - a number higher than the larger of the two numbers (say, 999); The exact numbers don't matter, so long as you test all five cases. And rather than printing True True True... let's use assert instead: for x in (7, 15, 21, 30, 999): assert (15 <= x < 30) == (15<= x and x <30) If the two cases are equal, assert will do nothing. But if they are unequal, assert will raise an exception and stop, and you know that the two cases are not equivalent and can go on to the next possibility. -- Steven From ned at nedbatchelder.com Tue Oct 7 07:01:29 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Tue, 07 Oct 2014 07:01:29 -0400 Subject: Pythonic way to iterate through multidimensional space? In-Reply-To: References: <20140806063923.750b81d6@bigbox.christie.dr> Message-ID: On 10/7/14 2:10 AM, Gelonida N wrote: > > Disadvantage of itertools.product() is, that it makes a copy in memory. > Reason ist, that itertools also makes products of generators (meaning of > objects, that one can't iterate several times through) > > > There are two use cases, that I occasionaly stumble over: > > One is making the product over lists(), > product( list_of_lists ) > > ex: > > product( [ [1,2,3], ['A','B'], ['a', 'b', 'c'] ] ) > > the other one making a product over a list of functions, which will > create generators > > ex: > product( [ lambda: [ 'A', 'B' ], lambda: xrange(3) ] ) > > > I personally would also be interested in a fast generic solution that > can iterate through an N-dimensional array and which does not duplicate > the memory or iterate through a list of generator-factories or however > this would be called. itertools.product makes a copy of the sequences passed in, but it is a shallow copy. It doesn't copy the objects in the sequences. It also doesn't store the entire product. If you are calling product(j, k, l, m, n), where len(j)==J, the extra memory is J+K+L+M+N, which is much smaller than the number of iterations product will produce. Are you sure that much extra memory use is a problem? How large are your lists that you are product'ing together? I don't understand your point about a list of functions that create generators? What is the problem there? -- Ned Batchelder, http://nedbatchelder.com From flebber.crue at gmail.com Tue Oct 7 08:29:11 2014 From: flebber.crue at gmail.com (flebber) Date: Tue, 7 Oct 2014 05:29:11 -0700 (PDT) Subject: ruby instance variable in python In-Reply-To: References: Message-ID: On Monday, 6 October 2014 21:07:24 UTC+11, roro codeath wrote: > in ruby: > > > module M > def ins_var > @ins_var ||= nil > end > > > def m > @ins_var = 'val' > end > > > def m2 > m > ins_var # => 'val' > end > end > > > in py: > > > # m.py > > > # how to def ins_var > > > def m: > ? ? # how to set ins_var > > > def m2: > ? ? m() > ? ? # how to get ins var I took || to be a ternary. So I assumed your code just sets ins_var to nil and then is called in module m and supplied a val. Could be wrong. if ins_var is None: ins_var = 'val' From illusiontechniques at gmail.com Tue Oct 7 08:43:33 2014 From: illusiontechniques at gmail.com (C Smith) Date: Tue, 7 Oct 2014 05:43:33 -0700 Subject: Practice question In-Reply-To: <5433a8f7$0$2916$c3e8da3$76491128@news.astraweb.com> References: <5433a8f7$0$2916$c3e8da3$76491128@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >>With two numbers, 15 and 30, all you really need is five test cases: My solution assumed integers also, but after I posted it, I thought: "What about floating points?" On Tue, Oct 7, 2014 at 1:48 AM, Steven D'Aprano wrote: > On Sun, 05 Oct 2014 20:18:13 -0400, Seymore4Head wrote: > >> I think I get it now. You are using a sample of answers. So you could >> actually just run through them all. (I haven't tried this yet) >> >> for x in range(lo,hi) >> print((15 <= x < 30) == (15<= x and x <30)) > > Yes, except using print is probably not the best idea, since you might > have dozens of True True True True ... printed, one per line, and if you > blink the odd False might have scrolled off screen before you notice. > > With two numbers, 15 and 30, all you really need is five test cases: > > - a number lower than the smaller of the two numbers (say, 7); > - a number equal to the smaller of the two numbers (that is, 15); > - a number between the two numbers (say, 21); > - a number equal to the larger of the two numbers (that is, 30); > - a number higher than the larger of the two numbers (say, 999); > > > The exact numbers don't matter, so long as you test all five cases. And > rather than printing True True True... let's use assert instead: > > > for x in (7, 15, 21, 30, 999): > assert (15 <= x < 30) == (15<= x and x <30) > > > If the two cases are equal, assert will do nothing. But if they are > unequal, assert will raise an exception and stop, and you know that the > two cases are not equivalent and can go on to the next possibility. > > > -- > Steven > -- > https://mail.python.org/mailman/listinfo/python-list From jpiitula at ling.helsinki.fi Tue Oct 7 08:46:14 2014 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 07 Oct 2014 15:46:14 +0300 Subject: ruby instance variable in python References: Message-ID: flebber writes: > On Monday, 6 October 2014 21:07:24 UTC+11, roro codeath wrote: > > in ruby: > > > > > > module M > > def ins_var > > @ins_var ||= nil > > end ... > I took || to be a ternary. So I assumed your code just sets ins_var > to nil and then is called in module m and supplied a val. Could be > wrong. > > if ins_var is None: > ins_var = 'val' Just out of interest, please, do you think the word 'ternary' is more or less synonymous with 'conditional'? I'm not being sarcastic. This possibility just occurred to me, and the world will begin to make more sense to me if it turns out that there are people who simply do not think 'three' when they think 'ternary'. From mthaqifisa at gmail.com Tue Oct 7 09:24:26 2014 From: mthaqifisa at gmail.com (mthaqifisa at gmail.com) Date: Tue, 7 Oct 2014 06:24:26 -0700 (PDT) Subject: add noise using python Message-ID: can someone teach me how to generate noisy images by applying Gaussian random noise onto an image? From marco.buttu at gmail.com Tue Oct 7 09:24:54 2014 From: marco.buttu at gmail.com (Marco Buttu) Date: Tue, 07 Oct 2014 15:24:54 +0200 Subject: Muddleheaded use of the "built-in" term Message-ID: I always thought the builtin objects were those we can get from the `builtins` module, that is those always available. In fact the "Built-in Functions" documentation: https://docs.python.org/3/library/functions.html says: """The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order""". The functions in the documentation list, as expected, are the same functions we get from the `builtins` module. Now, is `math.sin` builtin? Of course not, because it is not an attribute of builtins: >>> import builtins >>> hasattr(builtins, 'sin') False and in fact it is not always available: >>> sin Traceback (most recent call last): ... NameError: name 'sin' is not defined But what happens if I want to check by using `inspect.isbuiltin`? The answer surprises me: >>> import inspect >>> print(inspect.isbuiltin.__doc__.split('\n')[0]) Return true if the object is a built-in function or method. >>> import math >>> inspect.isbuiltin(math.sin) True That's because the term "built-in" here means "written in C", as explained here: https://docs.python.org/3/library/types.html#types.BuiltinMethodType So, we have built-in objects that are always available, whose names live in the builtin namespace, and other built-in objects that do not live in the builtin namespace :/ By using the same word (built-in) to indicate either objects written in C or objects referenced by the builtin namespace could be a bit muddler for everyone, beginner or not. Is it too late for changing the name of the `builtin` namespace in something like, for instance, `root` namespace, or using the name "core" (inspect.iscore(), types.CoreFunctionType, ecc.) to indicate "written in C"? -- Marco Buttu From rosuav at gmail.com Tue Oct 7 09:26:37 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 8 Oct 2014 00:26:37 +1100 Subject: add noise using python In-Reply-To: References: Message-ID: On Wed, Oct 8, 2014 at 12:24 AM, wrote: > can someone teach me how to generate noisy images by applying Gaussian random noise onto an image? http://www.lmgtfy.com/?q=python+image+gaussian+random+noise ChrisA From rosuav at gmail.com Tue Oct 7 09:40:43 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 8 Oct 2014 00:40:43 +1100 Subject: Muddleheaded use of the "built-in" term In-Reply-To: References: Message-ID: On Wed, Oct 8, 2014 at 12:24 AM, Marco Buttu wrote: > Is it too late for changing the name of the `builtin` namespace in something > like, for instance, `root` namespace, or using the name "core" > (inspect.iscore(), types.CoreFunctionType, ecc.) to indicate "written in C"? Yes, I think it's too late to change that. But it's no different from any other word that has more than one variant of meaning; you have to cope with the collisions. Is there any situation where it's ambiguous? There are builtin name bindings, and there are built-in functions. The former are provided by the language core and are thus available by default; the latter are provided by the language core and thus do not provide __code__. There's a connection between the meanings, but they aren't identical. What's a function? Obviously something created with def or lambda is. Is a class a function? Is an object with a __call__ method a function? Is a list comprehension a function? In different senses, all of them are; but maybe what you want to ask is not "is this a function" but "is this callable" (list comps aren't), or "does this create a new local scope", or "does this have __code__" or something. Yet the meanings of "function" are all related (mostly by external usage; list comps by internal functionality), so it wouldn't make sense to decry the collisions on that word. I do see your issue, but I don't think this can be changed, nor is worth changing. ChrisA From marco.buttu at gmail.com Tue Oct 7 09:02:22 2014 From: marco.buttu at gmail.com (Marco Buttu) Date: Tue, 07 Oct 2014 15:02:22 +0200 Subject: Muddleheaded use of the "built-in" term Message-ID: <5433E45E.5020605@oa-cagliari.inaf.it> I always thought the builtin objects were those we can get from the `builtins` module, that is those always available. In fact the "Built-in Functions" documentation: https://docs.python.org/3/library/functions.html says: """The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order""". The functions in the documentation list, as expected, are the same functions we get from the `builtins` module. Now, is `math.sin` builtin? Of course not, because it is not an attribute of builtins: >>> import builtins >>> hasattr(builtins, 'sin') False and in fact it is not always available: >>> sin Traceback (most recent call last): ... NameError: name 'sin' is not defined But what happens if I want to check by using `inspect.isbuiltin()`? The answer surprises me: >>> import inspect >>> print(inspect.isbuiltin.__doc__.split('\n')[0]) Return true if the object is a built-in function or method. >>> import math >>> inspect.isbuiltin(math.sin) True That's because the term "built-in" here means "written in C", as explained in the doc: https://docs.python.org/3/library/types.html#types.BuiltinMethodType So, we have built-in objects that are always available, whose names live in the builtin namespace, and other built-in objects that do not live in the builtin namespace :/ By using the same word (built-in) to indicate either objects written in C or objects referenced by the builtin namespace could be a bit muddler for everyone, beginner or not. Is it too late for changing the name of the `builtin` namespace in something like, for instance, `root` namespace, or using the name "core" (inspect.iscore(), types.CoreFunctionType, ecc.) to indicate "written in C or whatever underlying language"? -- Marco Buttu INAF-Osservatorio Astronomico di Cagliari Via della Scienza n. 5, 09047 Selargius (CA) Phone: 070 711 80 217 Email: mbuttu at oa-cagliari.inaf.it From jonathan.slenders at gmail.com Tue Oct 7 12:15:49 2014 From: jonathan.slenders at gmail.com (jonathan.slenders at gmail.com) Date: Tue, 7 Oct 2014 09:15:49 -0700 (PDT) Subject: How do I check if a string is a prefix of any possible other string that matches a given regex. Message-ID: Hi everyone, Probably I'm turning the use of regular expressions upside down with this question. I don't want to write a regex that matches prefixes of other strings, I know how to do that. I want to generate a regex -- given another regex --, that matches all possible strings that are a prefix of a string that matches the given regex. E.g. You have the regex ^[a-z]*4R$ then the strings "a", "ab", "A4" "ab4" are prefixes of this regex (because there is a way of adding characters that causes the regex to match), but "4a" or "a44" or not. How do I programmatically create a regex that matches "a", "ab", "A4", etc.. but not "4a", "a44", etc.. Logically, I'd think it should be possible by running the input string against the state machine that the given regex describes, and if at some point all the input characters are consumed, it's a match. (We don't have to run the regex until the end.) But I cannot find any library that does it... Thanks a lot, if anyone knows the answer to this question! Cheers, Jonathan From joshua at landau.ws Tue Oct 7 13:01:56 2014 From: joshua at landau.ws (Joshua Landau) Date: Tue, 7 Oct 2014 18:01:56 +0100 Subject: How do I check if a string is a prefix of any possible other string that matches a given regex. In-Reply-To: References: Message-ID: On 7 October 2014 17:15, wrote: > Probably I'm turning the use of regular expressions upside down with this question. I don't want to write a regex that matches prefixes of other strings, I know how to do that. I want to generate a regex -- given another regex --, that matches all possible strings that are a prefix of a string that matches the given regex. > [...] > Logically, I'd think it should be possible by running the input string against the state machine that the given regex describes, and if at some point all the input characters are consumed, it's a match. (We don't have to run the regex until the end.) But I cannot find any library that does it... How wide a net are you counting "regular expressions" to be? What grammar are you using? From cldistefano at att.net Tue Oct 7 13:04:58 2014 From: cldistefano at att.net (Carl Distefano) Date: Tue, 7 Oct 2014 10:04:58 -0700 Subject: Python 3.4.1 on W2K? Message-ID: <1412701498.34731.YahooMailNeo@web181603.mail.ne1.yahoo.com> Tim G.: > Of course, if you're happy to work with a slightly older > version of Python, such as 3.2, then you should be fine. Well, I just installed 3.2.5 in W2K and all of my "stuff" seems to work. I'm a happy camper. Many thanks for the information and link! ChrisA: > Wow. I wonder, since you're already poking around with > extremely legacy stuff, would it be easier for you to use OS/2 > instead of Win2K? Paul Smedley still produces OS/2 builds of > Python, and OS/2 itself runs happily under VirtualBox (we have > an OS/2 VM still on our network here, and I use Python to > manage its backups). Might not end up any better than your > current system, but it might be! That's actually an interesting idea. OS/2 was our OS of choice in the '90s. XyWrite ran beautifully under it, and when we needed extensions to the XyWrite Programming Language (XPL) we used Rexx ("RexXPL"). Since last year I've been using Python instead ("XPyL"). The fact is, though, most XyWriters are running XyWrite under Windows, except for the few running it under Linux. Much of our script development since then has focused on integrating Xy with Windows, so to revert to OS/2 would be swimming against the tide. But I may just try it anyway! Thanks, guys. Pal A. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Tue Oct 7 14:35:41 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 7 Oct 2014 12:35:41 -0600 Subject: How do I check if a string is a prefix of any possible other string that matches a given regex. In-Reply-To: References: Message-ID: On Tue, Oct 7, 2014 at 10:15 AM, wrote: > Logically, I'd think it should be possible by running the input string against the state machine that the given regex describes, and if at some point all the input characters are consumed, it's a match. (We don't have to run the regex until the end.) But I cannot find any library that does it... Strictly speaking, a DFA or NFA always consumes the entire input; the question of interest is whether it halts in an accepting state or not. It would be easy to transform a DFA or NFA in the manner that you want, though. For each non-accepting state, determine whether it has any transitions that lead in one or more steps to an accepting state. Modify the FSM so that each such state is also an accepting state. From wadson.espindola at gmail.com Tue Oct 7 15:07:53 2014 From: wadson.espindola at gmail.com (wadson.espindola at gmail.com) Date: Tue, 7 Oct 2014 12:07:53 -0700 (PDT) Subject: Need some direction in completing the exercise below, appreciate any input given, thanks! Message-ID: <17be299f-1539-456e-8735-2cd6c93ad46b@googlegroups.com> The aim of this exercise is to combine the sample database, click tracking information from a test website and application, and information from user's social networks. The sample database contains the following fields and is made up of 500 records. first_name, last_name, company_name, address, city, county, state, zip, phone1, phone2, email, web Here are the instructions: 1) Download the US500 database from http://www.briandunning.com/sample-data/ 2) Use the exchange portion of the telephone numbers (the middle three digits) as the proxy for "user clicked on and expressed interest in this topic". Identify groups of users that share topic interests (exchange numbers match). 3) Provide an API that takes an e-mail address an input, and returns the e-mail addresses of other users that share that interest. 4) Extend that API to return users within a certain "distance" N of that interest. For example, if the original user has an interest in group 236, and N is 2, return all users with interests in 234 through 238. 5) Identify and rank the states with the largest groups, and (separately) the largest number of groups. 6) Provide one or more demonstrations that the API works. These can be via a testing framework, and/or a quick and dirty web or command line client, or simply by driving it from a browser and showing a raw result. I was able to import the data this way, however I know there's a better method using the CSV module. The code below just reads lines, I'd like to be able to split each individual field into columns and assign primary and foreign keys in order to solve the challenge. What's the best method to accomplish this task? import os, csv, json, re class fetch500(): # class instantiation def __init__(self): # initializes data import object US_500file = open('us-500.csv') us_500list = US_500file.readlines() for column in us_500list: print column, # prints out phone1 array data_import = fetch500() print fetch500() From torriem at gmail.com Tue Oct 7 16:27:39 2014 From: torriem at gmail.com (Michael Torrie) Date: Tue, 07 Oct 2014 14:27:39 -0600 Subject: Python 3.4.1 on W2K? In-Reply-To: <1412553844.20683.YahooMailNeo@web181605.mail.ne1.yahoo.com> References: <1412553844.20683.YahooMailNeo@web181605.mail.ne1.yahoo.com> Message-ID: <54344CBB.70207@gmail.com> On 10/05/2014 06:04 PM, Pal Acreide wrote: > BTW, the reason I run VBox is that I belong to a group of diehard > users of the classic DOS word-processor XyWrite. I've devised a way > to use Python as an extension of XyWrite's built-in Programming > Language (XPL): http://users.datarealm.com/xywwweb/xypydoc.htm That's really interesting. I looked briefly at the page. How does your python extension work with xywrite? Does it manipulate xywrite documents or does it tie in at runtime with Xywrite somehow? If so, how does it do this? Crossing the divide into a 16-bit app is pretty impressive. I wonder how well your system could be made to work with dosbox. Dosbox runs xywrite on any platform (even non x86 like a tablet). I'm not sure how you'd interface dosbox with python on the host though. From random832 at fastmail.us Tue Oct 7 16:33:23 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Tue, 07 Oct 2014 16:33:23 -0400 Subject: Python 3.4.1 on W2K? In-Reply-To: <54344CBB.70207@gmail.com> References: <1412553844.20683.YahooMailNeo@web181605.mail.ne1.yahoo.com> <54344CBB.70207@gmail.com> Message-ID: <1412714003.2849393.176297141.1B143056@webmail.messagingengine.com> On Tue, Oct 7, 2014, at 16:27, Michael Torrie wrote: > That's really interesting. I looked briefly at the page. How does your > python extension work with xywrite? Does it manipulate xywrite > documents or does it tie in at runtime with Xywrite somehow? If so, how > does it do this? Crossing the divide into a 16-bit app is pretty > impressive. I assume that it uses temporary files (or pipes, don't know if DOS can do this), and that DOS programs can execute windows programs with int 21/4B. From Seymore4Head at Hotmail.invalid Tue Oct 7 17:26:05 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Tue, 07 Oct 2014 17:26:05 -0400 Subject: Timezones References: <90928119-0c8d-4c85-baca-99af580ca227@googlegroups.com> Message-ID: On Mon, 6 Oct 2014 13:48:58 +1100, Chris Angelico wrote: >On Mon, Oct 6, 2014 at 1:37 PM, Rustom Mody wrote: >>> My advice is to avoid time zones, they're a real pain, seriously. >> >> What say we send an application to the UN to declare the world flat? > >Easier to simply start scheduling things in UTC. I run an >international Dungeons & Dragons campaign with sessions every Sunday >at 02:00 UTC, and nobody needs to be confused by time zones. (The >server displays UTC time, so it's easy for anyone to see; for >instance, it's now Mon 02:48:09, so session time was about this time >yesterday.) Civil time can do whatever it likes, just as long as >everyone knows that the meeting is based on UTC. > >ChrisA And I just found out there is going to be another Y2K in 2038. I hope I am around to see it. I spend this Y2K in Las Vegas. Las Vegas is one of the last few time zones so TVs everywhere were showing the ringing in of the New Year and nothing was exploding. From jonathan.slenders at gmail.com Tue Oct 7 17:48:38 2014 From: jonathan.slenders at gmail.com (jonathan.slenders at gmail.com) Date: Tue, 7 Oct 2014 14:48:38 -0700 (PDT) Subject: How do I check if a string is a prefix of any possible other string that matches a given regex. In-Reply-To: References: Message-ID: <8c47cee0-7fec-4fb7-b32a-ddac6fd7c247@googlegroups.com> > > Logically, I'd think it should be possible by running the input string against the state machine that the given regex describes, and if at some point all the input characters are consumed, it's a match. (We don't have to run the regex until the end.) But I cannot find any library that does it... > > > > Strictly speaking, a DFA or NFA always consumes the entire input; the > > question of interest is whether it halts in an accepting state or not. > > > > It would be easy to transform a DFA or NFA in the manner that you > > want, though. For each non-accepting state, determine whether it has > > any transitions that lead in one or more steps to an accepting state. > > Modify the FSM so that each such state is also an accepting state. Thanks, I'll make every state of the FSM an accepting state. My use case is to implement autocompletion for a regular language. So I think if the input is accepted by the FSM that I build, it's a valid "prefix", and the autocompletion can be generated by looking at which transitions are possible at that point. More pointers are welcome, but I think that I have enough to start the implementation. From Seymore4Head at Hotmail.invalid Tue Oct 7 19:12:31 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Tue, 07 Oct 2014 19:12:31 -0400 Subject: Another time question Message-ID: I never really cared enough to ask anyone, but something like my cable bill is 98$ a month. Do companies (in general) consider a month every 30 days or every time the 14th comes around? I did rent a car once during a time change and I only got to keep the car 23 hours. As another side note I have had drug prescripts that were 28 days was considered a month supply. The would be 4 weeks instead of one month. From rosuav at gmail.com Tue Oct 7 19:21:10 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 8 Oct 2014 10:21:10 +1100 Subject: Another time question In-Reply-To: References: Message-ID: On Wed, Oct 8, 2014 at 10:12 AM, Seymore4Head wrote: > I never really cared enough to ask anyone, but something like my cable > bill is 98$ a month. Do companies (in general) consider a month every > 30 days or every time the 14th comes around? > > I did rent a car once during a time change and I only got to keep the > car 23 hours. > > As another side note I have had drug prescripts that were 28 days was > considered a month supply. The would be 4 weeks instead of one month. I'm not sure how this connects to Python, but I'll assume for now you're trying to do something up as a script and just haven't told us that bit... With periodic recurring charges, it's common for "month" to mean "calendar month", resetting every Nth of the month (often 1st, but any day works). If your mobile data plan costs $35/month and allows you 7GB/month throughput, both those figures will be per calendar month. For the rest, it depends on what the company's doing. Presumably drug prescriptions are primarily done on a weekly basis; car rentals will be on a daily basis. They're not going to say "cars have to be returned by 8AM, except during DST when they must be returned by 9AM", because that's just messy; so one day a year, you get an extra hour, and one day a year, you lose an hour. If you tell us what the code is you're trying to work on, we might be able to advise more usefully. ChrisA From python at mrabarnett.plus.com Tue Oct 7 19:39:50 2014 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 08 Oct 2014 00:39:50 +0100 Subject: How do I check if a string is a prefix of any possible other string that matches a given regex. In-Reply-To: <8c47cee0-7fec-4fb7-b32a-ddac6fd7c247@googlegroups.com> References: <8c47cee0-7fec-4fb7-b32a-ddac6fd7c247@googlegroups.com> Message-ID: <543479C6.3080203@mrabarnett.plus.com> On 2014-10-07 22:48, jonathan.slenders at gmail.com wrote: > >>> Logically, I'd think it should be possible by running the input >>> string against the state machine that the given regex describes, >>> and if at some point all the input characters are consumed, it's >>> a match. (We don't have to run the regex until the end.) But I >>> cannot find any library that does it... >> >> Strictly speaking, a DFA or NFA always consumes the entire input; >> the question of interest is whether it halts in an accepting state >> or not. >> >> It would be easy to transform a DFA or NFA in the manner that you >> want, though. For each non-accepting state, determine whether it >> has any transitions that lead in one or more steps to an accepting >> state. >> >> Modify the FSM so that each such state is also an accepting state. > > Thanks, I'll make every state of the FSM an accepting state. > > My use case is to implement autocompletion for a regular language. > So I think if the input is accepted by the FSM that I build, it's a > valid "prefix", and the autocompletion can be generated by looking > at which transitions are possible at that point. > > More pointers are welcome, but I think that I have enough to start > the implementation. > If you're not interested in generating an actual regex, but only in matching the prefix, then it sounds like you want "partial matching". The regex module supports that: https://pypi.python.org/pypi/regex From Seymore4Head at Hotmail.invalid Tue Oct 7 20:35:32 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Tue, 07 Oct 2014 20:35:32 -0400 Subject: Another time question References: Message-ID: On Wed, 8 Oct 2014 10:21:10 +1100, Chris Angelico wrote: >On Wed, Oct 8, 2014 at 10:12 AM, Seymore4Head > wrote: >> I never really cared enough to ask anyone, but something like my cable >> bill is 98$ a month. Do companies (in general) consider a month every >> 30 days or every time the 14th comes around? >> >> I did rent a car once during a time change and I only got to keep the >> car 23 hours. >> >> As another side note I have had drug prescripts that were 28 days was >> considered a month supply. The would be 4 weeks instead of one month. > >I'm not sure how this connects to Python, but I'll assume for now >you're trying to do something up as a script and just haven't told us >that bit... > >With periodic recurring charges, it's common for "month" to mean >"calendar month", resetting every Nth of the month (often 1st, but any >day works). If your mobile data plan costs $35/month and allows you >7GB/month throughput, both those figures will be per calendar month. >For the rest, it depends on what the company's doing. Presumably drug >prescriptions are primarily done on a weekly basis; car rentals will >be on a daily basis. They're not going to say "cars have to be >returned by 8AM, except during DST when they must be returned by 9AM", >because that's just messy; so one day a year, you get an extra hour, >and one day a year, you lose an hour. > >If you tell us what the code is you're trying to work on, we might be >able to advise more usefully. > >ChrisA Actually, the simple python code I am working on is not required to consider those complicated questions, but it still causes me to ponder them. From flebber.crue at gmail.com Tue Oct 7 20:59:44 2014 From: flebber.crue at gmail.com (flebber) Date: Tue, 7 Oct 2014 17:59:44 -0700 (PDT) Subject: ruby instance variable in python In-Reply-To: References: Message-ID: <48972e63-c980-4025-a624-cda0b60367de@googlegroups.com> I thought that it was a shortcut in ruby to negate the other option of providing another default . I don't greatly know ruby but took a guess after reading examples here https://blog.neowork.com/ruby-shortcuts From steve+comp.lang.python at pearwood.info Tue Oct 7 21:32:34 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 08 Oct 2014 12:32:34 +1100 Subject: ruby instance variable in python References: <48972e63-c980-4025-a624-cda0b60367de@googlegroups.com> Message-ID: <54349433$0$13001$c3e8da3$5496439d@news.astraweb.com> flebber wrote: > I thought that it was a shortcut in ruby to negate the other option of > providing another default . I'm afraid I can't work out what that sentence means, "to negate the other option of providing *another* default"? How many defaults are you providing? Then you negate *the option*, does that mean that you're not actually providing a default? Also, since you haven't quoted the person you are responding to, there is no context to your response. The end result of a confusing sentence with no context is that I have no idea what you are trying to say. Could you try explaining again please? -- Steven From steve+comp.lang.python at pearwood.info Tue Oct 7 21:39:46 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 08 Oct 2014 12:39:46 +1100 Subject: Another time question References: Message-ID: <543495e3$0$12987$c3e8da3$5496439d@news.astraweb.com> Seymore4Head wrote: > I never really cared enough to ask anyone, but something like my cable > bill is 98$ a month. Do companies (in general) consider a month every > 30 days or every time the 14th comes around? What does this have to do with Python? Companies do whatever they want. Some of them consider a month to start from the 1st and end at the end of the month, some of them take 30 days from the date you started, some of them 31 days from when you start, or 28 days (four weeks). Some of them have a fixed starting date. Some of them don't. Some bill you fortnightly, or weekly, or yearly. > I did rent a car once during a time change and I only got to keep the > car 23 hours. I'm not sure how that is relevant to either Python or what companies consider a month, but okay. > As another side note I have had drug prescripts that were 28 days was > considered a month supply. The would be 4 weeks instead of one month. Okay. -- Steven From steve+comp.lang.python at pearwood.info Tue Oct 7 21:41:54 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 08 Oct 2014 12:41:54 +1100 Subject: operator module functions Message-ID: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> Every Python operator has a function version in the operator module: operator + has function operator.add; operator - has function operator.sub; operator * has function operator.mul; and so forth. Only, that's not quite right... according to the documentation, the "official" functions are actually: operator.__add__; operator.__sub__; operator.__mul__; etc., with the underscore-less versions being provided as a convenience. Was anyone aware of this? It came as a surprise to me. Is there anyone who uses or prefers the dunder versions? -- Steven From joshua.higgins.pcv at gmail.com Tue Oct 7 21:51:42 2014 From: joshua.higgins.pcv at gmail.com (joshua.higgins.pcv at gmail.com) Date: Tue, 7 Oct 2014 18:51:42 -0700 (PDT) Subject: Perl Template Toolkit: Now in spicy new Python flavor In-Reply-To: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> Message-ID: <292a8089-9db1-47b9-9885-04c98bc7b69f@googlegroups.com> Sorry, is anyone else having trouble opening the README.txt? On Monday, January 14, 2008 6:00:52 PM UTC-5, eef... at gmail.com wrote: > I'd like to inform the Python community that the powerful and popular > Template Toolkit system, previously available only in its original > Perl implementation, is now also available in a beta Python > implementation: > > http://tt2.org/python/index.html > > I created this port both as a fun programming project, and for use in > environments where Perl is not available, for reasons technical, > cultural, or otherwise. The extensive Perl test suites have also been > ported, and most templates require no or very little modification. > > Discussion of the Python implementation should be conducted on the > main Template Toolkit developer mailing list; see the site above for > details. From rosuav at gmail.com Tue Oct 7 22:09:19 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 8 Oct 2014 13:09:19 +1100 Subject: Perl Template Toolkit: Now in spicy new Python flavor In-Reply-To: <292a8089-9db1-47b9-9885-04c98bc7b69f@googlegroups.com> References: <22bd781f-9abb-4937-a2c8-577cb9fa7cfd@c4g2000hsg.googlegroups.com> <292a8089-9db1-47b9-9885-04c98bc7b69f@googlegroups.com> Message-ID: On Wed, Oct 8, 2014 at 12:51 PM, wrote: > Sorry, is anyone else having trouble opening the README.txt? > > On Monday, January 14, 2008 6:00:52 PM UTC-5, eef... at gmail.com wrote: >> I'd like to inform the Python community that the powerful and popular >> Template Toolkit system, previously available only in its original >> Perl implementation, is now also available in a beta Python >> implementation: >> >> http://tt2.org/python/index.html >> >> I created this port both as a fun programming project, and for use in >> environments where Perl is not available, for reasons technical, >> cultural, or otherwise. The extensive Perl test suites have also been >> ported, and most templates require no or very little modification. >> >> Discussion of the Python implementation should be conducted on the >> main Template Toolkit developer mailing list; see the site above for >> details. You're top-posting from Google Groups in response to a six-year-old post. At least you provided us with some context. But you're looking at something pretty ancient, so a more appropriate response would be to first search the web to see if the URL's changed, and if you're still having trouble, to ask (as a brand new thread) something like "I found this from six years ago, does anyone know if it's still active?". We here on comp.lang.python / python-list don't have the power to help you; you need the original author, whose contact details can probably be found by poking around on the web site you quoted the link to. ChrisA From torriem at gmail.com Tue Oct 7 23:55:32 2014 From: torriem at gmail.com (Michael Torrie) Date: Tue, 07 Oct 2014 21:55:32 -0600 Subject: Python 3.4.1 on W2K? In-Reply-To: <1412714003.2849393.176297141.1B143056@webmail.messagingengine.com> References: <1412553844.20683.YahooMailNeo@web181605.mail.ne1.yahoo.com> <54344CBB.70207@gmail.com> <1412714003.2849393.176297141.1B143056@webmail.messagingengine.com> Message-ID: <5434B5B4.5000806@gmail.com> On 10/07/2014 02:33 PM, random832 at fastmail.us wrote: > On Tue, Oct 7, 2014, at 16:27, Michael Torrie wrote: >> That's really interesting. I looked briefly at the page. How does your >> python extension work with xywrite? Does it manipulate xywrite >> documents or does it tie in at runtime with Xywrite somehow? If so, how >> does it do this? Crossing the divide into a 16-bit app is pretty >> impressive. > > I assume that it uses temporary files (or pipes, don't know if DOS can > do this), and that DOS programs can execute windows programs with int > 21/4B. dosemu has the ability to execute linux shell commands, I know. Dosbox does not, unfortunately. It be nice to have such a facility. Then xywrite fans could have xywrite on any platform, not just windows. I suppose one could hack together a way of doing it via the dosbox IPX networking facilities. From bjlockie at lockie.ca Wed Oct 8 00:25:54 2014 From: bjlockie at lockie.ca (James Smith) Date: Tue, 7 Oct 2014 21:25:54 -0700 (PDT) Subject: help with regex Message-ID: I want the last "1" I can't this to work: >>> pattern=re.compile( "(\d+)$" ) >>> match=pattern.match( "LINE: 235 : Primary Shelf Number (attempt 1): 1") >>> print match.group() From tjreedy at udel.edu Wed Oct 8 02:28:57 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 08 Oct 2014 02:28:57 -0400 Subject: operator module functions In-Reply-To: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/7/2014 9:41 PM, Steven D'Aprano wrote: > Every Python operator has a function version in the operator module: > > operator + has function operator.add; > operator - has function operator.sub; > operator * has function operator.mul; > > and so forth. Only, that's not quite right... according to the > documentation, the "official" functions are actually: > > operator.__add__; > operator.__sub__; > operator.__mul__; > > etc., with the underscore-less versions being provided as a convenience. > > Was anyone aware of this? Of course. It has bugged me a bit for years. Messy. > Is there anyone who uses or prefers the dunder versions? I don't and don't, and that seems to be true of other core devs: there are no non-test uses of the dunder methods in the stdlib. Grepping /lib/*.py recursively for 'operator.' gives 540 hits, most for operator.someop. Grepping the same for 'operator.__' returns 4 hits for operator.__name__ and .__doc__ (not operators) and these 6 tests: C:\Programs\Python34\Lib\test\test_richcmp.py: 88: "lt": (lambda a,b: a< b, operator.lt, operator.__lt__), C:\Programs\Python34\Lib\test\test_richcmp.py: 89: "le": (lambda a,b: a<=b, operator.le, operator.__le__), C:\Programs\Python34\Lib\test\test_richcmp.py: 90: "eq": (lambda a,b: a==b, operator.eq, operator.__eq__), C:\Programs\Python34\Lib\test\test_richcmp.py: 91: "ne": (lambda a,b: a!=b, operator.ne, operator.__ne__), C:\Programs\Python34\Lib\test\test_richcmp.py: 92: "gt": (lambda a,b: a> b, operator.gt, operator.__gt__), C:\Programs\Python34\Lib\test\test_richcmp.py: 93: "ge": (lambda a,b: a>=b, operator.ge, operator.__ge_ If there a back-compatibility excuse? I cannot remember what operator had in 1.4 or whenever it was added, if after that. -- Terry Jan Reedy From __peter__ at web.de Wed Oct 8 02:38:10 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 08 Oct 2014 08:38:10 +0200 Subject: help with regex References: Message-ID: James Smith wrote: > I want the last "1" > I can't this to work: > >>>> pattern=re.compile( "(\d+)$" ) >>>> match=pattern.match( "LINE: 235 : Primary Shelf Number (attempt 1): 1") >>>> print match.group() >>> pattern = re.compile("(\d+)$") >>> match = pattern.search( "LINE: 235 : Primary Shelf Number (attempt 1): 1") >>> match.group() '1' See From ben+python at benfinney.id.au Wed Oct 8 03:42:43 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 08 Oct 2014 18:42:43 +1100 Subject: help with regex References: Message-ID: <85oatnt3bg.fsf@benfinney.id.au> Peter Otten <__peter__ at web.de> writes: > >>> pattern = re.compile("(\d+)$") > >>> match = pattern.search( "LINE: 235 : Primary Shelf Number (attempt 1): 1") > >>> match.group() > '1' An alternative way to accomplish the above using the ?match? method:: >>> import re >>> pattern = re.compile("^.*:(? *)(\d+)$") >>> match = pattern.match("LINE: 235 : Primary Shelf Number (attempt 1): 1") >>> match.groups() ('1',) > See Right. Always refer to the API documentation for the API you're attempting to use. -- \ ?Without cultural sanction, most or all of our religious | `\ beliefs and rituals would fall into the domain of mental | _o__) disturbance.? ?John F. Schumaker | Ben Finney From marco.nawijn at colosso.nl Wed Oct 8 04:46:02 2014 From: marco.nawijn at colosso.nl (marco.nawijn at colosso.nl) Date: Wed, 8 Oct 2014 01:46:02 -0700 (PDT) Subject: operator module functions In-Reply-To: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> Message-ID: For me it makes sense. operator.add should be used in a "global" context (I don't know how to express it otherwise). So you provide it with the two values that you want to add. The .__add__ variants are bound to a particular instance and you provide it with a single value that you want to add. You also need the dunder versions when you want to implement addition for user defined types. So although they are similar, I do believe they have slightly different uses. As an example, you cannot use the dunder versions for literals. >> 2.__add__(3) # Oops, does not work >> a = 2 >> a.__add__(3) 5 >> import operator >> operator.add(2,3) # Fine I also think operator.add versus .__add__ is equivalent to the global getattr() and .__getattr__. Marco From jonathan.slenders at gmail.com Wed Oct 8 04:48:26 2014 From: jonathan.slenders at gmail.com (jonathan.slenders at gmail.com) Date: Wed, 8 Oct 2014 01:48:26 -0700 (PDT) Subject: How do I check if a string is a prefix of any possible other string that matches a given regex. In-Reply-To: References: <8c47cee0-7fec-4fb7-b32a-ddac6fd7c247@googlegroups.com> Message-ID: Le mercredi 8 octobre 2014 01:40:11 UTC+2, MRAB a ?crit?: > If you're not interested in generating an actual regex, but only in > > matching the prefix, then it sounds like you want "partial matching". > > > > The regex module supports that: > > > > https://pypi.python.org/pypi/regex Wow, thanks a lot! That really helps me. From larry at hastings.org Wed Oct 8 04:57:53 2014 From: larry at hastings.org (Larry Hastings) Date: Wed, 08 Oct 2014 01:57:53 -0700 Subject: [RELEASE] Python 3.4.2 is now available Message-ID: <5434FC91.9070306@hastings.org> On behalf of the Python development community and the Python 3.4 release team, I'm pleased to announce the availability of Python 3.4.2. Python 3.4.2 has many bugfixes and other small improvements over 3.4.1. One new feature for Mac OS X users: the OS X installers are now distributed as signed installer package files compatible with the OS X Gatekeeper security feature. You can download it here: https://www.python.org/download/releases/3.4.2 May the road rise up to meet you, //arry/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Wed Oct 8 05:32:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 8 Oct 2014 20:32:11 +1100 Subject: operator module functions In-Reply-To: References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> Message-ID: (You didn't include any context in your post. Please quote as much text as would be helpful; it's the easiest way to show what you're talking about.) On Wed, Oct 8, 2014 at 7:46 PM, wrote: > For me it makes sense. operator.add should be used in a "global" context > (I don't know how to express it otherwise). So you provide it with the > two values that you want to add. The .__add__ variants are bound to a > particular instance and you provide it with a single value that you want > to add. What Steven's talking about is this: >>> operator.add is operator.__add__ True It's the exact same function, just accessed with a different name. > As an example, you cannot use the dunder versions for literals. > >>> 2.__add__(3) # Oops, does not work >>> a = 2 >>> a.__add__(3) > 5 That's actually just a syntactic issue with integers and the dot. It works fine if you use any other form of literal, or if you put a space between the digits and the dot, or use parentheses, or anything; this is the case with all methods off integers, not just dunder ones. >>> 2 .__add__(3) 5 >>> (2).__add__(3) 5 >>> 2.0.__add__(3.0) 5.0 The object is exactly the same whether you reference the literal '2' or the name 'a' that you've bound to it, so its methods must by definition all be there. ChrisA From palacreide-general at yahoo.com Wed Oct 8 00:22:57 2014 From: palacreide-general at yahoo.com (Pal Acreide) Date: Tue, 7 Oct 2014 21:22:57 -0700 Subject: Python 3.4.1 on W2K? Message-ID: <1412742177.68484.YahooMailNeo@web181602.mail.ne1.yahoo.com> random832 wrote on Tue Oct 7 22:33:23 CEST 2014 >On Tue, Oct 7, 2014, at 16:27, Michael Torrie wrote: >>That's really interesting. I looked briefly at the page. How does your >>python extension work with xywrite? Does it manipulate xywrite >>documents or does it tie in at runtime with Xywrite somehow? If so, how >>does it do this? Crossing the divide into a 16-bit app is pretty >>impressive. > I assume that it uses temporary files (or pipes, don't know if DOS can > do this), and that DOS programs can execute windows programs with int > 21/4B. Yup, files. In other words, rubber bands and chewing gum, but it works nicely. Here's a short screen video of an "XPyL" routine that compiles a sorted list of all unique words in a text file and reports average word length. Subject file is the Gutenberg e-file of Moby-Dick, a 1.2MB text file. It's fast. http://youtu.be/88isdo-Cch4 BTW, this is Python 3.2.5 running on W2K in VirtualBox. Pal A. -------------- next part -------------- An HTML attachment was scrubbed... URL: From palacreide-general at yahoo.com Wed Oct 8 00:47:28 2014 From: palacreide-general at yahoo.com (Pal Acreide) Date: Tue, 7 Oct 2014 21:47:28 -0700 Subject: Python 3.4.1 on W2K Message-ID: <1412743648.366.YahooMailNeo@web181604.mail.ne1.yahoo.com> Here's another quick one -- under 30 secs. -- and then I'll revert to lurker status. It's one of my favorites: "Veritas" wine & liquor search. (Teetotalers, avert your eyes.) http://youtu.be/jDtm4z7kqyI Pal A. From flebber.crue at gmail.com Wed Oct 8 06:12:15 2014 From: flebber.crue at gmail.com (flebber) Date: Wed, 8 Oct 2014 03:12:15 -0700 (PDT) Subject: ruby instance variable in python In-Reply-To: <54349433$0$13001$c3e8da3$5496439d@news.astraweb.com> References: <48972e63-c980-4025-a624-cda0b60367de@googlegroups.com> <54349433$0$13001$c3e8da3$5496439d@news.astraweb.com> Message-ID: <54c71633-8657-460e-9bf3-d20350e77a2e@googlegroups.com> The end result of a confusing sentence with no > > context is that I have no idea what you are trying to say. Could you try > > explaining again please? > > > Steven No problem my reply from phone at work a little confusing. So trying to determine what this does. def ins_var @ins_var ||= nil end In particular I was guessing at this. @ins_var ||= nil Which I have now found on Rubyinside http://www.rubyinside.com/21-ruby-tricks-902.html >From there 7 - Cut down on local variable definitions Instead of defining a local variable with some initial content (often just an empty hash or array), you can instead define it "on the go" so you can perform operations on it at the same time: (z ||= []) << 'test' 2009 Update: This is pretty rancid, to be honest. I've changed my mind; you shouldn't be doing this :) So now that I know this I am still further lost to the point of the initially posted code so my kubuntu has ruby so I have run it, and honestly I need further definition on what that code was trying to acheive. sayth at sayth-TravelMate-5740G:~/scripts$ ruby --version ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux] sayth at sayth-TravelMate-5740G:~/scripts$ irb irb(main):001:0> (z ||= []) << 'test' => ["test"] irb(main):002:0> @ins_var ||= nil => nil irb(main):003:0> def ins_var irb(main):004:1> @ins_var ||= nil irb(main):005:1> end => nil irb(main):006:0> def m irb(main):007:1> @ins_var = "val" irb(main):008:1> end => nil irb(main):009:0> def m2 irb(main):010:1> ins_var #=> "val" irb(main):011:1> end => nil irb(main):012:0> m => "val" irb(main):013:0> m2 => "val" Sayth From gelonida at gmail.com Wed Oct 8 06:48:23 2014 From: gelonida at gmail.com (Gelonida N) Date: Wed, 08 Oct 2014 12:48:23 +0200 Subject: Pythonic way to iterate through multidimensional space? In-Reply-To: References: <20140806063923.750b81d6@bigbox.christie.dr> Message-ID: On 10/7/2014 1:01 PM, Ned Batchelder wrote: > On 10/7/14 2:10 AM, Gelonida N wrote: >> >> Disadvantage of itertools.product() is, that it makes a copy in memory. >> Reason ist, that itertools also makes products of generators (meaning of >> objects, that one can't iterate several times through) >> >> >> There are two use cases, that I occasionaly stumble over: >> >> One is making the product over lists(), >> product( list_of_lists ) >> >> ex: >> >> product( [ [1,2,3], ['A','B'], ['a', 'b', 'c'] ] ) >> >> the other one making a product over a list of functions, which will >> create generators >> >> ex: >> product( [ lambda: [ 'A', 'B' ], lambda: xrange(3) ] ) >> >> >> I personally would also be interested in a fast generic solution that >> can iterate through an N-dimensional array and which does not duplicate >> the memory or iterate through a list of generator-factories or however >> this would be called. > > itertools.product makes a copy of the sequences passed in, but it is a > shallow copy. It doesn't copy the objects in the sequences. It also > doesn't store the entire product. > > If you are calling product(j, k, l, m, n), where len(j)==J, the extra > memory is J+K+L+M+N, which is much smaller than the number of iterations > product will produce. Are you sure that much extra memory use is a > problem? How large are your lists that you are product'ing together? > Thanks for the clarification. You are right. Consumption of a shallow copy of each iterator, should not be a problem in the cases that I encountered so far. > I don't understand your point about a list of functions that create > generators? What is the problem there? > The idea was to even avoid the creation of a shallow copy, by having a function, that will return the same generator over and over again (thus no need for shallow copy) From gelonida at gmail.com Wed Oct 8 06:53:41 2014 From: gelonida at gmail.com (Gelonida N) Date: Wed, 08 Oct 2014 12:53:41 +0200 Subject: how to add custom importer after the normal imports Message-ID: Hi, I just read about sys.meta_path, which allows to install custom importers *BEFORE* the default importers. However I have a use case where I would like to add a custom importer *AFTER* all other import methods have failed. Does anybody know how to do this. One way of implementing this would be to add the default importer as first entry in sys.meta_path. My only problem is, that I don't know how to create a 'default-importer', such that I can add it into sys.meta_path Thanks in advance for any suggestions From steve+comp.lang.python at pearwood.info Wed Oct 8 06:57:40 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 08 Oct 2014 21:57:40 +1100 Subject: operator module functions References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> Message-ID: <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> marco.nawijn at colosso.nl wrote: > For me it makes sense. operator.add should be used in a "global" context > (I don't know how to express it otherwise). So you provide it with the > two values that you want to add. The .__add__ variants are bound to a > particular instance and you provide it with a single value that you want > to add. That's not correct. You're misunderstanding me, I'm not talking about the special "dunder" methods on classes, e.g. (2).__add__(3) -> 5. I'm talking about *functions* in the operator module: py> import operator py> operator.add(2, 3) 5 py> operator.__add__(2, 3) 5 According to the documentation, operator.__add__ is the "official" function, and operator.add is just there for convenience. Neither of them is the special method __add__. But it seems that nobody uses the official operator.__add__ function, and Terry Reedy says there are no tests for it. -- Steven From invalid at invalid.invalid Wed Oct 8 10:11:42 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 8 Oct 2014 14:11:42 +0000 (UTC) Subject: Another time question References: Message-ID: On 2014-10-07, Seymore4Head wrote: > I never really cared enough to ask anyone, but something like my cable > bill is 98$ a month. Do companies (in general) consider a month every > 30 days or every time the 14th comes around? Either/both. My pre-pay T-Mobile account is every $30 every 30 days, but they call it "$30 a month". The T-Mobile post-pay contracts were per calendar month, and the payment was due on the same date every month. -- Grant Edwards grant.b.edwards Yow! Can you MAIL a BEAN at CAKE? gmail.com From rustompmody at gmail.com Wed Oct 8 12:14:28 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 8 Oct 2014 09:14:28 -0700 (PDT) Subject: Practice question In-Reply-To: <5433004e$0$2916$c3e8da3$76491128@news.astraweb.com> References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> <5433004e$0$2916$c3e8da3$76491128@news.astraweb.com> Message-ID: On Tuesday, October 7, 2014 2:19:39 AM UTC+5:30, Steven D'Aprano wrote: > I have fewer issues with your conclusion and analogy than I do with the > basic premise that there is a connection between Seymore's problem here > and the use, or non-use, of print in the interactive interpreter. I don't > see how replacing interactive use and/or the use of print with functions > containing return statements would help Seymore. The issue is not only that print is bad but that the interpreter is good for learning and trying out. Are these two really unconnected. Lets see... One can - use print without the interpreter - use the interpreter without print - use both But can one use neither? [Assuming telepathy/ESP etc is disallowed] So pushing beginners away from print can push them up the learning curve more quickly From rosuav at gmail.com Wed Oct 8 12:23:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 9 Oct 2014 03:23:24 +1100 Subject: Practice question In-Reply-To: References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> <5433004e$0$2916$c3e8da3$76491128@news.astraweb.com> Message-ID: On Thu, Oct 9, 2014 at 3:14 AM, Rustom Mody wrote: > The issue is not only that print is bad but that the interpreter is > good for learning and trying out. > > Are these two really unconnected. Lets see... One can > > - use print without the interpreter > - use the interpreter without print > - use both > > But can one use neither? [Assuming telepathy/ESP etc is disallowed] > > So pushing beginners away from print can push them up the learning > curve more quickly (Please be more clear with your terminology; running Python scripts is still using the interpreter, it's just not using *interactive* Python. What you're saying above is all about Python's interactive mode.) Your conclusion doesn't obviously follow from your preceding statements. How does pushing people away from print push them up? Which way is "up"? Is it "up" to move from interactive Python to scripts run from the command line? Or is that down? How does the avoidance of print push anyone anywhere, anyway? ChrisA From skip.montanaro at gmail.com Wed Oct 8 12:27:16 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Wed, 8 Oct 2014 11:27:16 -0500 Subject: Practice question In-Reply-To: References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> <5433004e$0$2916$c3e8da3$76491128@news.astraweb.com> Message-ID: On Wed, Oct 8, 2014 at 11:14 AM, Rustom Mody wrote: > So pushing beginners away from print can push them up the learning > curve more quickly Or more quickly discourage them. I still use print for all sorts of things. In my opinion, there is often no need for fancy loggers, str.format, or the write method of file-like objects. Print will often get you a "good enough" result faster than the other means. Skip From rustompmody at gmail.com Wed Oct 8 12:41:36 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 8 Oct 2014 09:41:36 -0700 (PDT) Subject: Practice question In-Reply-To: References: <9e674b54-92e8-469b-ba68-da593fc8564a@googlegroups.com> <5433004e$0$2916$c3e8da3$76491128@news.astraweb.com> Message-ID: On Wednesday, October 8, 2014 9:58:11 PM UTC+5:30, Skip Montanaro wrote: > On Wed, Oct 8, 2014 at 11:14 AM, Rustom Mody wrote: > > So pushing beginners away from print can push them up the learning > > curve more quickly > Or more quickly discourage them. I still use print for all sorts of > things. In my opinion, there is often no need for fancy loggers, > str.format, or the write method of file-like objects. Print will often > get you a "good enough" result faster than the other means. Well I'm not talking of people like you!! Nor of more sophisticated tools than print. I am talking of the fact that an absolute basic sine qua non for beginners is to be able to structure programs: - breaking up a complex expression into sub-expressions - abstracting out a sub-expression into a function with an appropriate parameterization - inverses of the above when the current cut is sub-optimal etc etc... what is nowadays fashionably called 'refactoring' And for that the noob needs to learn to write return-ing function where he currently writes a print-ing function. From bryanjugglercryptographer at yahoo.com Wed Oct 8 13:28:39 2014 From: bryanjugglercryptographer at yahoo.com (bryanjugglercryptographer at yahoo.com) Date: Wed, 8 Oct 2014 10:28:39 -0700 (PDT) Subject: "High water" Memory fragmentation still a thing? In-Reply-To: References: <7ac186c3-2dbc-4cfa-ab58-37854aeb59d1@googlegroups.com> Message-ID: Chris Angelico wrote: > Sure, and that's all well and good. But what I just cited there *is* a > shipping product. That's a live server that runs a game that I'm admin > of. So it's possible to do without the resource safety net of periodic > restarts. Nice that the non-Python server you administer stayed up for 88 weeks, but that doesn't really have anything to do with the issue here. The answer to the OP's title question is "yes", high-water memory fragmentation is a real thing, in most platforms including CPython. The cited article tells of Celery hitting the problem, and the working solution was to "roll the celery worker processes". That doesn't mean to tell a human administrator to regularly restart the server. It's programmatic and it's a reasonably simple and well-established design pattern. > > For an example see the Apache HTTP daemon, particularly the classic pre-forking server. There's a configuration parameter, "MaxRequestsPerChild", that sets how many requests a process should answer before terminating. > > That assumes that requests can be handled equally by any server > process - and more so, that there are such things as discrete > requests. That's true of HTTP, but not of everything. It's true of HTTP and many other protocols because they were designed to support robust operation even as individual components may fail. > And even with > HTTP, if you do "long polls" [1] then clients might remain connected > for arbitrary lengths of time; either you have to cut them off when > you terminate the server process (hopefully that isn't too often, or > you lose the benefit of long polling), or you retain processes for > much longer. If you look at actual long-polling protocols, you'll see that the server occasionally closing connections is no problem at all. They're actually designed to be robust even against connections that drop without proper shutdown. > Restarting isn't necessary. It's like rebooting a computer: people get > into the habit of doing it, because it "fixes problems", but all that > means is that it allows you to get sloppy with resource management. CPython, and for that matter malloc/free, have known problems in resource management, such as the fragmentation issue noted here. There are more. Try a Google site search for "memory leak" on http://bugs.python.org/. Do you think the last memory leak is fixed now? >From what I've seen, planned process replacement is the primary techniques to support long-lived mission-critical services in face of resource management flaws. Upon process termination the OS recovers the resources. I love CPython, but on this point I trust the Linux kernel much more. -- --Bryan From tjreedy at udel.edu Wed Oct 8 15:09:59 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 08 Oct 2014 15:09:59 -0400 Subject: operator module functions In-Reply-To: <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/8/2014 6:57 AM, Steven D'Aprano wrote: > According to the documentation, operator.__add__ is the "official" function, > and operator.add is just there for convenience. You are paraphrasing "The function names are those used for special class methods; variants without leading and trailing __ are also provided for convenience." But then there is the following: 10.3.1. Mapping Operators to Functions This table shows how abstract operations correspond to operator symbols in the Python syntax and the functions in the operator module. Operation Syntax Function Addition a + b add(a, b) etc, using the 'convenient' names. I would like to deprecate and eventually remove the dunder names. To me, the duplication is not 'convenient'. -- Terry Jan Reedy From george.trojan at noaa.gov Wed Oct 8 12:29:17 2014 From: george.trojan at noaa.gov (George Trojan) Date: Wed, 08 Oct 2014 16:29:17 +0000 Subject: strange numpy behaviour Message-ID: <5435665D.5010902@noaa.gov> This does not look right: dilbert at gtrojan> python3.4 Python 3.4.1 (default, Jul 7 2014, 15:47:25) [GCC 4.8.3 20140624 (Red Hat 4.8.3-1)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import numpy as np >>> a=np.ma.array([0, 1], dtype=np.int8, mask=[1, 0]) >>> a masked_array(data = [-- 1], mask = [ True False], fill_value = 999999) >>> a.data array([0, 1], dtype=int8) >>> a.filled() array([63, 1], dtype=int8) <------- Why 63? >>> What do you think? George From ian.g.kelly at gmail.com Wed Oct 8 15:19:32 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 8 Oct 2014 13:19:32 -0600 Subject: strange numpy behaviour In-Reply-To: <5435665D.5010902@noaa.gov> References: <5435665D.5010902@noaa.gov> Message-ID: On Wed, Oct 8, 2014 at 10:29 AM, George Trojan wrote: > This does not look right: > > dilbert at gtrojan> python3.4 > Python 3.4.1 (default, Jul 7 2014, 15:47:25) > [GCC 4.8.3 20140624 (Red Hat 4.8.3-1)] on linux > Type "help", "copyright", "credits" or "license" for more information. >>>> import numpy as np >>>> a=np.ma.array([0, 1], dtype=np.int8, mask=[1, 0]) >>>> a > masked_array(data = [-- 1], > mask = [ True False], > fill_value = 999999) > >>>> a.data > array([0, 1], dtype=int8) >>>> a.filled() > array([63, 1], dtype=int8) <------- Why 63? >>>> > > What do you think? The datatype is int8, the fill value is the default of 999999, and 999999 & 0xff == 63. From ethan at stoneleaf.us Wed Oct 8 15:38:22 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 08 Oct 2014 12:38:22 -0700 Subject: operator module functions In-Reply-To: References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> Message-ID: <543592AE.80807@stoneleaf.us> On 10/08/2014 12:09 PM, Terry Reedy wrote: > On 10/8/2014 6:57 AM, Steven D'Aprano wrote: > >> According to the documentation, operator.__add__ is the "official" function, >> and operator.add is just there for convenience. > > You are paraphrasing "The function names are those used for special class methods; variants without leading and trailing > __ are also provided for convenience." But then there is the following: > > 10.3.1. Mapping Operators to Functions > > This table shows how abstract operations correspond to operator symbols in the Python syntax and the functions in the > operator module. > Operation Syntax Function > Addition a + b add(a, b) > > etc, using the 'convenient' names. I would like to deprecate and eventually remove the dunder names. To me, the > duplication is not 'convenient'. LOL, no kidding! The main reason I bother using the operator module is for the readability of not seeing the dunders, and the writability of not having to type them. -- ~Ethan~ From random832 at fastmail.us Wed Oct 8 15:49:24 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Wed, 08 Oct 2014 15:49:24 -0400 Subject: operator module functions In-Reply-To: <543592AE.80807@stoneleaf.us> References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> <543592AE.80807@stoneleaf.us> Message-ID: <1412797764.3704154.176743089.32D63D13@webmail.messagingengine.com> On Wed, Oct 8, 2014, at 15:38, Ethan Furman wrote: > LOL, no kidding! The main reason I bother using the operator module is > for the readability of not seeing the dunders, > and the writability of not having to type them. I'm not sure what situation you would have to type them (as opposed to simply a + b) that the operator module would help with. From gelonida at gmail.com Wed Oct 8 17:05:08 2014 From: gelonida at gmail.com (Gelonida N) Date: Wed, 08 Oct 2014 23:05:08 +0200 Subject: operator module functions In-Reply-To: References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/8/2014 9:09 PM, Terry Reedy wrote: > On 10/8/2014 6:57 AM, Steven D'Aprano wrote: > >> According to the documentation, operator.__add__ is the "official" >> function, >> and operator.add is just there for convenience. > > You are paraphrasing "The function names are those used for special > class methods; variants without leading and trailing __ are also > provided for convenience." But then there is the following: > > 10.3.1. Mapping Operators to Functions > > This table shows how abstract operations correspond to operator symbols > in the Python syntax and the functions in the operator module. > Operation Syntax Function > Addition a + b add(a, b) > > etc, using the 'convenient' names. I would like to deprecate and > eventually remove the dunder names. To me, the duplication is not > 'convenient'. > I'd be curious about a proposal to obsolete the double underscore functions and just keep operator.add or to just keep the operator + For me they seem rather distinct, though they are interchangable in certain situations. Perhaps I got something wrong, but all dunder functions are 'magic' functions. Many of them mostly should ne used when when overloading behaviour or when creating a class which should implement operators. So for implemetation you use __add__ for using you use the operator + if you need a class MyClass(object): def __init__(self, x, y): self.x = x self.y = y # implements + for a certain type def __add__(self, other): return MyClass(self.x + other.x, self.y + other.y) def __repr__(self): return "(%f,%f)" % (self.x, self.y) a = MyClass(1,2) b = MyClass(4,5) print(a) print(b) print(a+b) # operator.add is identical to the + operator , # BUT it is a function and can thuss be # assigned to variables passed as parameter def dosomething(op, val1, val2): return op(val1, val2) print(dosomething(operator.add, 1, 2)) print(dosomething(operator.add, a, b)) From ian.g.kelly at gmail.com Wed Oct 8 17:23:18 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 8 Oct 2014 15:23:18 -0600 Subject: operator module functions In-Reply-To: References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Oct 8, 2014 at 3:05 PM, Gelonida N wrote: > On 10/8/2014 9:09 PM, Terry Reedy wrote: >> >> On 10/8/2014 6:57 AM, Steven D'Aprano wrote: >> >>> According to the documentation, operator.__add__ is the "official" >>> function, >>> and operator.add is just there for convenience. >> >> >> You are paraphrasing "The function names are those used for special >> class methods; variants without leading and trailing __ are also >> provided for convenience." But then there is the following: >> >> 10.3.1. Mapping Operators to Functions >> >> This table shows how abstract operations correspond to operator symbols >> in the Python syntax and the functions in the operator module. >> Operation Syntax Function >> Addition a + b add(a, b) >> >> etc, using the 'convenient' names. I would like to deprecate and >> eventually remove the dunder names. To me, the duplication is not >> 'convenient'. >> > > > I'd be curious about a proposal to obsolete the double underscore functions > and just keep operator.add or to just keep the operator + > > For me they seem rather distinct, though they are interchangable in certain > situations. > > Perhaps I got something wrong, but all dunder functions are 'magic' > functions. Many of them mostly should ne used when when overloading > behaviour or when creating a class which should implement operators. This isn't about the dunder *method* names. It's about the naming of the functions in the operator module, e.g. having both operator.add and operator.__add__ that are two names for the same function. From greg.ewing at canterbury.ac.nz Wed Oct 8 17:24:50 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 09 Oct 2014 10:24:50 +1300 Subject: How do I check if a string is a prefix of any possible other string that matches a given regex. In-Reply-To: <8c47cee0-7fec-4fb7-b32a-ddac6fd7c247@googlegroups.com> References: <8c47cee0-7fec-4fb7-b32a-ddac6fd7c247@googlegroups.com> Message-ID: jonathan.slenders at gmail.com wrote: >>For each non-accepting state, determine whether it has >>any transitions that lead in one or more steps to an accepting state. >>Modify the FSM so that each such state is also an accepting state. > Thanks, I'll make every state of the FSM an accepting state. Not *every* state -- that will give you an FSM that accepts any string! -- Greg From greg.ewing at canterbury.ac.nz Wed Oct 8 17:37:24 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 09 Oct 2014 10:37:24 +1300 Subject: operator module functions In-Reply-To: References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> Message-ID: Chris Angelico wrote: >>>>operator.add is operator.__add__ > True That doesn't always seem to have been the case, however. In Python 2.7 and 3.3, I get >>> operator.add is operator.__add__ False -- Greg From ethan at stoneleaf.us Wed Oct 8 17:49:00 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 08 Oct 2014 14:49:00 -0700 Subject: operator module functions In-Reply-To: <1412803417.3733140.176776081.0B98584A@webmail.messagingengine.com> References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> <543592AE.80807@stoneleaf.us> <1412797764.3704154.176743089.32D63D13@webmail.messagingengine.com> <54359623.8060307@stoneleaf.us> <1412803417.3733140.176776081.0B98584A@webmail.messagingengine.com> Message-ID: <5435B14C.9020907@stoneleaf.us> [redirecting back to the list] On 10/08/2014 02:23 PM, random832 at fastmail.us wrote: > On Wed, Oct 8, 2014, at 15:53, Ethan Furman wrote: >> On 10/08/2014 12:49 PM, random832 at fastmail.us wrote: >>> On Wed, Oct 8, 2014, at 15:38, Ethan Furman wrote: >>>> >>>> LOL, no kidding! The main reason I bother using the operator module is >>>> for the readability of not seeing the dunders, >>>> and the writability of not having to type them. >>> >>> I'm not sure what situation you would have to type them (as opposed to >>> simply a + b) that the operator module would help with. >> >> unittest springs to mind: >> >> self.assertRaises(TypeError, op.add, obj1, obj2) > > Er, my point is, that is not a situation where you would be able to use > obj1.__add__ - you'd have to use the operator module *anyway*, and > therefore aren't using it just to get the convenience of a non-dunder > name. self.assertRaises(TypeError, lambda x, y: x+y, obj1, obj2) -- ~Ethan~ From ckaynor at zindagigames.com Wed Oct 8 17:21:25 2014 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Wed, 8 Oct 2014 14:21:25 -0700 Subject: operator module functions In-Reply-To: References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Oct 8, 2014 at 2:05 PM, Gelonida N wrote: > On 10/8/2014 9:09 PM, Terry Reedy wrote: > >> On 10/8/2014 6:57 AM, Steven D'Aprano wrote: >> >> According to the documentation, operator.__add__ is the "official" >>> function, >>> and operator.add is just there for convenience. >>> >> >> You are paraphrasing "The function names are those used for special >> class methods; variants without leading and trailing __ are also >> provided for convenience." But then there is the following: >> >> 10.3.1. Mapping Operators to Functions >> >> This table shows how abstract operations correspond to operator symbols >> in the Python syntax and the functions in the operator module. >> Operation Syntax Function >> Addition a + b add(a, b) >> >> etc, using the 'convenient' names. I would like to deprecate and >> eventually remove the dunder names. To me, the duplication is not >> 'convenient'. >> >> > > I'd be curious about a proposal to obsolete the double underscore > functions and just keep operator.add or to just keep the operator + > > For me they seem rather distinct, though they are interchangable in > certain situations. > > Perhaps I got something wrong, but all dunder functions are 'magic' > functions. Many of them mostly should ne used when when overloading > behaviour or when creating a class which should implement operators. > > print(dosomething(operator.add, 1, 2)) > print(dosomething(operator.add, a, b)) The thing being purposed to remove, is that you can also do: print(dosomething(operator.__add__, 1, 2)) print(dosomething(operator.__add__, a, b)) Not that fact that you can define __add__ in the class, or that "operator.add(a, b)" is the same as "a + b" (all of which are quite useful). Basically, the operator module has a "__add__" function in addition to a "add" function, and they are both identical (in fact, they are the same function object): >>> import operator >>> operator.add >>> operator.__add__ >>> operator.__add__ is operator.add True -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Wed Oct 8 17:57:15 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 09 Oct 2014 08:57:15 +1100 Subject: operator module functions References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> <543592AE.80807@stoneleaf.us> <1412797764.3704154.176743089.32D63D13@webmail.messagingengine.com> Message-ID: <85k34atebo.fsf@benfinney.id.au> random832 at fastmail.us writes: > On Wed, Oct 8, 2014, at 15:38, Ethan Furman wrote: > > The main reason I bother using the operator module is for the > > readability of not seeing the dunders, and the writability of not > > having to type them. > > I'm not sure what situation you would have to type them (as opposed to > simply a + b) that the operator module would help with. Any situation where you need to refer to a function. ?+? is not a function, whereas ?operator.add? is. import operator import functools add_three = functools.partial(operator.add, 3) foo = list(range(10)) bar = map(add_three, foo) The above ?map? invocation ? which is useful because it allows any arbitrary one-parameter function to be used ? cannot be used with ?+?, which is not a function. Likewise, ?functools.partial? requires a function, and ?+? is not a function. There are countless such uses for the functions in the ?operator? module. -- \ ?It is the integrity of each individual human that is in final | `\ examination. On personal integrity hangs humanity's fate.? | _o__) ?Richard Buckminster Fuller, _Critical Path_, 1981 | Ben Finney From gelonida at gmail.com Wed Oct 8 18:09:50 2014 From: gelonida at gmail.com (Gelonida N) Date: Thu, 09 Oct 2014 00:09:50 +0200 Subject: virtualenv question: include just a few site packages Message-ID: virtualenv has the switch --system-site-packages (including all system site pacgaes) and the switch --no-site-packages (to expclude all site packages) Does anyone know an easy way to include just a few site-packages? for example (PySide, but not PyQt) The reason I'm asking is following. Some site packages are sometimes raher huge or sometimes refuse to compile on certain hosts. as these packages are already part of the site packages I'd like to include them. You might wonder why I care whether I have more site packages than I need. As long as I don't import them, I shouldn't care about it. If I really wanted to replace a version I could use pip install -U. However sometimes I'd like to have a test environment where want to be sure, that no module can find certain other modules. so they should not be visible. at the moment I make some experiments with pyinstaller and the module pythonqtbindings. and there I'd like to be sure that no PuQt files end up in the generated code. The only idea, that I have so far is to run virutalanv with --system-side-packages and to manually remove modules I don't want or to run virtualenv without this switch and to manually add links for site packages, taht I want. both options don't really feel right for me. Is there any other way? From rosuav at gmail.com Wed Oct 8 18:30:31 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 9 Oct 2014 09:30:31 +1100 Subject: operator module functions In-Reply-To: References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Oct 9, 2014 at 8:37 AM, Gregory Ewing wrote: > Chris Angelico wrote: > >>>>> operator.add is operator.__add__ >> >> True > > > That doesn't always seem to have been the case, however. > In Python 2.7 and 3.3, I get > >>>> operator.add is operator.__add__ > False Huh. So it is. rosuav at sikorsky:~$ python3 Python 3.5.0a0 (default:301b9a58021c, Oct 2 2014, 09:20:24) [GCC 4.7.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import operator >>> operator.add, operator.__add__ (, ) >>> rosuav at sikorsky:~$ python Python 2.7.3 (default, Mar 13 2014, 11:03:55) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import operator >>> operator.add, operator.__add__ (, ) >>> Presumably they have the same code behind them, just different function names. But anyway, the fact that it doesn't throw back an AttributeError proves that both functions do at least exist. Learn something new every day! ChrisA From ckaynor at zindagigames.com Wed Oct 8 18:40:18 2014 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Wed, 8 Oct 2014 15:40:18 -0700 Subject: operator module functions In-Reply-To: References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Oct 8, 2014 at 3:30 PM, Chris Angelico wrote: > > > > > > That doesn't always seem to have been the case, however. > > In Python 2.7 and 3.3, I get > > > >>>> operator.add is operator.__add__ > > False > > Huh. So it is. > > rosuav at sikorsky:~$ python3 > Python 3.5.0a0 (default:301b9a58021c, Oct 2 2014, 09:20:24) > [GCC 4.7.2] on linux > Type "help", "copyright", "credits" or "license" for more information. > >>> import operator > >>> operator.add, operator.__add__ > (, ) > >>> > rosuav at sikorsky:~$ python > Python 2.7.3 (default, Mar 13 2014, 11:03:55) > [GCC 4.7.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> import operator > >>> operator.add, operator.__add__ > (, ) > >>> > > Presumably they have the same code behind them, just different > function names. But anyway, the fact that it doesn't throw back an > AttributeError proves that both functions do at least exist. > > Learn something new every day! I only tried it in Python 3.4, and I got true. Perhaps it was optimized slightly after 3.3? Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Wed Oct 8 18:44:04 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 8 Oct 2014 16:44:04 -0600 Subject: how to add custom importer after the normal imports In-Reply-To: References: Message-ID: On Wed, Oct 8, 2014 at 4:53 AM, Gelonida N wrote: > Hi, > > > I just read about sys.meta_path, which allows to install custom importers > *BEFORE* the default importers. > > However I have a use case where I would like to add a custom importer > *AFTER* all other import methods have failed. > > Does anybody know how to do this. > > One way of implementing this would be to add the default importer as first > entry in sys.meta_path. My only problem is, that I don't know how to create > a 'default-importer', such that I can add it into sys.meta_path As of CPython 3.3 the default importers are already in sys.meta_path, so you could just add your custom importer to the end. If you need to support earlier versions or alternate implementations then this may not be reliable. From tjreedy at udel.edu Wed Oct 8 18:46:05 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 08 Oct 2014 18:46:05 -0400 Subject: operator module functions In-Reply-To: <5435B14C.9020907@stoneleaf.us> References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> <543592AE.80807@stoneleaf.us> <1412797764.3704154.176743089.32D63D13@webmail.messagingengine.com> <54359623.8060307@stoneleaf.us> <1412803417.3733140.176776081.0B98584A@webmail.messagingengine.com> <5435B14C.9020907@stoneleaf.us> Message-ID: On 10/8/2014 5:49 PM, Ethan Furman wrote: > [redirecting back to the list] >>>> I'm not sure what situation you would have to type them (as opposed to >>>> simply a + b) that the operator module would help with. >>> >>> unittest springs to mind: >>> >>> self.assertRaises(TypeError, op.add, obj1, obj2) >> >> Er, my point is, that is not a situation where you would be able to use >> obj1.__add__ - you'd have to use the operator module *anyway*, and >> therefore aren't using it just to get the convenience of a non-dunder >> name. > > self.assertRaises(TypeError, lambda x, y: x+y, obj1, obj2) That works, but is a bit harder to type (given the import), more confusing to read (the extra ',' that does *not* delimit an argument) and adds an extra layer to the call stack with each call. The extra layer *could* make a difference in recursion. -- Terry Jan Reedy From ethan at stoneleaf.us Wed Oct 8 19:35:11 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 08 Oct 2014 16:35:11 -0700 Subject: operator module functions In-Reply-To: References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> <543592AE.80807@stoneleaf.us> <1412797764.3704154.176743089.32D63D13@webmail.messagingengine.com> <54359623.8060307@stoneleaf.us> <1412803417.3733140.176776081.0B98584A@webmail.messagingengine.com> <5435B14C.9020907@stoneleaf.us> Message-ID: <5435CA2F.3010005@stoneleaf.us> On 10/08/2014 03:46 PM, Terry Reedy wrote: > On 10/8/2014 5:49 PM, Ethan Furman wrote: >> [redirecting back to the list] > >>>>> I'm not sure what situation you would have to type them (as opposed to >>>>> simply a + b) that the operator module would help with. >>>> >>>> unittest springs to mind: >>>> >>>> self.assertRaises(TypeError, op.add, obj1, obj2) >>> >>> Er, my point is, that is not a situation where you would be able to use >>> obj1.__add__ - you'd have to use the operator module *anyway*, and >>> therefore aren't using it just to get the convenience of a non-dunder >>> name. >> >> self.assertRaises(TypeError, lambda x, y: x+y, obj1, obj2) > > That works, but is a bit harder to type (given the import), more confusing to read (the extra ',' that does *not* > delimit an argument) and adds an extra layer to the call stack with each call. The extra layer *could* make a > difference in recursion. Indeed, thanks for the corrections. I was merely replying to the "have to use the operator module anyway" comment. -- ~Ethan~ From Seymore4Head at Hotmail.invalid Wed Oct 8 20:11:41 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 08 Oct 2014 20:11:41 -0400 Subject: Toggle Message-ID: I want to toggle between color="Red" and color="Blue" Here is one: if color == "Red": color = "Blue" else: color = "Red" Here is two: if x = "True" color = "Red" else: color="Blue" x= not x Others? From davea at davea.name Wed Oct 8 21:24:22 2014 From: davea at davea.name (Dave Angel) Date: Wed, 8 Oct 2014 21:24:22 -0400 (EDT) Subject: Toggle References: Message-ID: Seymore4Head Wrote in message: > I want to toggle between color="Red" and color="Blue" > Here is one: > if color == "Red": > color = "Blue" > else: > color = "Red" > Here is two: > if x = "True" color = "Red" > else: > color="Blue" > x= not x > > Others? > One looks like it wrks and two looks like nonsense. Just what are you trying to ask? -- DaveA From breamoreboy at yahoo.co.uk Wed Oct 8 21:25:46 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 09 Oct 2014 02:25:46 +0100 Subject: Toggle In-Reply-To: References: Message-ID: On 09/10/2014 01:11, Seymore4Head wrote: > I want to toggle between color="Red" and color="Blue" > Here is one: > if color == "Red": > color = "Blue" > else: > color = "Red" > Here is two: > if x = "True" color = "Red" > else: > color="Blue" > x= not x > > Others? > Here http://stackoverflow.com/questions/8381735/toggle-a-value-in-python but why couldn't you search in the first place? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve+comp.lang.python at pearwood.info Wed Oct 8 21:29:08 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 09 Oct 2014 12:29:08 +1100 Subject: Toggle References: Message-ID: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> Seymore4Head wrote: > I want to toggle between color="Red" and color="Blue" > Here is one: > if color == "Red": > color = "Blue" > else: > color = "Red" Apart from the horrible spelling of colour :-) that seems fine to me. You might wish to include a comment: # Assumes that color can only take the values "Red" or "Blue". just before the toggle code. But even better than a comment is an assertion: assert color in ("Red", "Blue") if color == "Red": color = "Blue" else: color = "Red" This makes it a "checked comment" -- the primary purpose of the assert here is as a comment, but the interpreter will by default actually check that it is true (although that can be turned off by the user). You can find out more about good, and bad, uses of assert here: http://import-that.dreamwidth.org/676.html > Here is two: > if x = "True" color = "Red" > else: > color="Blue" > x= not x That gives SyntaxError. And it's wrong because you are confusing the *string* "T r u e" with the constant True. It should be: assert isinstance(x, bool) if x: # don't write "if x == True" since that is redundant color = 'Red' else: color = 'Blue' x = not x > Others? color = ("Red", "Blue")[color == "Red"] color = {"Red": "Blue", "Blue": "Red"}[color] color = "Red" if color == "Blue" else "Blue" There may be even more complicated, obscure or obfuscated versions possible. -- Steven From ned at nedbatchelder.com Wed Oct 8 21:41:12 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Wed, 08 Oct 2014 21:41:12 -0400 Subject: operator module functions In-Reply-To: <5435B14C.9020907@stoneleaf.us> References: <54349662$0$12987$c3e8da3$5496439d@news.astraweb.com> <543518a5$0$12989$c3e8da3$5496439d@news.astraweb.com> <543592AE.80807@stoneleaf.us> <1412797764.3704154.176743089.32D63D13@webmail.messagingengine.com> <54359623.8060307@stoneleaf.us> <1412803417.3733140.176776081.0B98584A@webmail.messagingengine.com> <5435B14C.9020907@stoneleaf.us> Message-ID: On 10/8/14 5:49 PM, Ethan Furman wrote: > [redirecting back to the list] > > On 10/08/2014 02:23 PM, random832 at fastmail.us wrote: >> On Wed, Oct 8, 2014, at 15:53, Ethan Furman wrote: >>> On 10/08/2014 12:49 PM, random832 at fastmail.us wrote: >>>> On Wed, Oct 8, 2014, at 15:38, Ethan Furman wrote: >>>>> >>>>> LOL, no kidding! The main reason I bother using the operator >>>>> module is >>>>> for the readability of not seeing the dunders, >>>>> and the writability of not having to type them. >>>> >>>> I'm not sure what situation you would have to type them (as opposed to >>>> simply a + b) that the operator module would help with. >>> >>> unittest springs to mind: >>> >>> self.assertRaises(TypeError, op.add, obj1, obj2) >> >> Er, my point is, that is not a situation where you would be able to use >> obj1.__add__ - you'd have to use the operator module *anyway*, and >> therefore aren't using it just to get the convenience of a non-dunder >> name. > > self.assertRaises(TypeError, lambda x, y: x+y, obj1, obj2) Don't forget, in 2.7 you can do: with self.assertRaises(TypeError): obj1 + obj2 -- Ned Batchelder, http://nedbatchelder.com From ben+python at benfinney.id.au Wed Oct 8 21:42:14 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 09 Oct 2014 12:42:14 +1100 Subject: Toggle References: Message-ID: <857g0at3wp.fsf@benfinney.id.au> Seymore4Head writes: > I want to toggle between color="Red" and color="Blue" It's good to cultivate ongoing familiarity with the standard library so that you can make use of wheels already invented and maintained:: import itertools colours = ["Red", "Blue"] colour_cycle = itertools.cycle(colours) next(colour_cycle) # ? "Red" next(colour_cycle) # ? "Blue" next(colour_cycle) # ? "Red" next(colour_cycle) # ? "Blue" next(colour_cycle) # ? "Red" for colour in colour_cycle: # ? loops indefinitely # with ?colour? bound to each value in turn ? -- \ ?My roommate got a pet elephant. Then it got lost. It's in the | `\ apartment somewhere.? ?Steven Wright | _o__) | Ben Finney From rustompmody at gmail.com Wed Oct 8 22:34:30 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 8 Oct 2014 19:34:30 -0700 (PDT) Subject: Toggle In-Reply-To: References: Message-ID: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> On Thursday, October 9, 2014 7:12:41 AM UTC+5:30, Ben Finney wrote: > Seymore4Head writes: > > I want to toggle between color="Red" and color="Blue" > It's good to cultivate ongoing familiarity with the standard library And language. In recent python3: >>> class Color(Enum): ... Red = 0 ... Blue = 1 ... >>> Color.Red >>> print (Color.Red) Color.Red # Not sure what to make of that distinction... >>> c=Color.Red >>> c = Color.Blue if c==Color.Red else Color.Red >>> c >>> >>> # Better >>> def toggle(c): return Color.Blue if c==Color.Red else Color.Red ... >>> toggle(c) >>> toggle(c) # which means the c has not changed >>> toggle(toggle(c)) [Yeah and like Steven I find the colour of 'color' colourless] From breamoreboy at yahoo.co.uk Wed Oct 8 23:02:31 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 09 Oct 2014 04:02:31 +0100 Subject: Toggle In-Reply-To: References: Message-ID: On 09/10/2014 02:25, Mark Lawrence wrote: > On 09/10/2014 01:11, Seymore4Head wrote: >> I want to toggle between color="Red" and color="Blue" >> Here is one: >> if color == "Red": >> color = "Blue" >> else: >> color = "Red" >> Here is two: >> if x = "True" color = "Red" >> else: >> color="Blue" >> x= not x >> >> Others? >> > > Here http://stackoverflow.com/questions/8381735/toggle-a-value-in-python > but why couldn't you search in the first place? > When I first read this I was extremely jealous of the originator but having used it umpteen times I'm still extremely jealous of the originator!!! Why doesn't my mind work like his? :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From random832 at fastmail.us Wed Oct 8 23:54:06 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Wed, 08 Oct 2014 23:54:06 -0400 Subject: Toggle In-Reply-To: References: Message-ID: <1412826846.1947388.176878769.2F8374DF@webmail.messagingengine.com> On Wed, Oct 8, 2014, at 23:02, Mark Lawrence wrote: > When I first read this I was extremely jealous of the originator but > having used it umpteen times I'm still extremely jealous of the > originator!!! Why doesn't my mind work like his? :) You could also keep the ints in two variables and do a ^= b : b ^= a : a ^= b. Or use a, b = b, a. What I don't see in that answer is any benchmarking support for his sweeping assertions of what is the fastest version. From rosuav at gmail.com Wed Oct 8 23:57:23 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 9 Oct 2014 14:57:23 +1100 Subject: Toggle In-Reply-To: <1412826846.1947388.176878769.2F8374DF@webmail.messagingengine.com> References: <1412826846.1947388.176878769.2F8374DF@webmail.messagingengine.com> Message-ID: On Thu, Oct 9, 2014 at 2:54 PM, wrote: > On Wed, Oct 8, 2014, at 23:02, Mark Lawrence wrote: >> When I first read this I was extremely jealous of the originator but >> having used it umpteen times I'm still extremely jealous of the >> originator!!! Why doesn't my mind work like his? :) > > You could also keep the ints in two variables and do a ^= b : b ^= a : a > ^= b. Or use a, b = b, a. What I don't see in that answer is any > benchmarking support for his sweeping assertions of what is the fastest > version. Possibly because it doesn't matter. Who cares how fast it is? All you need to do is go from either of two states to the other. If the performance of that has any impact whatsoever on your code, there's something wrong with your design. ChrisA From steve at pearwood.info Thu Oct 9 00:56:29 2014 From: steve at pearwood.info (Steven D'Aprano) Date: 09 Oct 2014 04:56:29 GMT Subject: Toggle References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> Message-ID: <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> On Wed, 08 Oct 2014 19:34:30 -0700, Rustom Mody wrote: >>>> Color.Red > >>>> print (Color.Red) > Color.Red > > # Not sure what to make of that distinction... That's because the interactive interpreter displays the repr() of objects (except for None, which it suppresses), while print outputs the str() of them. py> class Test: ... def __repr__(self): return "repr" ... def __str__(self): return "str" ... py> x = Test() py> x repr py> print(x) str That's an old, old part of Python, going back to Python 1.5 or older, if I remember correctly. -- Steven From greg.ewing at canterbury.ac.nz Thu Oct 9 00:57:03 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 09 Oct 2014 17:57:03 +1300 Subject: Toggle In-Reply-To: References: Message-ID: Seymore4Head wrote: > I want to toggle between color="Red" and color="Blue" toggle = {"Red": "Blue", "Blue": "Red"} color = toggle[color] From travisgriggs at gmail.com Thu Oct 9 01:38:26 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Wed, 8 Oct 2014 22:38:26 -0700 Subject: Toggle In-Reply-To: References: Message-ID: On Oct 8, 2014, at 9:57 PM, Gregory Ewing wrote: > Seymore4Head wrote: >> I want to toggle between color="Red" and color="Blue" Don?t forget polymorphic dispatch? class Red(object): def toggle(self): return Blue() class Blue(object): def toggle(self): return Red() Blue().toggle().toggle().toggle().toggle().toggle() :) -- Travis Griggs Objologist "Some of them wanted to sell me snake oil and I'm not necessarily going to dismiss all of these, as I have never found a rusty snake." --Terry Pratchett From rustompmody at gmail.com Thu Oct 9 01:39:21 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 8 Oct 2014 22:39:21 -0700 (PDT) Subject: Toggle In-Reply-To: <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8dba70e4-9670-40d3-9a3f-d2b593d52ac6@googlegroups.com> On Thursday, October 9, 2014 10:26:41 AM UTC+5:30, Steven D'Aprano wrote: > On Wed, 08 Oct 2014 19:34:30 -0700, Rustom Mody wrote: > >>>> Color.Red > >>>> print (Color.Red) > > Color.Red > > # Not sure what to make of that distinction... > That's because the interactive interpreter displays the repr() of objects > (except for None, which it suppresses), while print outputs the str() of > them. Yeah... What I meant to wonder upon was: "Is this behavior what the pro-print or the anti-print folks like?" In any case that the P in REPL is not *exactly* the same as print (or equivalently the distinction between str and repr) makes for some intricate noob confusions. BTW is there some flag that can make them identical? From rosuav at gmail.com Thu Oct 9 01:55:03 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 9 Oct 2014 16:55:03 +1100 Subject: Toggle In-Reply-To: <8dba70e4-9670-40d3-9a3f-d2b593d52ac6@googlegroups.com> References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> <8dba70e4-9670-40d3-9a3f-d2b593d52ac6@googlegroups.com> Message-ID: On Thu, Oct 9, 2014 at 4:39 PM, Rustom Mody wrote: > On Thursday, October 9, 2014 10:26:41 AM UTC+5:30, Steven D'Aprano wrote: >> On Wed, 08 Oct 2014 19:34:30 -0700, Rustom Mody wrote: > >> >>>> Color.Red >> >>>> print (Color.Red) >> > Color.Red >> > # Not sure what to make of that distinction... > >> That's because the interactive interpreter displays the repr() of objects >> (except for None, which it suppresses), while print outputs the str() of >> them. > > Yeah... > > What I meant to wonder upon was: "Is this behavior what the pro-print or the > anti-print folks like?" > > In any case that the P in REPL is not *exactly* the same as print > (or equivalently the distinction between str and repr) makes for some > intricate noob confusions. > > BTW is there some flag that can make them identical? I haven't used a proprinter since our XL24E died. Never used an antiprinter, myself. Here's how to make print() output the repr() of something: _ORIG_PRINT = print def print(*args, **kw): return _ORIG_PRINT(*(repr(arg) for arg in args), **kw) But what's the point? (Also: Have fun backporting that to 2.5, it won't be easy.) ChrisA From karthik.sharma at gmail.com Thu Oct 9 02:16:46 2014 From: karthik.sharma at gmail.com (karthik.sharma at gmail.com) Date: Wed, 8 Oct 2014 23:16:46 -0700 (PDT) Subject: ZMQError: Resource temporarily unavailable Message-ID: <0ac40dbc-105b-42d4-91f8-d0937bad30cf@googlegroups.com> I am using zero-mq for IPC between two machines. My zmq function is given below def recieve_messages(self): string = self.sub_socket.recv(flags=zmq.NOBLOCK) print('flow mod messages recieved {}'.format(string)) When I run the program however I get the following error. string = self.sub_socket.recv(flags=zmq.NOBLOCK) File "socket.pyx", line 616, in zmq.core.socket.Socket.recv (zmq/core/socket.c:5961) File "socket.pyx", line 650, in zmq.core.socket.Socket.recv (zmq/core/socket.c:5832) File "socket.pyx", line 119, in zmq.core.socket._recv_copy (zmq/core/socket.c:1669) ZMQError: Resource temporarily unavailable Can someone explain what is likely causing this error. From rustompmody at gmail.com Thu Oct 9 02:52:57 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 8 Oct 2014 23:52:57 -0700 (PDT) Subject: trying idle Message-ID: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Been using emacs for over 20 years and teaching python for 10. And getting fed up that my audience looks at me like Rip van Winkle each time I start up emacs... So trying out Idle... Some specific and some general questions: My audience consists of people having linux and windows and macbooks. Does Idle run on all these? [Remember seeing some adventures with Tkinter...] Particularly with macs my knowledge is at the level: "How the ^%*)( do you right click without a right-click button?" So I would like to avoid something that is not quite working. Specific: Is there a way to cut-paste a snippet from the interpreter window containing ">>> " "... " into the file window and auto-remove the prompts? [I have a vague recollection of Terry showing somethin...] From __peter__ at web.de Thu Oct 9 03:51:13 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 09 Oct 2014 09:51:13 +0200 Subject: Toggle References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> <8dba70e4-9670-40d3-9a3f-d2b593d52ac6@googlegroups.com> Message-ID: Rustom Mody wrote: > On Thursday, October 9, 2014 10:26:41 AM UTC+5:30, Steven D'Aprano wrote: >> On Wed, 08 Oct 2014 19:34:30 -0700, Rustom Mody wrote: > >> >>>> Color.Red >> >>>> print (Color.Red) >> > Color.Red >> > # Not sure what to make of that distinction... > >> That's because the interactive interpreter displays the repr() of objects >> (except for None, which it suppresses), while print outputs the str() of >> them. > > Yeah... > > What I meant to wonder upon was: "Is this behavior what the pro-print or > the anti-print folks like?" > > In any case that the P in REPL is not *exactly* the same as print > (or equivalently the distinction between str and repr) makes for some > intricate noob confusions. > > BTW is there some flag that can make them identical? No flag, but you can tweak that P: >>> import sys >>> sys.displayhook = print >>> "foo" foo >>> def f(): pass ... >>> f() None From michael at stroeder.com Thu Oct 9 04:24:53 2014 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 09 Oct 2014 10:24:53 +0200 Subject: ANN: python-ldap 2.4.18 Message-ID: Find a new release of python-ldap: http://pypi.python.org/pypi/python-ldap/2.4.18 python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAP URLs and LDAPv3 schema). Project's web site: http://www.python-ldap.org/ Ciao, Michael. ---------------------------------------------------------------- Released 2.4.18 2014-10-09 Changes since 2.4.17: Lib/ * Fixed raising exception in LDAPObject.read_s() when reading an entry returns empty search result From tjreedy at udel.edu Thu Oct 9 05:26:25 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 09 Oct 2014 05:26:25 -0400 Subject: trying idle In-Reply-To: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Message-ID: On 10/9/2014 2:52 AM, Rustom Mody wrote: > Been using emacs for over 20 years and teaching python for 10. > And getting fed up that my audience looks at me like Rip van Winkle > each time I start up emacs... > > So trying out Idle... > > Some specific and some general questions: > My audience consists of people having linux and windows and macbooks. > Does Idle run on all these? If macbook runs OSX, and the linux has recent tcl/tk installed, the answer should be Yes > [Remember seeing some adventures with Tkinter...] One may have to install activestate tkc/tk on mac, depending on osx version. This page has details: https://www.python.org/download/mac/tcltk > Particularly with macs my knowledge is at the level: > "How the ^%*)( do you right click without a right-click button?" I believe control-click, but Macs users could say better. > So I would like to avoid something that is not quite working. > > Specific: > Is there a way to cut-paste a snippet from the interpreter window > containing ">>> " "... " into the file window and auto-remove the prompts? > [I have a vague recollection of Terry showing somethin...] I doubt I said anything. I have said there is a tracker issue for the feature (something similar to dedent). I would like to add a general facility for users to define reformat/transform functions to do precisely what they want. In particular, what to do with output lines? -- Terry Jan Reedy From vijnaana at gmail.com Thu Oct 9 08:20:34 2014 From: vijnaana at gmail.com (vijnaana at gmail.com) Date: Thu, 9 Oct 2014 05:20:34 -0700 (PDT) Subject: CLI framework using python Message-ID: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> Hi, I need to develop a python CLI framework. For example if i need to set an ip address in linux: ifconfig eth0 172.16.25.125 I should be able to use python to do the above. 1. The user will execute a python script to which i will pass the params eth0 and ip address (something like ifconf.py eth0 172.16.25.125) 2. Within the script i grab the params and do something to the effect of user executing 'ifconfig eth0 172.16.25.125' from the shell. 3. There are other such commands for which i will be using python scripts. I came across pyCLI, but it doesn't have much documentation, so couldn't figure out how to move forward. 4. The CLI framework needs to reuse code so i didn't want to use pure python and develop a framework from scratch. Rather use something like pyCLI/CLIFF. The problem is lack of documentation with examples on how to use the above. Any guidance would be greatly appreciated. Regards & Thanks, Vij From wxjmfauth at gmail.com Thu Oct 9 08:21:46 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Thu, 9 Oct 2014 05:21:46 -0700 (PDT) Subject: trying idle In-Reply-To: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Message-ID: <2e1b8b45-d7bc-4335-8624-3a90af7ef564@googlegroups.com> Le jeudi 9 octobre 2014 08:53:26 UTC+2, Rustom Mody a ?crit?: > > So trying out Idle... > > > > Some specific and some general questions: > > My audience consists of people having linux and windows and macbooks. > > Does Idle run on all these? > --- No. From venugopal.reddy at tspl.com Thu Oct 9 08:30:21 2014 From: venugopal.reddy at tspl.com (Venugopal Reddy) Date: Thu, 9 Oct 2014 05:30:21 -0700 (PDT) Subject: Hi Guys... Reading XML using Jython code Message-ID: Am new to python and Jython... Kindly help me on My issue please ! My Issue is: XML parsing using Jython.. I am sucessfully reading XML file using xml.etree.ElementTree package .. But I have a issue in below scenario . this scenario my code is not working. In my XML file , One main node is there and Multiple child tags are there. But In Child tags , same name repeated twice (like tag repeated twice) This scenario , this package can not read .. How can I read very first come tag (means it should read first come node value only .leave the second come node value) Please help me on this.... From rustompmody at gmail.com Thu Oct 9 08:42:13 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 9 Oct 2014 05:42:13 -0700 (PDT) Subject: Toggle In-Reply-To: References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> <8dba70e4-9670-40d3-9a3f-d2b593d52ac6@googlegroups.com> Message-ID: On Thursday, October 9, 2014 1:21:49 PM UTC+5:30, Peter Otten wrote: > Rustom Mody wrote: > > BTW is there some flag that can make them identical? > No flag, but you can tweak that P: > >>> import sys > >>> sys.displayhook = print > >>> "foo" > foo > >>> def f(): pass > ... > >>> f() > None Yeah. Thats what I was looking for -- thanks! With print as above: >>> "Hello World\n" Hello World >>> With default displayhook: >>> "Hello World\n" 'Hello World\n' >>> From random832 at fastmail.us Thu Oct 9 08:47:14 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Thu, 09 Oct 2014 08:47:14 -0400 Subject: trying idle In-Reply-To: References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Message-ID: <1412858834.4019983.177018357.68629DF0@webmail.messagingengine.com> On Thu, Oct 9, 2014, at 05:26, Terry Reedy wrote: > On 10/9/2014 2:52 AM, Rustom Mody wrote: > > Particularly with macs my knowledge is at the level: > > "How the ^%*)( do you right click without a right-click button?" > > I believe control-click, but Macs users could say better. Control-click was the canonical way to do it when right click menus were introduced in Mac OS itself. Some programs (notably Netscape) supported them via click-hold before that. And it's been nearly a decade since Apple sold a mouse with no ability to right-click. From gelonida at gmail.com Thu Oct 9 08:51:17 2014 From: gelonida at gmail.com (Gelonida N) Date: Thu, 09 Oct 2014 14:51:17 +0200 Subject: how to add custom importer after the normal imports In-Reply-To: References: Message-ID: On 10/9/2014 12:44 AM, Ian Kelly wrote: > On Wed, Oct 8, 2014 at 4:53 AM, Gelonida N wrote: >> Hi, >> >> >> I just read about sys.meta_path, which allows to install custom importers >> *BEFORE* the default importers. >> >> However I have a use case where I would like to add a custom importer >> *AFTER* all other import methods have failed. >> >> Does anybody know how to do this. >> >> One way of implementing this would be to add the default importer as first >> entry in sys.meta_path. My only problem is, that I don't know how to create >> a 'default-importer', such that I can add it into sys.meta_path > > As of CPython 3.3 the default importers are already in sys.meta_path, > so you could just add your custom importer to the end. If you need to > support earlier versions or alternate implementations then this may > not be reliable. > thanks for your answer. I'm using Puthon 2.7 for the given project and there sys.meta_path is []. Just for fun I started Python3.3 and looked at it's meta_path, which contained for example _frozen_importlib.PathFinder Unfortunately python 2.7 does not seem to have the package _frozen_importlib So now the question seems to boil down to looking for the 2.7 equivalent of python 3.3's _frozen_importlib.PathFinder From rustompmody at gmail.com Thu Oct 9 08:53:36 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 9 Oct 2014 05:53:36 -0700 (PDT) Subject: trying idle In-Reply-To: References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Message-ID: <08cfc924-af98-4c8b-a9b7-c6534d1585d7@googlegroups.com> On Thursday, October 9, 2014 2:56:56 PM UTC+5:30, Terry Reedy wrote: > > Specific: > > Is there a way to cut-paste a snippet from the interpreter window > > containing ">>> " "... " into the file window and auto-remove the prompts? > > [I have a vague recollection of Terry showing somethin...] > I doubt I said anything. I have said there is a tracker issue for the > feature (something similar to dedent). I would like to add a general > facility for users to define reformat/transform functions to do > precisely what they want. In particular, what to do with output lines? I was looking for something more simplistic: eg in emacs there are rectangle commands; also following MS office there are 'column' commands. Using either of these its a couple of keystrokes/clicks to 'de-prompt' a region/selection all of whose lines start with ">>> " or "... " From marksabbath at gmail.com Thu Oct 9 09:08:41 2014 From: marksabbath at gmail.com (marksabbath at gmail.com) Date: Thu, 9 Oct 2014 06:08:41 -0700 (PDT) Subject: Numpy, uint64 and Big O notation. Message-ID: <4fca2ff7-ad35-4514-b142-d4330c137fdb@googlegroups.com> Hey all! I'm trying to find out the best way to multiply an uint64 (numpy). Could someone help me find the best way to achieve that and where can I find the time and space complexity in a Big O notation? From rustompmody at gmail.com Thu Oct 9 09:12:08 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 9 Oct 2014 06:12:08 -0700 (PDT) Subject: trying idle In-Reply-To: References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Message-ID: <77f669aa-1fe6-4b0e-a648-9e22e5ed7029@googlegroups.com> On Thursday, October 9, 2014 2:56:56 PM UTC+5:30, Terry Reedy wrote: > On 10/9/2014 2:52 AM, Rustom Mody wrote: > > My audience consists of people having linux and windows and macbooks. > > Does Idle run on all these? > If macbook runs OSX, and the linux has recent tcl/tk installed, the > answer should be Yes I get this traceback on closing idle. Otherwise seems to be working. Still... [idle3 on linux] Exception ignored in: > Traceback (most recent call last): File "/usr/lib/python3.4/idlelib/MultiCall.py", line 244, in __del__ self.widget.unbind(self.widgetinst, seq, id) File "/usr/lib/python3.4/tkinter/__init__.py", line 1071, in unbind self.tk.call('bind', self._w, sequence, '') _tkinter.TclError: can't invoke "bind" command: application has been destroyed Exception ignored in: > Traceback (most recent call last): File "/usr/lib/python3.4/idlelib/MultiCall.py", line 244, in __del__ self.widget.unbind(self.widgetinst, seq, id) File "/usr/lib/python3.4/tkinter/__init__.py", line 1071, in unbind self.tk.call('bind', self._w, sequence, '') _tkinter.TclError: can't invoke "bind" command: application has been destroyed Exception ignored in: > Traceback (most recent call last): File "/usr/lib/python3.4/idlelib/MultiCall.py", line 244, in __del__ self.widget.unbind(self.widgetinst, seq, id) File "/usr/lib/python3.4/tkinter/__init__.py", line 1071, in unbind self.tk.call('bind', self._w, sequence, '') _tkinter.TclError: can't invoke "bind" command: application has been destroyed Exception ignored in: > Traceback (most recent call last): File "/usr/lib/python3.4/idlelib/MultiCall.py", line 244, in __del__ self.widget.unbind(self.widgetinst, seq, id) File "/usr/lib/python3.4/tkinter/__init__.py", line 1071, in unbind self.tk.call('bind', self._w, sequence, '') _tkinter.TclError: can't invoke "bind" command: application has been destroyed From jeanmichel at sequans.com Thu Oct 9 09:19:29 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 9 Oct 2014 15:19:29 +0200 (CEST) Subject: virtualenv question: include just a few site packages In-Reply-To: Message-ID: <515407053.9531235.1412860769774.JavaMail.root@sequans.com> ----- Original Message ----- > From: "Gelonida N" > To: python-list at python.org > Sent: Thursday, 9 October, 2014 12:09:50 AM > Subject: virtualenv question: include just a few site packages > > virtualenv has the switch > --system-site-packages (including all system site pacgaes) > and the switch > --no-site-packages (to expclude all site packages) > > > Does anyone know an easy way to include just a few site-packages? > for example (PySide, but not PyQt) > > The reason I'm asking is following. > Some site packages are sometimes raher huge or sometimes refuse to > compile on certain hosts. > > as these packages are already part of the site packages I'd like to > include them. > > You might wonder why I care whether I have more site packages than I > need. As long as I don't import them, I shouldn't care about it. > If I really wanted to replace a version I could use pip install -U. > > However sometimes I'd like to have a test environment where want to > be > sure, that no module can find certain other modules. so they should > not > be visible. > > at the moment I make some experiments with pyinstaller and the module > pythonqtbindings. and there I'd like to be sure that no PuQt files > end > up in the generated code. > > > The only idea, that I have so far is to > run virutalanv with --system-side-packages and to manually remove > modules I don't want or to > run virtualenv without this switch and to manually add links for site > packages, taht I want. both options don't really feel right for me. > > > Is there any other way? You could build a virtual machine, installing only your VIP modules, and create virtual environment on this virtual machine, using the system site packages. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From ian.g.kelly at gmail.com Thu Oct 9 10:14:29 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 9 Oct 2014 08:14:29 -0600 Subject: how to add custom importer after the normal imports In-Reply-To: References: Message-ID: On Oct 9, 2014 6:53 AM, "Gelonida N" wrote: > I'm using Puthon 2.7 for the given project and there sys.meta_path is []. > > Just for fun I started Python3.3 and looked at it's meta_path, which contained for example _frozen_importlib.PathFinder > > Unfortunately python 2.7 does not seem to have the package _frozen_importlib > > So now the question seems to boil down to looking for the 2.7 equivalent of python 3.3's _frozen_importlib.PathFinder There is no equivalent. Prior to 3.3 that code was buried deeply in the interpreter and not available to scripts. The reason for the change was to expose more of the import machinery for exactly this kind of manipulation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alister.nospam.ware at ntlworld.com Thu Oct 9 11:23:49 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Thu, 09 Oct 2014 15:23:49 GMT Subject: Toggle References: Message-ID: <9MxZv.411008$J62.18700@fx03.am4> On Thu, 09 Oct 2014 17:57:03 +1300, Gregory Ewing wrote: > Seymore4Head wrote: >> I want to toggle between color="Red" and color="Blue" > > toggle = {"Red": "Blue", "Blue": "Red"} > color = toggle[color] How about a simple colour = 'red' if colour == 'blue' else 'blue' -- The light at the end of the tunnel is the headlight of an approaching train. From d.joshi84 at gmail.com Thu Oct 9 11:25:40 2014 From: d.joshi84 at gmail.com (Unix SA) Date: Thu, 9 Oct 2014 20:55:40 +0530 Subject: CLI framework using python In-Reply-To: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> References: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> Message-ID: Hello, Go for Optparse.. Look at below docs on how to use it. http://pymotw.com/2/optparse/ Regards, DJ On Thu, Oct 9, 2014 at 5:50 PM, wrote: > Hi, > > I need to develop a python CLI framework. > > For example if i need to set an ip address in linux: > > ifconfig eth0 172.16.25.125 > > I should be able to use python to do the above. > > 1. The user will execute a python script to which i will pass the params > eth0 and ip address (something like ifconf.py eth0 172.16.25.125) > > 2. Within the script i grab the params and do something to the effect of > user executing 'ifconfig eth0 172.16.25.125' from the shell. > > 3. There are other such commands for which i will be using python scripts. > I came across pyCLI, but it doesn't have much documentation, so couldn't > figure out how to move forward. > > 4. The CLI framework needs to reuse code so i didn't want to use pure > python and develop a framework from scratch. Rather use something like > pyCLI/CLIFF. > > The problem is lack of documentation with examples on how to use the above. > > Any guidance would be greatly appreciated. > > Regards & Thanks, > Vij > > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alister.nospam.ware at ntlworld.com Thu Oct 9 11:28:51 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Thu, 09 Oct 2014 15:28:51 GMT Subject: Practice question References: Message-ID: On Mon, 06 Oct 2014 22:06:09 -0400, Seymore4Head wrote: > On Tue, 7 Oct 2014 01:46:37 +0000 (UTC), Denis McMahon > wrote: > >>On Sun, 05 Oct 2014 19:02:31 -0400, Seymore4Head wrote: >> >>> For the record, I don't want a hint. I want the answer. >>> I see a practice question is similar to this. >>> 15 <= x < 30 And it wants a similar expression that is equivalent. >> >>I think part of the problem here is that you don't understand the >>expression. >> >>The expression: >> >>15 <= x < 30 >> >>contains two conditions: >> >>15 <= x >> >>x < 30 >> >>For the whole expression to be true, both conditions must be true, hence >>the equivalence is: >> >>(15 <= x) and (x < 30) >> >>to test this in python command line, see if the two different >>expressions give the same result for a suitable range of values of x: >> >>for x in range(50): >> if not (15 <= x < 30) == ((15 <= x) and (x < 30)): >> print "discrepancy" >> >>or >> >>for x in range(50): >> if (15 <= x < 30) == ((15 <= x) and (x < 30)): >> print "ok" > > All of the practice questions up to this question had 4 answers. With > each question you could verify the correct answers by just copy and > pasting each choice into Python. > > So when the instructions said I could verify this with Python I assumed > there might be some way to test if the question was == to each answer. no you need to type in each snippet of code & see if they give the same result when run. -- In every non-trivial program there is at least one bug. From skip.montanaro at gmail.com Thu Oct 9 11:39:56 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Thu, 9 Oct 2014 10:39:56 -0500 Subject: Numpy, uint64 and Big O notation. In-Reply-To: <4fca2ff7-ad35-4514-b142-d4330c137fdb@googlegroups.com> References: <4fca2ff7-ad35-4514-b142-d4330c137fdb@googlegroups.com> Message-ID: On Thu, Oct 9, 2014 at 8:08 AM, wrote: > I'm trying to find out the best way to multiply an uint64 (numpy). Could someone help me find the best way to achieve that and where can I find the time and space complexity in a Big O notation? Multiply it by what? This works fine for me: >>> import numpy >>> x = numpy.uint64(57) >>> x 57 >>> type(x) >>> xx = x * x >>> type(xx) >>> xx 3249 >>> xxx = xx * xx >>> xxx 10556001 >>> xxxx = xxx * xxx >>> xxxx 111429157112001 >>> type(xxxx) >>> xxxxx = xxxx * xxxx >>> type(xxxxx) >>> xxxxx 12238449225650938241 I assume under the covers there must be a Python long somewhere: >>> int(xxxxx) 12238449225650938241L I think your question needs to be more concrete. Skip From gelonida at gmail.com Thu Oct 9 11:55:44 2014 From: gelonida at gmail.com (Gelonida N) Date: Thu, 09 Oct 2014 17:55:44 +0200 Subject: virtualenv question: include just a few site packages In-Reply-To: <515407053.9531235.1412860769774.JavaMail.root@sequans.com> References: <515407053.9531235.1412860769774.JavaMail.root@sequans.com> Message-ID: On 10/09/2014 03:19 PM, Jean-Michel Pichavant wrote: > ----- Original Message ----- >> virtualenv has the switch >> --system-site-packages (including all system site pacgaes) >> and the switch >> --no-site-packages (to expclude all site packages) >> >> Does anyone know an easy way to include just a few site-packages? >> for example (PySide, but not PyQt) >> >> The reason I'm asking is following. >> Some site packages are sometimes raher huge or sometimes refuse to >> compile on certain hosts. >> >> as these packages are already part of the site packages I'd like to >> include them. >> >> You might wonder why I care whether I have more site packages than I >> need. As long as I don't import them, I shouldn't care about it. >> If I really wanted to replace a version I could use pip install -U. >> >> However sometimes I'd like to have a test environment where want to >> be >> sure, that no module can find certain other modules. so they should >> not be visible. >> >> at the moment I make some experiments with pyinstaller and the module >> pythonqtbindings. and there I'd like to be sure that no PuQt files >> end up in the generated code. >> >> The only idea, that I have so far is to >> run virutalanv with --system-side-packages and to manually remove >> modules I don't want or to >> run virtualenv without this switch and to manually add links for site >> packages, taht I want. both options don't really feel right for me. >> >> Is there any other way? > > You could build a virtual machine, installing only your VIP modules, and create virtual environment on this virtual machine, using the system site packages. > Yeah that's an option. However I guess in this case it's probably faster to write a script, that 'post-processes' the virtualenv and just deletes files / symlinks, that are not desired. Definitely not elegant, but probably OK. On the other hand a VM migfht help finding out which files to keep. From gelonida at gmail.com Thu Oct 9 12:00:57 2014 From: gelonida at gmail.com (Gelonida N) Date: Thu, 09 Oct 2014 18:00:57 +0200 Subject: CLI framework using python In-Reply-To: References: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> Message-ID: On 10/09/2014 05:25 PM, Unix SA wrote: > Hello, > > Go for Optparse.. Look at below docs on how to use it. > > http://pymotw.com/2/optparse/ > For newer projects I'd suggest argparse (part of Python since 2.7 and can be downloaded / installed for 2.5 / 2.6). https://docs.python.org/2.7/library/argparse.html argparse is very powerfull. you might be interested in looking at subparsers. For calling commands in a slightly nicer way than os.system / sybprocess.Popen you might look at sh or plumbum https://pypi.python.org/pypi/sh https://pypi.python.org/pypi/plumbum > Regards, > DJ > > On Thu, Oct 9, 2014 at 5:50 PM, > wrote: > > Hi, > > I need to develop a python CLI framework. > > For example if i need to set an ip address in linux: > > ifconfig eth0 172.16.25.125 > > I should be able to use python to do the above. > > 1. The user will execute a python script to which i will pass the > params eth0 and ip address (something like ifconf.py eth0 > 172.16.25.125) > > 2. Within the script i grab the params and do something to the > effect of user executing 'ifconfig eth0 172.16.25.125' from the shell. > > 3. There are other such commands for which i will be using python > scripts. I came across pyCLI, but it doesn't have much > documentation, so couldn't figure out how to move forward. > > 4. The CLI framework needs to reuse code so i didn't want to use > pure python and develop a framework from scratch. Rather use > something like pyCLI/CLIFF. > > The problem is lack of documentation with examples on how to use the > above. > > Any guidance would be greatly appreciated. > > Regards & Thanks, > Vij > > -- > https://mail.python.org/mailman/listinfo/python-list > > > > From ian.g.kelly at gmail.com Thu Oct 9 12:07:28 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 9 Oct 2014 10:07:28 -0600 Subject: Toggle In-Reply-To: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> Message-ID: On Wed, Oct 8, 2014 at 8:34 PM, Rustom Mody wrote: > On Thursday, October 9, 2014 7:12:41 AM UTC+5:30, Ben Finney wrote: >> Seymore4Head writes: > >> > I want to toggle between color="Red" and color="Blue" > >> It's good to cultivate ongoing familiarity with the standard library > > And language. In recent python3: > >>>> class Color(Enum): > ... Red = 0 > ... Blue = 1 > ... >>>> Color.Red > >>>> print (Color.Red) > Color.Red > > # Not sure what to make of that distinction... > >>>> c=Color.Red >>>> c = Color.Blue if c==Color.Red else Color.Red >>>> c > >>>> > >>>> # Better >>>> def toggle(c): return Color.Blue if c==Color.Red else Color.Red > ... >>>> toggle(c) > >>>> toggle(c) > > > # which means the c has not changed Python enums can have methods and properties, which means that toggle could be implemented as such: >>> class Color(Enum): ... red = 0 ... blue = 1 ... def toggle(self): ... return Color.blue if self is Color.red else Color.red ... >>> Color.blue.toggle() >>> Color.blue.toggle().toggle() (Note the recommended way to compare enum instances is with "is", not "==".) From python at rgbaz.eu Thu Oct 9 12:08:52 2014 From: python at rgbaz.eu (Python UL) Date: Thu, 09 Oct 2014 18:08:52 +0200 Subject: CLI framework using python In-Reply-To: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> References: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> Message-ID: <5436B314.7080306@rgbaz.eu> On 09-10-14 14:20, vijnaana at gmail.com wrote: > Hi, > > I need to develop a python CLI framework. > > For example if i need to set an ip address in linux: > > ifconfig eth0 172.16.25.125 > > I should be able to use python to do the above. > > 1. The user will execute a python script to which i will pass the params eth0 and ip address (something like ifconf.py eth0 172.16.25.125) > > 2. Within the script i grab the params and do something to the effect of user executing 'ifconfig eth0 172.16.25.125' from the shell. > > 3. There are other such commands for which i will be using python scripts. I came across pyCLI, but it doesn't have much documentation, so couldn't figure out how to move forward. > > 4. The CLI framework needs to reuse code so i didn't want to use pure python and develop a framework from scratch. Rather use something like pyCLI/CLIFF. > > The problem is lack of documentation with examples on how to use the above. > > Any guidance would be greatly appreciated. > > Regards & Thanks, > Vij > Hi Vij Maybe you can have a look at iPython: http://ipython.org/ipython-doc/stable/interactive/tutorial.html gr Arno From skip.montanaro at gmail.com Thu Oct 9 12:31:58 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Thu, 9 Oct 2014 11:31:58 -0500 Subject: Numpy, uint64 and Big O notation. In-Reply-To: References: <4fca2ff7-ad35-4514-b142-d4330c137fdb@googlegroups.com> Message-ID: (For future reference, when responding to answers, it's worthwhile to continue to cc python-list.) On Thu, Oct 9, 2014 at 11:12 AM, Marcos Schratzenstaller < marksabbath at gmail.com> wrote: > The numpy has a function which manipulate 64 bits integers, but I couldn't > find a specific method to multiplicate this kind of objects can not be > manipulated as the same way, so if python is using the correct function > (assuning python is detecting the object, calling the correct function) it > is not a problem, but, where can I find this deep information? Marcos, Yes, the builtin help() function serves as reasonable documentation in this case: >>> help(numpy.int64) Help on class int64 in module numpy: class int64(signedinteger, __builtin__.int) | 64-bit integer. Character code 'l'. Python int compatible. | | Method resolution order: | int64 | signedinteger | integer | number | generic | __builtin__.int | __builtin__.object | | Methods defined here: ... | Methods inherited from generic: | | __abs__(...) | x.__abs__() <==> abs(x) | | __add__(...) | x.__add__(y) <==> x+y ... | __mod__(...) | x.__mod__(y) <==> x%y | | __mul__(...) | x.__mul__(y) <==> x*y ... The __mul__ method implements multiplication. I don't know the specific implementation in numpy, but it's probably little more than a thin wrapper around x * y (with perhaps some type and overflow checking). Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From rustompmody at gmail.com Thu Oct 9 12:33:30 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 9 Oct 2014 09:33:30 -0700 (PDT) Subject: Toggle In-Reply-To: References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> Message-ID: <6c9cf38a-7b43-46f7-a2bb-4fcc4d13cd93@googlegroups.com> On Thursday, October 9, 2014 9:39:07 PM UTC+5:30, Ian wrote: > On Wed, Oct 8, 2014 at 8:34 PM, Rustom Mody wrote: > > On Thursday, October 9, 2014 7:12:41 AM UTC+5:30, Ben Finney wrote: > >> Seymore4Head writes: > >> > I want to toggle between color="Red" and color="Blue" > >> It's good to cultivate ongoing familiarity with the standard library > > And language. In recent python3: > >>>> class Color(Enum): > > ... Red = 0 > > ... Blue = 1 > > ... > >>>> Color.Red > >>>> print (Color.Red) > > Color.Red > > # Not sure what to make of that distinction... > >>>> c=Color.Red > >>>> c = Color.Blue if c==Color.Red else Color.Red > >>>> c > >>>> # Better > >>>> def toggle(c): return Color.Blue if c==Color.Red else Color.Red > > ... > >>>> toggle(c) > >>>> toggle(c) > > # which means the c has not changed > Python enums can have methods and properties, which means that toggle > could be implemented as such: > >>> class Color(Enum): > ... red = 0 > ... blue = 1 > ... def toggle(self): > ... return Color.blue if self is Color.red else Color.red > ... > >>> Color.blue.toggle() > >>> Color.blue.toggle().toggle() Nice! In fact this: > >>> Color.blue.toggle() > > >>> Color.blue.toggle().toggle() > is a nice example of a pattern that is rarely seen: OO syntax, functional (ie non-state-changing) semantics. It would have been even nicer were this acceptable [Its not :-( ] >>> class Color(Enum): ... red = 0 ... blue = 1 ... def toggle(self): ... return blue if self is red else red > (Note the recommended way to compare enum instances is with "is", not "==".) Umm... I know... Im in Lent -- fasting off contentious territories. [You may remember that I'd rather avoid 'is'] From none at mailinator.com Thu Oct 9 13:43:11 2014 From: none at mailinator.com (mm0fmf) Date: Thu, 09 Oct 2014 18:43:11 +0100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 09/10/2014 02:29, Steven D'Aprano wrote: > Apart from the horrible spelling of colour :-) I've always spelt colour as "color" when programming and as "colour" when writing language including documentation about software. colour in a programme doesn't seem right. From buzzard at invalid.invalid Thu Oct 9 14:24:47 2014 From: buzzard at invalid.invalid (duncan smith) Date: Thu, 09 Oct 2014 19:24:47 +0100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5436d2f0$0$48145$862e30e2@ngroups.net> On 09/10/14 18:43, mm0fmf wrote: > On 09/10/2014 02:29, Steven D'Aprano wrote: >> Apart from the horrible spelling of colour :-) > > I've always spelt colour as "color" when programming and as "colour" > when writing language including documentation about software. > > colour in a programme doesn't seem right. > Even in British English that is usually spelt 'program' (from the US spelling, of course). Let's not cave in on 'colour' too. It's bad enough that we can't use 'whilst' loops :-). Duncan From toby at tobiah.org Thu Oct 9 14:26:32 2014 From: toby at tobiah.org (Tobiah) Date: Thu, 09 Oct 2014 11:26:32 -0700 Subject: Python Basics In-Reply-To: References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <78au2a12nlq6nipske1a327p14dvgvakug@4ax.com> Message-ID: >> for i in range(1,10): >> print (str(i)*i) > > Seymour, please don't do this. When you "help" someone by just giving > him the answer to a homework problem, you get him past his immediate > issue of "I need to submit my homework for this problem". That lets > him get through his course without understanding the code he's > creating (because he's not the one creating it). He'll either run into > more trouble before graduating the course, or (far worse) he'll > graduate successfully, without having the competence that the course > is supposed to teach - and the world will be given a qualified > programmer who doesn't know his stuff. That damages the world, damages > the reputation of the course, and gives python-list a reputation as a > homework assignment solver... none of which I want. I'm pretty sure > you don't want it either. > > So don't do people's homework for them. PLEASE!! Wow. How do you react when someone does something that's actually harmful? I don't think you'd have the words! :) From tbaror at gmail.com Thu Oct 9 14:45:56 2014 From: tbaror at gmail.com (Tal Bar-Or) Date: Thu, 9 Oct 2014 11:45:56 -0700 (PDT) Subject: Cant get my tshark pharse to work Message-ID: Hello All, I am writing some code to get captured wiresahrk pcap file , using popen.subprocess and extract some table csv format related to SMB, but for some reason i can get the csv when using off-course regular cmd line its work The code as follow below , maybe someone with exprience with such can help Please advice Thanks import socket,subprocess import os,time sharkCall = ["tshark","-i" ,"1", "-w",os.getcwd() +'/smbsession.pcap'] sharkProc = subprocess.Popen(sharkCall,executable="C:/Program Files/Wireshark/tshark.exe") localip = socket.gethostbyname(socket.gethostname()) a = 0 while a ==0: a = sharkProc.pid time.sleep(2) ipflt = '' listip = socket.gethostbyname_ex('media.isilon.gefen.local')[2] for ip in listip: ipflt= ipflt+ "ip.addr==" + ip + "||" ipflt = ipflt + "ip.addr==" + localip if ipflt.endswith('||'): ipflt = ipflt[:-2] print (ipflt) b= os.path.getsize("//media.isilon.gofn.local/Media/New Text Document.txt") #statinfo print(b) #time.sleep(2) sharkProc.kill() tsharkCall = ["tshark","-r",'C:/traces_test/smbsession.pcap',"-Y",ipflt,"-T","fields","-e","ip.src","-e","ip.dst","-e","smb.file",\ "-e","smb.path","-e","smb.time","-e","tcp.time_delta", "-E","header=y","-E","separator=,","-E","quote=d","-E","occurrence=f",\ '> '+os.getcwd() +'/tracetemp.csv'] tsharkProc = subprocess.Popen(tsharkCall,executable="C:/Program Files/Wireshark/tshark.exe") a = 0 while a ==0: a = tsharkProc.pid time.sleep(2) print ('Finished') From timothy.c.delaney at gmail.com Thu Oct 9 15:53:43 2014 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Fri, 10 Oct 2014 06:53:43 +1100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: <5436d2f0$0$48145$862e30e2@ngroups.net> References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> Message-ID: On 10 October 2014 05:24, duncan smith wrote: > On 09/10/14 18:43, mm0fmf wrote: > > On 09/10/2014 02:29, Steven D'Aprano wrote: > >> Apart from the horrible spelling of colour :-) > > > > I've always spelt colour as "color" when programming and as "colour" > > when writing language including documentation about software. > > > > colour in a programme doesn't seem right. > > > > Even in British English that is usually spelt 'program' (from the US > spelling, of course). Let's not cave in on 'colour' too. It's bad enough > that we can't use 'whilst' loops :-). > That would be a theatre programme vs a computer program. I try to stick with the current spelling style when modifying existing code - esp. for APIs. It's very annoying to have some methods use "z" and others "s" in the same package. So since I'm currently working for a US company I have to consciously remind myself to use their abominations ;) Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Thu Oct 9 16:49:11 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 09 Oct 2014 16:49:11 -0400 Subject: trying idle In-Reply-To: <77f669aa-1fe6-4b0e-a648-9e22e5ed7029@googlegroups.com> References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> <77f669aa-1fe6-4b0e-a648-9e22e5ed7029@googlegroups.com> Message-ID: On 10/9/2014 9:12 AM, Rustom Mody wrote: > On Thursday, October 9, 2014 2:56:56 PM UTC+5:30, Terry Reedy wrote: >> On 10/9/2014 2:52 AM, Rustom Mody wrote: >>> My audience consists of people having linux and windows and macbooks. >>> Does Idle run on all these? > >> If macbook runs OSX, and the linux has recent tcl/tk installed, the >> answer should be Yes > > I get this traceback on closing idle. Otherwise seems to be working. [snip] > _tkinter.TclError: can't invoke "bind" command: application has been destroyed Are you running 3.4.0? This was a 3.4 regression that was only reported to occur if one opened Idle with a editor window and closed without ever running it. This was fixed in http://bugs.python.org/issue20167 but I believe too late for 3.4.0. If you see this with 3.4.2 (strongly recommended, especially forthcoming OSX) or even 3.4.1, please add a note to the issue with exact details -- how start, what do, how close. -- Terry Jan Reedy From marko at pacujo.net Thu Oct 9 16:48:36 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 09 Oct 2014 23:48:36 +0300 Subject: [OT] spelling colour / color was Re: Toggle References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> Message-ID: <877g099dgb.fsf@elektro.pacujo.net> Tim Delaney : > It's very annoying to have some methods use "z" and others "s" in the > same package. "-ize" is standard everywhere in the English-speaking world. Americans insist on "analyze," "paralyze" and "catalyze" but paradoxically also on "lyse". > So since I'm currently working for a US company I have to consciously > remind myself to use their abominations ;) I will use American English instead of my native Finnish in my code so why wouldn't you use American English instead of your native variant of English? It'll also make you get a remote sense of the pain the French are feeling. If it's any consolation, even the Atlanta-based CNN makes their anchors speak standard Hollywoodese. Marko From tjreedy at udel.edu Thu Oct 9 16:57:08 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 09 Oct 2014 16:57:08 -0400 Subject: Toggle In-Reply-To: References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> <8dba70e4-9670-40d3-9a3f-d2b593d52ac6@googlegroups.com> Message-ID: On 10/9/2014 8:42 AM, Rustom Mody wrote: > On Thursday, October 9, 2014 1:21:49 PM UTC+5:30, Peter Otten wrote: >> Rustom Mody wrote: >>> BTW is there some flag that can make them identical? > >> No flag, but you can tweak that P: > >>>>> import sys >>>>> sys.displayhook = print >>>>> "foo" >> foo >>>>> def f(): pass >> ... >>>>> f() >> None > > Yeah. Thats what I was looking for -- thanks! > > With print as above: > >>>> "Hello World\n" > Hello World > With default displayhook: > >>>> "Hello World\n" > 'Hello World\n' For anyone wondering, the reason for the default behavior is to avoid ambiguity between ints and strings containing digits. >>> print(123) 123 >>> print('123') 123 >>> '123' '123' -- Terry Jan Reedy From rosuav at gmail.com Thu Oct 9 17:38:02 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 10 Oct 2014 08:38:02 +1100 Subject: Python Basics In-Reply-To: References: <3c9504c9-6906-4358-b14c-5764bba70a65@googlegroups.com> <78au2a12nlq6nipske1a327p14dvgvakug@4ax.com> Message-ID: On Fri, Oct 10, 2014 at 5:26 AM, Tobiah wrote: >> So don't do people's homework for them. PLEASE!! > > > Wow. How do you react when someone does something that's > actually harmful? I don't think you'd have the words! :) You just saw it. Doing someone's homework *is* harmful. Harms the student, harms the course, harms the industry. ChrisA From emile at fenx.com Thu Oct 9 17:39:49 2014 From: emile at fenx.com (Emile van Sebille) Date: Thu, 09 Oct 2014 14:39:49 -0700 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: References: <7ac186c3-2dbc-4cfa-ab58-37854aeb59d1@googlegroups.com> Message-ID: On 10/8/2014 10:28 AM, bryanjugglercryptographer at yahoo.com.dmarc.invalid wrote: > That doesn't mean to tell a human administrator to regularly restart the server. It's programmatic and it's a reasonably simple and well-established design pattern. I'd call it more a compensation technique than a design pattern*. You know, like rebooting windows routinely. :) Emile *) Alternately known as a workaround or kludge. From rosuav at gmail.com Thu Oct 9 17:42:13 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 10 Oct 2014 08:42:13 +1100 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: References: <7ac186c3-2dbc-4cfa-ab58-37854aeb59d1@googlegroups.com> Message-ID: On Fri, Oct 10, 2014 at 8:39 AM, Emile van Sebille wrote: > On 10/8/2014 10:28 AM, bryanjugglercryptographer at yahoo.com.dmarc.invalid > wrote: > >> That doesn't mean to tell a human administrator to regularly restart the >> server. It's programmatic and it's a reasonably simple and well-established >> design pattern. > > I'd call it more a compensation technique than a design pattern*. You know, > like rebooting windows routinely. :) > > *) Alternately known as a workaround or kludge. That sounds about right to me. ChrisA From tjreedy at udel.edu Thu Oct 9 18:53:58 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 09 Oct 2014 18:53:58 -0400 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/9/2014 1:43 PM, mm0fmf wrote: > On 09/10/2014 02:29, Steven D'Aprano wrote: >> Apart from the horrible spelling of colour :-) > > I've always spelt colour as "color" when programming and as "colour" > when writing language including documentation about software. Like it or not, Python uses American English. Searching 'colour' in F:\Python\dev\4\py34\Doc\*.rst ... F:\Python\dev\4\py34\Doc\faq\library.rst: 102: functions from ncurses and SYSV curses such as colour, alternative character set F:\Python\dev\4\py34\Doc\howto\curses.rst: 382: instead of the Canadian/British spelling 'colour'. If you're used to the F:\Python\dev\4\py34\Doc\howto\regex.rst: 1114: Here's a simple example of using the :meth:`sub` method. It replaces colour F:\Python\dev\4\py34\Doc\howto\regex.rst: 1115: names with the word ``colour``:: F:\Python\dev\4\py34\Doc\howto\regex.rst: 1118: >>> p.sub( 'colour', 'blue socks and red shoes') F:\Python\dev\4\py34\Doc\howto\regex.rst: 1119: 'colour socks and colour shoes' F:\Python\dev\4\py34\Doc\howto\regex.rst: 1120: >>> p.sub( 'colour', 'blue socks and red shoes', count=1) F:\Python\dev\4\py34\Doc\howto\regex.rst: 1121: 'colour socks and red shoes' F:\Python\dev\4\py34\Doc\howto\regex.rst: 1127: >>> p.subn( 'colour', 'blue socks and red shoes') F:\Python\dev\4\py34\Doc\howto\regex.rst: 1128: ('colour socks and colour shoes', 2) F:\Python\dev\4\py34\Doc\howto\regex.rst: 1129: >>> p.subn( 'colour', 'no colours at all') F:\Python\dev\4\py34\Doc\howto\regex.rst: 1130: ('no colours at all', 0) F:\Python\dev\4\py34\Doc\library\colorsys.rst: 24: http://www.cambridgeincolour.com/tutorials/color-spaces.htm. F:\Python\dev\4\py34\Doc\whatsnew\2.0.rst: 1059: and SYSV curses, such as colour, alternative character set support, pads, and Hits found: 14 most regex examples. > colour in a programme doesn't seem right. Perhaps ironically, there are 52 uses of 'colour' in the stdlib, all but 4 in idlelib, and most of those in one file. I just changed all except in the one file. -- Terry Jan Reedy From rosuav at gmail.com Thu Oct 9 19:21:03 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 10 Oct 2014 10:21:03 +1100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Oct 10, 2014 at 9:53 AM, Terry Reedy wrote: > >> colour in a programme doesn't seem right. > > Perhaps ironically, there are 52 uses of 'colour' in the stdlib, all but 4 > in idlelib, and most of those in one file. I just changed all except in the > one file. I agree, although I wouldn't make the change without good reason (avoiding code churn). The last time I used "COLOUR" in any code was in Q-Basic; I had my own subroutine of that name, which did some processing and then used the built-in COLOR command. In fact, the only reason I used the "non-program" spelling of the word was because BASIC doesn't allow shadowing of commands. (I don't even remember what the COLOUR command did. Probably something like coping with red-block - when a CRT screen starts to die and the red channel isn't functional. Hacks to deal with faults, that's what we do!) ChrisA From denismfmcmahon at gmail.com Thu Oct 9 20:37:40 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 10 Oct 2014 00:37:40 +0000 (UTC) Subject: Hi Guys... Reading XML using Jython code References: Message-ID: On Thu, 09 Oct 2014 05:30:21 -0700, Venugopal Reddy wrote: > XML parsing using Jython.. > In my XML file , One main node is there and Multiple child tags are > there. But In Child tags , same name repeated twice (like tag > repeated twice) > Please help me on this.... Normally, when pulling data from an xml document, you'll get a collection of some sort: Are you trying to select every subject of every child, the first subject of every child, the last subject of every child, or some nth subject of every child? You may need to go back to your specification code and look again at how you're specifying which node(s) you want to select. -- Denis McMahon, denismfmcmahon at gmail.com From rustompmody at gmail.com Thu Oct 9 22:03:03 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 9 Oct 2014 19:03:03 -0700 (PDT) Subject: trying idle In-Reply-To: References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> <77f669aa-1fe6-4b0e-a648-9e22e5ed7029@googlegroups.com> Message-ID: <55d849bf-3e68-4a88-9725-3fe5152d22d5@googlegroups.com> On Friday, October 10, 2014 2:19:53 AM UTC+5:30, Terry Reedy wrote: > On 10/9/2014 9:12 AM, Rustom Mody wrote: > > On Thursday, October 9, 2014 2:56:56 PM UTC+5:30, Terry Reedy wrote: > >> On 10/9/2014 2:52 AM, Rustom Mody wrote: > >>> My audience consists of people having linux and windows and macbooks. > >>> Does Idle run on all these? > >> If macbook runs OSX, and the linux has recent tcl/tk installed, the > >> answer should be Yes > > I get this traceback on closing idle. Otherwise seems to be working. > [snip] > > _tkinter.TclError: can't invoke "bind" command: application has been destroyed > Are you running 3.4.0? This was a 3.4 regression that was only reported > to occur if one opened Idle with a editor window and closed without ever > running it. This was fixed in > http://bugs.python.org/issue20167 > but I believe too late for 3.4.0. If you see this with 3.4.2 (strongly > recommended, especially forthcoming OSX) or even 3.4.1, please add a > note to the issue with exact details -- how start, what do, how close. Added the backtrace there. 3.4.1-1 on debian testing From ikorot01 at gmail.com Fri Oct 10 00:21:44 2014 From: ikorot01 at gmail.com (Igor Korot) Date: Thu, 9 Oct 2014 21:21:44 -0700 Subject: python on Linux Message-ID: Hi, ALL, When I am on Windows, I can write something like this: sys.path.append('C:\Users\Igor\Documents\MyLib') Now, when I'm on Linux, can I do this: sys.path.append('~/MyLib') ? I.e., will '~' sign be expanded correctly? Thank you. From drsalists at gmail.com Fri Oct 10 00:38:55 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Thu, 9 Oct 2014 21:38:55 -0700 Subject: python on Linux In-Reply-To: References: Message-ID: Try: sys.path.append(os.path.expanduser('~/MyLib')) On Thu, Oct 9, 2014 at 9:21 PM, Igor Korot wrote: > Hi, ALL, > When I am on Windows, I can write something like this: > > sys.path.append('C:\Users\Igor\Documents\MyLib') > > Now, when I'm on Linux, can I do this: > > sys.path.append('~/MyLib') > > ? > > I.e., will '~' sign be expanded correctly? > > Thank you. > -- > https://mail.python.org/mailman/listinfo/python-list From gordon at panix.com Fri Oct 10 00:37:52 2014 From: gordon at panix.com (John Gordon) Date: Fri, 10 Oct 2014 04:37:52 +0000 (UTC) Subject: python on Linux References: Message-ID: In Igor Korot writes: > sys.path.append('~/MyLib') > I.e., will '~' sign be expanded correctly? Not as written. Use os.path.expanduser() to get user's home directories. -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From dieter at handshake.de Fri Oct 10 01:57:49 2014 From: dieter at handshake.de (dieter) Date: Fri, 10 Oct 2014 07:57:49 +0200 Subject: ZMQError: Resource temporarily unavailable References: <0ac40dbc-105b-42d4-91f8-d0937bad30cf@googlegroups.com> Message-ID: <87h9zcpiua.fsf@handshake.de> karthik.sharma at gmail.com writes: > I am using zero-mq for IPC between two machines. > > My zmq function is given below > > def recieve_messages(self): > string = self.sub_socket.recv(flags=zmq.NOBLOCK) > print('flow mod messages recieved {}'.format(string)) > > > When I run the program however I get the following error. > > string = self.sub_socket.recv(flags=zmq.NOBLOCK) > File "socket.pyx", line 616, in zmq.core.socket.Socket.recv (zmq/core/socket.c:5961) > File "socket.pyx", line 650, in zmq.core.socket.Socket.recv (zmq/core/socket.c:5832) > File "socket.pyx", line 119, in zmq.core.socket._recv_copy (zmq/core/socket.c:1669) > ZMQError: Resource temporarily unavailable > > > Can someone explain what is likely causing this error. The most likely cause is that you try to receive data while there is none available. Usually, with non blocking operations, you start them only after you know they can succeed. If the operation is impossible, you will get an exception (and "Resource temporarily unavailable" seems a good candidate). From dieter at handshake.de Fri Oct 10 02:09:33 2014 From: dieter at handshake.de (dieter) Date: Fri, 10 Oct 2014 08:09:33 +0200 Subject: "High water" Memory fragmentation still a thing? References: <7ac186c3-2dbc-4cfa-ab58-37854aeb59d1@googlegroups.com> Message-ID: <87d2a0piaq.fsf@handshake.de> Emile van Sebille writes: > On 10/8/2014 10:28 AM, > bryanjugglercryptographer at yahoo.com.dmarc.invalid wrote: > >> That doesn't mean to tell a human administrator to regularly restart the server. It's programmatic and it's a reasonably simple and well-established design pattern. > > I'd call it more a compensation technique than a design pattern*. You > know, like rebooting windows routinely. :) > > Emile > > > *) Alternately known as a workaround or kludge. Well, everything has a price. Python does not use memory compaction but places many objects on the heap and therefore, long running processes usually are subject to memory fragmentation. As a consequence, those processes need to be restarted from time to time. Would Python use memory compaction, implementing C extensions would be much more tedious and error prone and there would be less such extensions - limiting the domain where Python is used. One has to choose. People who do not like the choice of the "CPython" implementation (no memory compaction) may look at "Jython" (based on Java, with memory compaction). If they are lucky, all the extensions they need are available there. From irmen.NOSPAM at xs4all.nl Fri Oct 10 02:31:04 2014 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 10 Oct 2014 08:31:04 +0200 Subject: python on Linux In-Reply-To: References: Message-ID: <54377d29$0$2833$e4fe514c@news.xs4all.nl> On 10-10-2014 6:21, Igor Korot wrote: > Hi, ALL, > When I am on Windows, I can write something like this: > > sys.path.append('C:\Users\Igor\Documents\MyLib') While this might work on your system, it may not work on others. - you need to escape the backslashes (or just use forward slashes, they work on windows too) - not all windows installations and versions have their user folders in C:\Users\. On windows too, you'll have to use something like %USERPROFILE% to get to the correct directory if you want it to work correctly in all cases. Irmen From rosuav at gmail.com Fri Oct 10 02:52:49 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 10 Oct 2014 17:52:49 +1100 Subject: "High water" Memory fragmentation still a thing? In-Reply-To: <87d2a0piaq.fsf@handshake.de> References: <7ac186c3-2dbc-4cfa-ab58-37854aeb59d1@googlegroups.com> <87d2a0piaq.fsf@handshake.de> Message-ID: On Fri, Oct 10, 2014 at 5:09 PM, dieter wrote: > Python does not use memory compaction but places many objects on the > heap and therefore, long running processes > usually are subject to memory fragmentation. As a consequence, those > processes need to be restarted from time to time. Pike doesn't use memory compaction either, and also places pretty much everything on the heap. Yet its processes don't need to be restarted; in fact, everything's designed around keeping stuff running permanently. As Emile said, it's not a requirement, it's a compensation technique. I've yet to build a Python process that runs for an entire year (as I'm not confident that I can get it so right that I don't need to update any code), so I can't say for sure that it would work, but I do have Python processes running for multiple months without suffering serious fragmentation. ChrisA From steve+comp.lang.python at pearwood.info Fri Oct 10 02:52:01 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 10 Oct 2014 17:52:01 +1100 Subject: [OT] spelling colour / color was Re: Toggle References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <54378212$0$13009$c3e8da3$5496439d@news.astraweb.com> mm0fmf wrote: > On 09/10/2014 02:29, Steven D'Aprano wrote: >> Apart from the horrible spelling of colour :-) > > I've always spelt colour as "color" when programming and as "colour" > when writing language including documentation about software. > > colour in a programme doesn't seem right. "Normal" programmers spell words the same in code as they do outside of code, e.g.: age address length modulo the odd abbreviation like "len", "addr", etc., and coding conventions like camelCase, underscore_words, sHungarianNotation, etc. So if you spell colour with a U outside of code, I would expect you to spell it with a U inside of code too. Unix programmers take every opportunity to obfuscate their code by dropping nouns and consonants, so I'd expect them to spell "colo(u)r" as something like clr, colr, clor, or even clour. Web programmers tend to make random spelling mistakes ("referer"), so I'd expect "coluor", or perhaps "kolour". But I've never come across your convention of spelling it "colour" in documentation and "color" in code before. How very strange. -- Steven From rosuav at gmail.com Fri Oct 10 02:58:07 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 10 Oct 2014 17:58:07 +1100 Subject: python on Linux In-Reply-To: <54377d29$0$2833$e4fe514c@news.xs4all.nl> References: <54377d29$0$2833$e4fe514c@news.xs4all.nl> Message-ID: On Fri, Oct 10, 2014 at 5:31 PM, Irmen de Jong wrote: > On 10-10-2014 6:21, Igor Korot wrote: >> Hi, ALL, >> When I am on Windows, I can write something like this: >> >> sys.path.append('C:\Users\Igor\Documents\MyLib') > > While this might work on your system, it may not work on others. > > - you need to escape the backslashes (or just use forward slashes, they work on windows too) > - not all windows installations and versions have their user folders in > C:\Users\. On windows too, you'll have to use something like %USERPROFILE% to > get to the correct directory if you want it to work correctly in all cases. AIUI you can use os.path.expanduser() on Windows as well, and it'll take care of USERPROFILE. ChrisA From rosuav at gmail.com Fri Oct 10 03:04:52 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 10 Oct 2014 18:04:52 +1100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: <54378212$0$13009$c3e8da3$5496439d@news.astraweb.com> References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <54378212$0$13009$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Oct 10, 2014 at 5:52 PM, Steven D'Aprano wrote: > "Normal" programmers spell words the same in code as they do outside of > code, e.g.: > > age > address > length There's a difference between identifiers and commands, though. I would expect, for instance, that a customer's address is stored in the database in an address table, which will have an id, which I can reference in Python using the name id. (Yes, that mandates shadowing.) But if I need to reference something that the language/library author provides, I expect that to use American spelling, mainly because that's the most common. REXX is somewhat unusual in providing 'center' and 'centre' functions (identical, just like operator.add and operator.__add__), but I always used center() because it felt wrong to use British spelling in language features. ChrisA From steve+comp.lang.python at pearwood.info Fri Oct 10 03:11:06 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 10 Oct 2014 18:11:06 +1100 Subject: [OT] spelling colour / color was Re: Toggle References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5437868a$0$13011$c3e8da3$5496439d@news.astraweb.com> Terry Reedy wrote: > On 10/9/2014 1:43 PM, mm0fmf wrote: >> On 09/10/2014 02:29, Steven D'Aprano wrote: >>> Apart from the horrible spelling of colour :-) >> >> I've always spelt colour as "color" when programming and as "colour" >> when writing language including documentation about software. > > Like it or not, Python uses American English. [...] > Perhaps ironically, there are 52 uses of 'colour' in the stdlib, all but > 4 in idlelib, and most of those in one file. I just changed all except > in the one file. Well of course Python uses "color" *now*, you've just changed them all. Which I think is bad practice Terry. That's needless code churn. I don't think we should be churning code just to give preference to a minority variant of spelling. "Colour" is preferred in the UK, Australia, New Zealand, Canada, Nigeria, India, Pakistan, Kenya, Malaysia, the Philippines, Ireland, South Africa, and many others. "Color" is preferred only in the USA. Whether you count by number of countries, or by total population of English speakers, users of American spelling make up a minority (less than 30% of English speakers world-wide, and much less by country count). I don't mind Americans using their own spelling in code they write, but I do mind when they churn the standard library to push their preference over that of the original author. I would never go through a code base doing a mass "correction" of American spelling to English, and I don't think you should do the opposite. I believe that documentation, in particular, should be written in a form which is going to be most acceptable to readers world-wide, not just a small minority. Python is an international product, not American. -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 10 03:15:47 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 10 Oct 2014 18:15:47 +1100 Subject: Toggle References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> <6c9cf38a-7b43-46f7-a2bb-4fcc4d13cd93@googlegroups.com> Message-ID: <543787a4$0$13012$c3e8da3$5496439d@news.astraweb.com> Rustom Mody wrote: > In fact this: >> >>> Color.blue.toggle() >> >> >>> Color.blue.toggle().toggle() >> > > is a nice example of a pattern that is rarely seen: > OO syntax, functional (ie non-state-changing) semantics. You don't write much Python code, do you? *wink* It is not "rarely seen" in Python: some_string.strip().replace("x", "y").upper().split() sort of thing is extremely common in Python. -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 10 03:18:07 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 10 Oct 2014 18:18:07 +1100 Subject: Toggle References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> <8dba70e4-9670-40d3-9a3f-d2b593d52ac6@googlegroups.com> Message-ID: <5437882f$0$13012$c3e8da3$5496439d@news.astraweb.com> Rustom Mody wrote: > On Thursday, October 9, 2014 10:26:41 AM UTC+5:30, Steven D'Aprano wrote: >> On Wed, 08 Oct 2014 19:34:30 -0700, Rustom Mody wrote: > >> >>>> Color.Red >> >>>> print (Color.Red) >> > Color.Red >> > # Not sure what to make of that distinction... > >> That's because the interactive interpreter displays the repr() of objects >> (except for None, which it suppresses), while print outputs the str() of >> them. > > Yeah... > > What I meant to wonder upon was: "Is this behavior what the pro-print or > the anti-print folks like?" Python's print is a tool, not a political party or religion. I'm no more "pro-print" than I'm "pro-len" and "anti-float". I use it when appropriate, and don't use it when it isn't. > In any case that the P in REPL is not *exactly* the same as print The "P" in Read Eval Print Loop no more stands for Python's print function (or statement, in 2.x) than the "R" stands for Perl's read(), the "E" for Lisp's eval, or the L for, um, whatever concrete example of a function called "loop" we can come up with. It's a generic term that describes the actions of the interactive environment, not the specific semantics used. > (or equivalently the distinction between str and repr) makes for some > intricate noob confusions. I've been reading this mailing list / newsgroup, and the tutor mailing list, for over a decade, and I don't recall ever seeing a newbie confused by the difference between str() and repr(), or why print uses one and the interactive interpreter the other. I've seen the odd question about it, but I wouldn't call it "confused". That's not to say that it categorically never happened. I'm sure that *somewhere* there is somebody who is confused. There probably is one or two newbies out there who lie awake at night wondering why the output of print looks different from the output in the interactive interpreter. But I do not believe that this is a widespread problem. -- Steven From irmen.NOSPAM at xs4all.nl Fri Oct 10 03:48:33 2014 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 10 Oct 2014 09:48:33 +0200 Subject: python on Linux In-Reply-To: References: <54377d29$0$2833$e4fe514c@news.xs4all.nl> Message-ID: <54378f52$0$2935$e4fe514c@news.xs4all.nl> On 10-10-2014 8:58, Chris Angelico wrote: > AIUI you can use os.path.expanduser() on Windows as well, and it'll > take care of USERPROFILE. Nice, didn't know that! I've been using the appdirs module (https://pypi.python.org/pypi/appdirs/) as well to avoid constructing paths manually altogether. Irmen From harrismh777 at gmail.com Fri Oct 10 03:53:39 2014 From: harrismh777 at gmail.com (Mark H Harris) Date: Fri, 10 Oct 2014 02:53:39 -0500 Subject: trying idle References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Message-ID: On 10/9/14 7:47 AM, random832 at fastmail.us wrote: >> >> I believe control-click, but Macs users could say better. > > Control-click was the canonical way to do it when right click menus were > introduced in Mac OS itself. Some programs (notably Netscape) supported > them via click-hold before that. And it's been nearly a decade since > Apple sold a mouse with no ability to right-click. > The apple mouse has only one click in the hardware... but, through the software (settings) the apple hardware 'know' which side of the mouse you are pushing over. You can configure the mouse through the settings to make the left or right side function alternately. The same is true for the magic mouse (wireless, swipe-able); it also only has one clicker but 'senses' which side of the mouse the fingers are over when the push occurs. At any rate, right mousing on the mac has been happening for several years. From harrismh777 at gmail.com Fri Oct 10 03:54:49 2014 From: harrismh777 at gmail.com (Mark H Harris) Date: Fri, 10 Oct 2014 02:54:49 -0500 Subject: trying idle References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> <2e1b8b45-d7bc-4335-8624-3a90af7ef564@googlegroups.com> Message-ID: On 10/9/14 7:21 AM, wxjmfauth at gmail.com wrote: >> >> My audience consists of people having linux and windows and macbooks. >> >> Does Idle run on all these? >> > --- > > No. > Huh? From harrismh777 at gmail.com Fri Oct 10 04:08:13 2014 From: harrismh777 at gmail.com (Mark H Harris) Date: Fri, 10 Oct 2014 03:08:13 -0500 Subject: trying idle References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Message-ID: On 10/9/14 1:52 AM, Rustom Mody wrote: > Been using emacs for over 20 years and teaching python for 10. > And getting fed up that my audience looks at me like Rip van Winkle > each time I start up emacs... (sigh) > So trying out Idle... Good for you! ... and even better for your students. IDLE is fabulous as a native python interactive development environment these days. It really works well, is clean and does what it advertises; its very nice! > > Some specific and some general questions: > My audience consists of people having linux and windows and macbooks. > Does Idle run on all these? Absolutely. The ONLY problem you might run into on the (macs) apple systems is that tcl/tk tkinter might be at the wrong level. Use ActiveTCL: https://www.python.org/download/mac/tcltk Depending on the apple system the wrong (built-in tcl/tk tkinter) will cause problems. If you ActiveTCL you'll have no problem. Just point your students at the appropriate pages. Cheers From rustompmody at gmail.com Fri Oct 10 04:43:22 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 10 Oct 2014 01:43:22 -0700 (PDT) Subject: CLI framework using python In-Reply-To: References: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> Message-ID: <90907ef5-275d-4f24-bffb-bb97e7c3f051@googlegroups.com> On Thursday, October 9, 2014 9:31:39 PM UTC+5:30, gelonida wrote: > For calling commands in a slightly nicer way than os.system / > sybprocess.Popen you might look at sh or plumbum > https://pypi.python.org/pypi/sh > https://pypi.python.org/pypi/plumbum Both of these look quite nice! [Im looking at them from a couple of angles 1. Using python as a scripting language 2. Notion of DSL ] Can you tell me in short whats the difference?? From raphael.houtin at gmail.com Fri Oct 10 05:49:28 2014 From: raphael.houtin at gmail.com (raphael houtin) Date: Fri, 10 Oct 2014 02:49:28 -0700 (PDT) Subject: Results of arpalert to json in python Message-ID: <6fe8f03d-e336-49ad-87ed-3e417f069afa@googlegroups.com> Hello, I'm trying to create a program who'll catch the mac address connections. For this, I take the /var/log/arpalert.log and create a dict. with the results in JSON. I'm a beginner in Python. For now, I have the arpalert log to a file.txt. I take this file and create a dictionary in an other file. I transform the result to JSON format. But the problem is the "format" of my dictionary. In the Json format I have all the informations of one connection in a key, and all the informations of another connection in the value of the key. But what I want is a key "mac" with the address in value, a key "ip" with the address in value, etc... This is my code for now : from json import dumps, dump from itertools import izip def get_log(source, destination): log = open(source, 'r') fil_dest = open(destination, 'w') txt = log.readline() while txt: fil_dest.write(txt) txt = log.readline() log.close() fil_dest.close() def to_json(source, destination): fil_dest = open(destination, 'w') with open(source, 'r') as lines: txt = lines.readlines() wanted_lines = txt[0:] i = iter(wanted_lines) dict_log = dict(izip(i, i)) dump(dict_log, fil_dest, sort_keys=True, indent=1) lines.close() fil_dest.close() get_log('/var/log/arpalert.log', 'arpalert_strings.txt') to_json('arpalert_strings.txt', 'json_conversion.txt') and the result in JSON ("key": "value") "Oct 8 14:45:52 arpalert: seq=2, mac=a2:e5:68:3c:16:f1, ip=192.168.1.19, type=new, dev=p3p1, vendor=\"(null)\"\n": "Oct 8 14:45:52 arpalert: seq=3, mac=04:e8:ca:a8:6f:b8, ip=192.168.1.19, type=new, dev=p3p1, vendor=\"(null)\"\n", "Oct 9 09:41:46 arpalert: Auto selected device: bluetooth0\n": "Oct 9 09:41:46 arpalert: [./capture.c 181] ioctl[19] : No such device\n", Anybody can help me please ? I tried with regex but I'm lost and I losing my mind ! From marko at pacujo.net Fri Oct 10 06:08:43 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 10 Oct 2014 13:08:43 +0300 Subject: [OT] spelling colour / color was Re: Toggle References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5437868a$0$13011$c3e8da3$5496439d@news.astraweb.com> Message-ID: <877g08nsno.fsf@elektro.pacujo.net> Steven D'Aprano : > Python is an international product, not American. And American English is the international software engineering language, minority or not. The rest of us are using it; why should you not follow suit? Marko From rosuav at gmail.com Fri Oct 10 06:40:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 10 Oct 2014 21:40:42 +1100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: <877g08nsno.fsf@elektro.pacujo.net> References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5437868a$0$13011$c3e8da3$5496439d@news.astraweb.com> <877g08nsno.fsf@elektro.pacujo.net> Message-ID: On Fri, Oct 10, 2014 at 9:08 PM, Marko Rauhamaa wrote: > Steven D'Aprano : > >> Python is an international product, not American. > > And American English is the international software engineering language, > minority or not. > > The rest of us are using it; why should you not follow suit? If Python ever grows a 'color' statement or keyword, then sure. Otherwise, it's just identifiers and data, which are international. ChrisA From marko at pacujo.net Fri Oct 10 06:51:37 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 10 Oct 2014 13:51:37 +0300 Subject: [OT] spelling colour / color was Re: Toggle References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5437868a$0$13011$c3e8da3$5496439d@news.astraweb.com> <877g08nsno.fsf@elektro.pacujo.net> Message-ID: <87y4somc3q.fsf@elektro.pacujo.net> Chris Angelico : > If Python ever grows a 'color' statement or keyword, then sure. > Otherwise, it's just identifiers and data, which are international. Do you mean that the Python syntax should use American spellings, but the Python standard library could use words like "colour", "Farbe", "v?ri" etc? Marko From jeanmichel at sequans.com Fri Oct 10 07:17:11 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 10 Oct 2014 13:17:11 +0200 (CEST) Subject: virtualenv question: include just a few site packages In-Reply-To: Message-ID: <397893630.9690797.1412939830966.JavaMail.root@sequans.com> ----- Original Message ----- > From: "Gelonida N" > To: python-list at python.org > Sent: Thursday, 9 October, 2014 5:55:44 PM > Subject: Re: virtualenv question: include just a few site packages > > You could build a virtual machine, installing only your VIP > > modules, and create virtual environment on this virtual machine, > > using the system site packages. > > > > Yeah that's an option. > > However I guess in this case it's probably faster to write a script, > that 'post-processes' the virtualenv and just deletes files / > symlinks, > that are not desired. Definitely not elegant, but probably OK. On the > other hand a VM migfht help finding out which files to keep. > if you have the package somewhere of those modules you'd want to install you can specify local packages in the pip_requirement.txt file: https://pip.readthedocs.org/en/1.1/requirements.html JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From gelonida at gmail.com Fri Oct 10 07:46:48 2014 From: gelonida at gmail.com (Gelonida N) Date: Fri, 10 Oct 2014 13:46:48 +0200 Subject: how to add custom importer after the normal imports In-Reply-To: References: Message-ID: <5437C728.7080301@gmail.com> On 10/09/2014 04:14 PM, Ian Kelly wrote: >> I have a use case where I would like to add a custom importer *AFTER* all other import methods have failed. > > On Oct 9, 2014 6:53 AM, "Gelonida N" > wrote: > > I'm using Puthon 2.7 for the given project and there sys.meta_path is []. > > > > Just for fun I started Python3.3 and looked at it's meta_path, which > contained for example _frozen_importlib.PathFinder > > > > Unfortunately python 2.7 does not seem to have the package > _frozen_importlib > > > > So now the question seems to boil down to looking for the 2.7 > equivalent of python 3.3's _frozen_importlib.PathFinder > > There is no equivalent. Prior to 3.3 that code was buried deeply in the > interpreter and not available to scripts. The reason for the change was > to expose more of the import machinery for exactly this kind of > manipulation. > > > Thanks for your answer. That's a pity. So the only option I had is to write another custom importer, that mimics as much functionality of the default importer as is necessary so that I can insert it before the otjer custom importers. In my current case this would be to import '.py' files from the current working directory. Will try to find some docs. From gelonida at gmail.com Fri Oct 10 07:46:48 2014 From: gelonida at gmail.com (Gelonida N) Date: Fri, 10 Oct 2014 13:46:48 +0200 Subject: how to add custom importer after the normal imports In-Reply-To: References: Message-ID: <5437C728.7080301@gmail.com> On 10/09/2014 04:14 PM, Ian Kelly wrote: >> I have a use case where I would like to add a custom importer *AFTER* all other import methods have failed. > > On Oct 9, 2014 6:53 AM, "Gelonida N" > wrote: > > I'm using Puthon 2.7 for the given project and there sys.meta_path is []. > > > > Just for fun I started Python3.3 and looked at it's meta_path, which > contained for example _frozen_importlib.PathFinder > > > > Unfortunately python 2.7 does not seem to have the package > _frozen_importlib > > > > So now the question seems to boil down to looking for the 2.7 > equivalent of python 3.3's _frozen_importlib.PathFinder > > There is no equivalent. Prior to 3.3 that code was buried deeply in the > interpreter and not available to scripts. The reason for the change was > to expose more of the import machinery for exactly this kind of > manipulation. > > > Thanks for your answer. That's a pity. So the only option I had is to write another custom importer, that mimics as much functionality of the default importer as is necessary so that I can insert it before the otjer custom importers. In my current case this would be to import '.py' files from the current working directory. Will try to find some docs. From david.jobes.sony at gmail.com Fri Oct 10 07:46:14 2014 From: david.jobes.sony at gmail.com (David Jobes) Date: Fri, 10 Oct 2014 04:46:14 -0700 (PDT) Subject: Parse bad xml file Message-ID: <9bb1f027-dc72-43c1-9301-e2105225f75a@googlegroups.com> I was given a badly or poor formatted xml file that i need to convert to csv file: 00000001-0001-0001-0001-000000000027 27 2 0027: IP Options: Record Route (RR) Network_equip 10 ip 100741885 2001-0752,1999-1339,1999-0986 870 I have been able to load and read the file line by line, but once i get to the r line and try to process each c(column) that is where it blows up. I need to be able to split the lines and place each one or the r (row) on a single line for the csv. i have a list set for each one of the headers based on the col name field, i just have been able to format properly. From rosuav at gmail.com Fri Oct 10 07:50:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 10 Oct 2014 22:50:45 +1100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: <87y4somc3q.fsf@elektro.pacujo.net> References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5437868a$0$13011$c3e8da3$5496439d@news.astraweb.com> <877g08nsno.fsf@elektro.pacujo.net> <87y4somc3q.fsf@elektro.pacujo.net> Message-ID: On Fri, Oct 10, 2014 at 9:51 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> If Python ever grows a 'color' statement or keyword, then sure. >> Otherwise, it's just identifiers and data, which are international. > > Do you mean that the Python syntax should use American spellings, but > the Python standard library could use words like "colour", "Farbe", > "v?ri" etc? That's up to the core devs. But mainly, I was talking about user level code, where you most definitely can do that sort of thing. ChrisA From jeanmichel at sequans.com Thu Oct 9 09:11:39 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 9 Oct 2014 15:11:39 +0200 (CEST) Subject: CLI framework using python In-Reply-To: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> Message-ID: <1421576587.9529932.1412860299434.JavaMail.root@sequans.com> ----- Original Message ----- > From: vijnaana at gmail.com > > Hi, > > I need to develop a python CLI framework. > [snip] > 3. There are other such commands for which i will be using python > scripts. I came across pyCLI, but it doesn't have much > documentation, so couldn't figure out how to move forward. > > Any guidance would be greatly appreciated. > > Regards & Thanks, > Vij https://pythonhosted.org/pyCLI/ The doc features a quick tour and basic usage section + the complete API, illustrated with examples. Why don't you show us some code you've written using pyCli, maybe we could help. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From antoon.pardon at rece.vub.ac.be Fri Oct 10 07:44:08 2014 From: antoon.pardon at rece.vub.ac.be (Antoon Pardon) Date: Fri, 10 Oct 2014 13:44:08 +0200 Subject: Toggle In-Reply-To: <857g0at3wp.fsf@benfinney.id.au> References: <857g0at3wp.fsf@benfinney.id.au> Message-ID: <5437C688.5050001@rece.vub.ac.be> Op 09-10-14 om 03:42 schreef Ben Finney: > Seymore4Head writes: > >> I want to toggle between color="Red" and color="Blue" > It's good to cultivate ongoing familiarity with the standard library > > so that you can make use of wheels already invented and maintained:: > > import itertools > > colours = ["Red", "Blue"] > colour_cycle = itertools.cycle(colours) > > next(colour_cycle) # ? "Red" > next(colour_cycle) # ? "Blue" > next(colour_cycle) # ? "Red" > next(colour_cycle) # ? "Blue" > next(colour_cycle) # ? "Red" > > for colour in colour_cycle: > # ? loops indefinitely > # with ?colour? bound to each value in turn ? I think this solution will become rather involved fast, when you have multiple toggles. -- Antoon Pardon From gelonida at gmail.com Fri Oct 10 07:58:11 2014 From: gelonida at gmail.com (Gelonida N) Date: Fri, 10 Oct 2014 13:58:11 +0200 Subject: CLI framework using python In-Reply-To: <90907ef5-275d-4f24-bffb-bb97e7c3f051@googlegroups.com> References: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> <90907ef5-275d-4f24-bffb-bb97e7c3f051@googlegroups.com> Message-ID: On 10/10/2014 10:43 AM, Rustom Mody wrote: > On Thursday, October 9, 2014 9:31:39 PM UTC+5:30, gelonida wrote: > >> For calling commands in a slightly nicer way than os.system / >> sybprocess.Popen you might look at sh or plumbum > >> https://pypi.python.org/pypi/sh > >> https://pypi.python.org/pypi/plumbum > > Both of these look quite nice! > [Im looking at them from a couple of angles > 1. Using python as a scripting language > 2. Notion of DSL > ] > > Can you tell me in short whats the difference?? > Not really, both are quite new to me as well. On a first glanced I prefered sh However: plumbum works also on Windows systems. As I have to write some code for Windows, some code for Linux and some code for both platforms I think plumbum might be nicer as I can stick to one syntax. So far I used both of them just in very tiny scripts. Most of my code still uses subprocess.Popen or my own clumsy wrappers around it. From __peter__ at web.de Fri Oct 10 08:20:04 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 10 Oct 2014 14:20:04 +0200 Subject: Parse bad xml file References: <9bb1f027-dc72-43c1-9301-e2105225f75a@googlegroups.com> Message-ID: David Jobes wrote: > I was given a badly or poor formatted xml file that i need to convert to > csv file: There are no "badly formatted" XML files, only valid and invalid ones. Fortunately following looks like the beginning of a valid one. > > >
> > > > > > > > > > > > > > > > 00000001-0001-0001-0001-000000000027 > 27 > 2 > 0027: IP Options: Record Route (RR) > Network_equip > 10 > ip > 100741885 > 2001-0752,1999-1339,1999-0986 > 870 > > > > > > > I have been able to load and read the file line by line, XML doesn't have an idea of lines, so don't do that. Instead let a parser make sense of the document structure. > but once i get to > the r line and try to process each c(column) that is where it blows up. I > need to be able to split the lines and place each one or the r (row) on a > single line for the csv. > > i have a list set for each one of the headers based on the col name field, > i just have been able to format properly. Here's a simple script using ElementTree, to introduce you to basic xml handling with Python's stdlib. If you are lucky it might even work ;) import csv import sys from xml.etree import ElementTree SOURCEFILE = "xml_to_csv.xml" tree = ElementTree.parse(SOURCEFILE) table = tree.find("table") column_names = [c.attrib["name"] for c in table.findall("column")] writer = csv.writer(sys.stdout) writer.writerow(column_names) for row in table.find("data").findall("r"): writer.writerow([field.text for field in row.findall("c")]) From david.jobes.sony at gmail.com Fri Oct 10 08:33:40 2014 From: david.jobes.sony at gmail.com (David Jobes) Date: Fri, 10 Oct 2014 05:33:40 -0700 (PDT) Subject: Parse bad xml file In-Reply-To: References: <9bb1f027-dc72-43c1-9301-e2105225f75a@googlegroups.com> Message-ID: On Friday, October 10, 2014 8:21:17 AM UTC-4, Peter Otten wrote: > David Jobes wrote: > > > > > I was given a badly or poor formatted xml file that i need to convert to > > > csv file: > > > > There are no "badly formatted" XML files, only valid and invalid ones. > > Fortunately following looks like the beginning of a valid one. > > > > > > > > > > >
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > 00000001-0001-0001-0001-000000000027 > > > 27 > > > 2 > > > 0027: IP Options: Record Route (RR) > > > Network_equip > > > 10 > > > ip > > > 100741885 > > > 2001-0752,1999-1339,1999-0986 > > > 870 > > > > > > > > > > > > > > > > > > > > > I have been able to load and read the file line by line, > > > > XML doesn't have an idea of lines, so don't do that. Instead let a parser > > make sense of the document structure. > > > > > but once i get to > > > the r line and try to process each c(column) that is where it blows up. I > > > need to be able to split the lines and place each one or the r (row) on a > > > single line for the csv. > > > > > > i have a list set for each one of the headers based on the col name field, > > > i just have been able to format properly. > > > > Here's a simple script using ElementTree, to introduce you to basic xml > > handling with Python's stdlib. If you are lucky it might even work ;) > > > > import csv > > import sys > > from xml.etree import ElementTree > > > > SOURCEFILE = "xml_to_csv.xml" > > > > tree = ElementTree.parse(SOURCEFILE) > > table = tree.find("table") > > column_names = [c.attrib["name"] for c in table.findall("column")] > > writer = csv.writer(sys.stdout) > > writer.writerow(column_names) > > for row in table.find("data").findall("r"): > > writer.writerow([field.text for field in row.findall("c")]) That did it, thank you, and in a lot fewer lines of code than i had, i was trying to use strings and regex. i will read up more on the xml.etree stuff. From rustompmody at gmail.com Fri Oct 10 10:24:06 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 10 Oct 2014 07:24:06 -0700 (PDT) Subject: Toggle In-Reply-To: <5437882f$0$13012$c3e8da3$5496439d@news.astraweb.com> References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> <8dba70e4-9670-40d3-9a3f-d2b593d52ac6@googlegroups.com> <5437882f$0$13012$c3e8da3$5496439d@news.astraweb.com> Message-ID: <39f1d237-0f45-4770-bbad-4a9ebf847ac8@googlegroups.com> On Friday, October 10, 2014 12:48:20 PM UTC+5:30, Steven D'Aprano wrote: > Rustom Mody wrote: > > On Thursday, October 9, 2014 10:26:41 AM UTC+5:30, Steven D'Aprano wrote: > >> On Wed, 08 Oct 2014 19:34:30 -0700, Rustom Mody wrote: > >> >>>> Color.Red > >> >>>> print (Color.Red) > >> > Color.Red > >> > # Not sure what to make of that distinction... > >> That's because the interactive interpreter displays the repr() of objects > >> (except for None, which it suppresses), while print outputs the str() of > >> them. > > Yeah... > > What I meant to wonder upon was: "Is this behavior what the pro-print or > > the anti-print folks like?" > Python's print is a tool, not a political party or religion. I'm no > more "pro-print" than I'm "pro-len" and "anti-float". I use it when > appropriate, and don't use it when it isn't. Yeah... in an ideal world politics and science/technology would be separable if not completely separate. I dont see such a world (round me at least). See (particularly section 2): http://blog.jot.fm/2010/08/26/ten-things-i-hate-about-object-oriented-programming/comment-page-2/ > > In any case that the P in REPL is not *exactly* the same as print > The "P" in Read Eval Print Loop no more stands for Python's print function > (or statement, in 2.x) than the "R" stands for Perl's read(), the "E" for > Lisp's eval, or the L for, um, whatever concrete example of a function > called "loop" we can come up with. It's a generic term that describes the > actions of the interactive environment, not the specific semantics used. > > (or equivalently the distinction between str and repr) makes for some > > intricate noob confusions. > That's not to say that it categorically never happened. I'm sure that > *somewhere* there is somebody who is confused. There probably is one or two > newbies out there who lie awake at night wondering why the output of print > looks different from the output in the interactive interpreter. But I do > not believe that this is a widespread problem. I think Ive seen a number of confusions on this list from the fact that None quietly disappears at REPL top level and no where else. Yeah this is no str vs repr but print statement/expression vs REPL-print. > I've been reading this mailing list / newsgroup, and the tutor mailing list, > for over a decade, and I don't recall ever seeing a newbie confused by the > difference between str() and repr(), or why print uses one and the > interactive interpreter the other. I've seen the odd question about it, but > I wouldn't call it "confused". Count me as noob then! http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python are some explanations: Alex Martelli: repr -- should be unambiguous str -- should be human readable Ned Batchelder: repr for developers str for customers More telling comments from Alex (same SO post) 1. Both have mostly useless default implementations 2. if you override __repr__, that's ALSO used for __str__, but not vice versa 3. despite the words on the subject found in typical docs, hardly anybody bothers making the __repr__ of objects be a string that eval may use to build an equal object (it's just too hard, AND not knowing how the relevant module was actually imported makes it actually flat out impossible). If you dont find all this confusing, I am reminded of Schr?dinger (or one of his ilk): If you dont find Quantum physics confusing you've not begun to understand it For myself: Yeah I understand the philosophy (vaguely) Exact detailed differences -- I never remember. In particular when which is called. Also which defaults to the other. In any case when teaching beginners, I dont want to have anything to do with repr. Just as a teacher of school arithmetic does not generalize arithmetic to Rings and Fields From rustompmody at gmail.com Fri Oct 10 10:28:40 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 10 Oct 2014 07:28:40 -0700 (PDT) Subject: Toggle In-Reply-To: <39f1d237-0f45-4770-bbad-4a9ebf847ac8@googlegroups.com> References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> <8dba70e4-9670-40d3-9a3f-d2b593d52ac6@googlegroups.com> <5437882f$0$13012$c3e8da3$5496439d@news.astraweb.com> <39f1d237-0f45-4770-bbad-4a9ebf847ac8@googlegroups.com> Message-ID: On Friday, October 10, 2014 7:54:33 PM UTC+5:30, Rustom Mody wrote: > More telling comments from Alex (same SO post) > 1. Both have mostly useless default implementations > 2. if you override __repr__, that's ALSO used for __str__, but not vice versa > 3. despite the words on the subject found in typical docs, hardly > anybody bothers making the __repr__ of objects be a string that > eval may use to build an equal object (it's just too hard, AND not > knowing how the relevant module was actually imported makes it > actually flat out impossible). > If you dont find all this confusing, I am reminded of Schr?dinger (or > one of his ilk): > If you dont find Quantum physics confusing you've not begun to understand it Ok: Not Schr?dinger but John Wheeler: http://www.colorado.edu/physics/phys3220/phys3220_fa08/quotes.html From rosuav at gmail.com Fri Oct 10 10:36:49 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 11 Oct 2014 01:36:49 +1100 Subject: Toggle In-Reply-To: References: <64c26ed7-33cc-4be9-93ac-8d2b84b92451@googlegroups.com> <5436157d$0$12918$c3e8da3$5496439d@news.astraweb.com> <8dba70e4-9670-40d3-9a3f-d2b593d52ac6@googlegroups.com> <5437882f$0$13012$c3e8da3$5496439d@news.astraweb.com> <39f1d237-0f45-4770-bbad-4a9ebf847ac8@googlegroups.com> Message-ID: On Sat, Oct 11, 2014 at 1:28 AM, Rustom Mody wrote: >> If you dont find all this confusing, I am reminded of Schr?dinger (or >> one of his ilk): > >> If you dont find Quantum physics confusing you've not begun to understand it > > Ok: Not Schr?dinger but John Wheeler: > http://www.colorado.edu/physics/phys3220/phys3220_fa08/quotes.html Schroedinger's quote. It's both correctly and incorrectly attributed, until someone actually goes and looks it up, at which point its waveform collapses. ChrisA From neilc at norwich.edu Fri Oct 10 10:46:22 2014 From: neilc at norwich.edu (Neil D. Cerutti) Date: Fri, 10 Oct 2014 10:46:22 -0400 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> Message-ID: On 10/9/2014 3:53 PM, Tim Delaney wrote: > That would be a theatre programme vs a computer program. > > I try to stick with the current spelling style when modifying existing > code - esp. for APIs. It's very annoying to have some methods use "z" > and others "s" in the same package. So since I'm currently working for a > US company I have to consciously remind myself to use their abominations ;) Yes, we must not allow unmetred errour to paralyse communication. -- Neil Cerutti From pkpearson at nowhere.invalid Fri Oct 10 11:44:24 2014 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 10 Oct 2014 15:44:24 GMT Subject: python on Linux References: <54377d29$0$2833$e4fe514c@news.xs4all.nl> Message-ID: On Fri, 10 Oct 2014 08:31:04 +0200, Irmen de Jong wrote: > On 10-10-2014 6:21, Igor Korot wrote: >> When I am on Windows, I can write something like this: >> >> sys.path.append('C:\Users\Igor\Documents\MyLib') > > While this might work on your system, it may not work on others. > > - you need to escape the backslashes (or just use forward slashes, > they work on windows too) And remember that os.path.join() will join path fragments with the right kind of slashes for your operating system. -- To email me, substitute nowhere->runbox, invalid->com. From ian.g.kelly at gmail.com Fri Oct 10 11:52:08 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 10 Oct 2014 09:52:08 -0600 Subject: python on Linux In-Reply-To: <54377d29$0$2833$e4fe514c@news.xs4all.nl> References: <54377d29$0$2833$e4fe514c@news.xs4all.nl> Message-ID: On Fri, Oct 10, 2014 at 12:31 AM, Irmen de Jong wrote: > - you need to escape the backslashes (or just use forward slashes, they work on windows too) Or use a raw string. There is usually no reason to have escape sequences at all in a file system path. From rosuav at gmail.com Fri Oct 10 11:53:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 11 Oct 2014 02:53:18 +1100 Subject: python on Linux In-Reply-To: References: <54377d29$0$2833$e4fe514c@news.xs4all.nl> Message-ID: On Sat, Oct 11, 2014 at 2:44 AM, Peter Pearson wrote: > On Fri, 10 Oct 2014 08:31:04 +0200, Irmen de Jong wrote: >> On 10-10-2014 6:21, Igor Korot wrote: > >>> When I am on Windows, I can write something like this: >>> >>> sys.path.append('C:\Users\Igor\Documents\MyLib') >> >> While this might work on your system, it may not work on others. >> >> - you need to escape the backslashes (or just use forward slashes, >> they work on windows too) > > And remember that os.path.join() will join path fragments with > the right kind of slashes for your operating system. That's fine if you have the parts separately already, but when it's primarily a single literal string, just use slashes and save yourself the trouble. ChrisA From alister.nospam.ware at ntlworld.com Fri Oct 10 13:31:23 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Fri, 10 Oct 2014 17:31:23 GMT Subject: [OT] spelling colour / color was Re: Toggle References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> <877g099dgb.fsf@elektro.pacujo.net> Message-ID: On Thu, 09 Oct 2014 23:48:36 +0300, Marko Rauhamaa wrote: > Tim Delaney : > >> It's very annoying to have some methods use "z" and others "s" in the >> same package. > > "-ize" is standard everywhere in the English-speaking world. Not in England! > > Americans insist on "analyze," "paralyze" and "catalyze" but > paradoxically also on "lyse". > >> So since I'm currently working for a US company I have to consciously >> remind myself to use their abominations ;) > > I will use American English instead of my native Finnish in my code so > why wouldn't you use American English instead of your native variant of > English? > Because I am English, I use English English (mostly, but interspersed with a large dose of bollocks :-) ) > It'll also make you get a remote sense of the pain the French are > feeling. > > If it's any consolation, even the Atlanta-based CNN makes their anchors > speak standard Hollywoodese. > > > Marko -- I brought my BOWLING BALL -- and some DRUGS!! From breamoreboy at yahoo.co.uk Fri Oct 10 13:38:33 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 10 Oct 2014 18:38:33 +0100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 09/10/2014 23:53, Terry Reedy wrote: > > Like it or not, Python uses American English. > It is my understanding that this has been agreed to by a Dutch born dictator. The traitor should be shot, selling out his fellow Europeans to the North Americans indeed :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Fri Oct 10 13:45:02 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 10 Oct 2014 18:45:02 +0100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> Message-ID: On 10/10/2014 15:46, Neil D. Cerutti wrote: > On 10/9/2014 3:53 PM, Tim Delaney wrote: >> That would be a theatre programme vs a computer program. >> >> I try to stick with the current spelling style when modifying existing >> code - esp. for APIs. It's very annoying to have some methods use "z" >> and others "s" in the same package. So since I'm currently working for a >> US company I have to consciously remind myself to use their >> abominations ;) > > Yes, we must not allow unmetred errour to paralyse communication. > Ghoughpteighbteau and ghoti pie to you to. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve at bellissimmo.com Fri Oct 10 14:13:53 2014 From: steve at bellissimmo.com (Simmo) Date: Fri, 10 Oct 2014 19:13:53 +0100 Subject: Python and sqlite versions Message-ID: First off, this is my first attempt to post via Thunderbird newsgroup, so apologies (and please let me know) if it doesn't arrive in good shape. I'm just starting to get to grips with using a database (sqlite) and I've run into some confusion as to how Python 'ties in' to sqlite. First step in the tutorial is to import sqlite3 and display sqlite3.version and sqlite3.sqlite_version. Output below... >>> sqlite3.version '2.6.0' >>> sqlite3.sqlite_version '3.7.12' Next step is to run up sqlite. Output below... SQLite version 3.8.6 2014-08-15 11:46:33 Enter ".help" for usage hints. So, I have a disparity between installed sqlite and the Python sqlite library. Do I need to find a 3.7.12 version of sqlite and , if so, where might I find it or can I change the Python library for the later version? Steve From cruzud at gmail.com Fri Oct 10 14:51:03 2014 From: cruzud at gmail.com (cruzud at gmail.com) Date: Fri, 10 Oct 2014 11:51:03 -0700 (PDT) Subject: Make a colour blink Message-ID: <4b06699a-8852-4389-8a46-f0d2659322e1@googlegroups.com> Hello. I'm trying to make a colour blink when an event occurs. But the program is displaying only the last colour: self.bttn.bind('',blink) def blink(self, event=None): lbl['background'] = 'red' sleep(0.5) lbl.['background'] = 'SystemButtonFace' Can you help? From zachary.ware+pylist at gmail.com Fri Oct 10 15:02:04 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 10 Oct 2014 14:02:04 -0500 Subject: Python and sqlite versions In-Reply-To: References: Message-ID: Hi Steve, On Fri, Oct 10, 2014 at 1:13 PM, Simmo wrote: > First off, this is my first attempt to post via Thunderbird newsgroup, so > apologies (and please let me know) if it doesn't arrive in good shape. Looks fine to me :) > I'm just starting to get to grips with using a database (sqlite) and I've > run into some confusion as to how Python 'ties in' to sqlite. How Python links with SQLite depends on several things, most importantly which platform you're on. > First step in the tutorial is to import sqlite3 and display sqlite3.version > and sqlite3.sqlite_version. Output below... > >>>> sqlite3.version > '2.6.0' >>>> sqlite3.sqlite_version > '3.7.12' > > Next step is to run up sqlite. Output below... > > SQLite version 3.8.6 2014-08-15 11:46:33 > Enter ".help" for usage hints. > > So, I have a disparity between installed sqlite and the Python sqlite > library. Do I need to find a 3.7.12 version of sqlite and , if so, where > might I find it or can I change the Python library for the later version? There aren't a huge number of differences between various versions of SQLite3 and fewer that you're likely to run into anyway, especially just starting out. You should be fine just using what you've got, just keep the fact that you're running different versions in the back of your mind if you come across differences that don't make any sense. It may be possible to change the version that Python uses, but again it depends on your platform and possibly your version of Python (sqlite3.version has been the same from Python 2.6 to 3.5). -- Zach From marko at pacujo.net Fri Oct 10 15:01:58 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 10 Oct 2014 22:01:58 +0300 Subject: [OT] spelling colour / color was Re: Toggle References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> <877g099dgb.fsf@elektro.pacujo.net> Message-ID: <87y4sneok9.fsf@elektro.pacujo.net> alister : > On Thu, 09 Oct 2014 23:48:36 +0300, Marko Rauhamaa wrote: > >> "-ize" is standard everywhere in the English-speaking world. > > Not in England! Both -ize and -ise are valid in England. >> why wouldn't you use American English instead of your native variant >> of English? >> > Because I am English, I use English English How can you expect the French to use English if you are not willing to make the token gesture of using American spelling in the names of your variables? Marko From square.steve at gmail.com Fri Oct 10 15:18:07 2014 From: square.steve at gmail.com (Simmo) Date: Fri, 10 Oct 2014 20:18:07 +0100 Subject: Python and sqlite versions In-Reply-To: References: Message-ID: <543830EF.8090008@bellissimmo.com> On 10/10/2014 20:02, Zachary Ware wrote: > Hi Steve, > > On Fri, Oct 10, 2014 at 1:13 PM, Simmo wrote: >> First off, this is my first attempt to post via Thunderbird newsgroup, so >> apologies (and please let me know) if it doesn't arrive in good shape. > > Looks fine to me :) Thank you ;-) > >> I'm just starting to get to grips with using a database (sqlite) and I've >> run into some confusion as to how Python 'ties in' to sqlite. > > How Python links with SQLite depends on several things, most > importantly which platform you're on. > >> First step in the tutorial is to import sqlite3 and display sqlite3.version >> and sqlite3.sqlite_version. Output below... >> >>>>> sqlite3.version >> '2.6.0' >>>>> sqlite3.sqlite_version >> '3.7.12' >> >> Next step is to run up sqlite. Output below... >> >> SQLite version 3.8.6 2014-08-15 11:46:33 >> Enter ".help" for usage hints. >> >> So, I have a disparity between installed sqlite and the Python sqlite >> library. Do I need to find a 3.7.12 version of sqlite and , if so, where >> might I find it or can I change the Python library for the later version? > > There aren't a huge number of differences between various versions of > SQLite3 and fewer that you're likely to run into anyway, especially > just starting out. You should be fine just using what you've got, > just keep the fact that you're running different versions in the back > of your mind if you come across differences that don't make any sense. > > It may be possible to change the version that Python uses, but again > it depends on your platform and possibly your version of Python > (sqlite3.version has been the same from Python 2.6 to 3.5). > Thanks for this too. I'll plough on and deal with exceptions as they come. For the record, I'm on Windows 7 Steve From steve at bellissimmo.com Fri Oct 10 15:18:07 2014 From: steve at bellissimmo.com (Simmo) Date: Fri, 10 Oct 2014 20:18:07 +0100 Subject: Python and sqlite versions In-Reply-To: References: Message-ID: <543830EF.8090008@bellissimmo.com> On 10/10/2014 20:02, Zachary Ware wrote: > Hi Steve, > > On Fri, Oct 10, 2014 at 1:13 PM, Simmo wrote: >> First off, this is my first attempt to post via Thunderbird newsgroup, so >> apologies (and please let me know) if it doesn't arrive in good shape. > > Looks fine to me :) Thank you ;-) > >> I'm just starting to get to grips with using a database (sqlite) and I've >> run into some confusion as to how Python 'ties in' to sqlite. > > How Python links with SQLite depends on several things, most > importantly which platform you're on. > >> First step in the tutorial is to import sqlite3 and display sqlite3.version >> and sqlite3.sqlite_version. Output below... >> >>>>> sqlite3.version >> '2.6.0' >>>>> sqlite3.sqlite_version >> '3.7.12' >> >> Next step is to run up sqlite. Output below... >> >> SQLite version 3.8.6 2014-08-15 11:46:33 >> Enter ".help" for usage hints. >> >> So, I have a disparity between installed sqlite and the Python sqlite >> library. Do I need to find a 3.7.12 version of sqlite and , if so, where >> might I find it or can I change the Python library for the later version? > > There aren't a huge number of differences between various versions of > SQLite3 and fewer that you're likely to run into anyway, especially > just starting out. You should be fine just using what you've got, > just keep the fact that you're running different versions in the back > of your mind if you come across differences that don't make any sense. > > It may be possible to change the version that Python uses, but again > it depends on your platform and possibly your version of Python > (sqlite3.version has been the same from Python 2.6 to 3.5). > Thanks for this too. I'll plough on and deal with exceptions as they come. For the record, I'm on Windows 7 Steve From python at mrabarnett.plus.com Fri Oct 10 15:24:01 2014 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 10 Oct 2014 20:24:01 +0100 Subject: Make a colour blink In-Reply-To: <4b06699a-8852-4389-8a46-f0d2659322e1@googlegroups.com> References: <4b06699a-8852-4389-8a46-f0d2659322e1@googlegroups.com> Message-ID: <54383251.2060004@mrabarnett.plus.com> On 2014-10-10 19:51, cruzud at gmail.com wrote: > Hello. I'm trying to make a colour blink when an event occurs. > But the program is displaying only the last colour: > > self.bttn.bind('',blink) > > def blink(self, event=None): > lbl['background'] = 'red' > sleep(0.5) > lbl.['background'] = 'SystemButtonFace' > > Can you help? > You shouldn't use sleep like that because it'll block the event loop. Instead, you should use a timed callback that will reset the colour after a certain amount of time has elapsed, something like this (untested): def blink(self, event=None): lbl['background'] = 'red' # Assuming that 'main_window' is the main window... main_window.after(500, reset_color) # Time in milliseconds. def reset_color(): lbl.['background'] = 'SystemButtonFace' Have a look here: http://effbot.org/tkinterbook/widget.htm From breamoreboy at yahoo.co.uk Fri Oct 10 15:25:03 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 10 Oct 2014 20:25:03 +0100 Subject: Make a colour blink In-Reply-To: <4b06699a-8852-4389-8a46-f0d2659322e1@googlegroups.com> References: <4b06699a-8852-4389-8a46-f0d2659322e1@googlegroups.com> Message-ID: On 10/10/2014 19:51, cruzud at gmail.com wrote: > Hello. I'm trying to make a colour blink when an event occurs. > But the program is displaying only the last colour: > > self.bttn.bind('',blink) > > def blink(self, event=None): > lbl['background'] = 'red' > sleep(0.5) > lbl.['background'] = 'SystemButtonFace' > > Can you help? > Telling us what platform you're on, your OS, Python version and the actual GUI helps in cases like this. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From zachary.ware+pylist at gmail.com Fri Oct 10 15:31:22 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 10 Oct 2014 14:31:22 -0500 Subject: Python and sqlite versions In-Reply-To: <543830EF.8090008@bellissimmo.com> References: <543830EF.8090008@bellissimmo.com> Message-ID: On Fri, Oct 10, 2014 at 2:18 PM, Simmo wrote: > For the record, I'm on Windows 7 In that case (if I'm remembering correctly, I'm not on Windows at the moment), you could probably back up C:\Python33\DLLs\sqlite3.dll somewhere (just in case) and copy the sqlite3.dll you got with the sqlite3 distribution into that folder, and Python should be happy to use the newer version of sqlite3. -- Zach From random832 at fastmail.us Fri Oct 10 15:32:38 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Fri, 10 Oct 2014 15:32:38 -0400 Subject: trying idle In-Reply-To: References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Message-ID: <1412969558.419397.177595321.7151092C@webmail.messagingengine.com> On Fri, Oct 10, 2014, at 03:53, Mark H Harris wrote: > The apple mouse has only one click in the hardware... but, through the > software (settings) the apple hardware 'know' which side of the mouse > you are pushing over. It only has one physical switch (I'm not sure the latest ones have any at all), but AFAIK that doesn't mean it doesn't send right-click events to systems that just see it as a dumb HID mouse. From cruzud at gmail.com Fri Oct 10 15:45:21 2014 From: cruzud at gmail.com (Ulisses) Date: Fri, 10 Oct 2014 12:45:21 -0700 (PDT) Subject: Make a colour blink In-Reply-To: References: <4b06699a-8852-4389-8a46-f0d2659322e1@googlegroups.com> Message-ID: <50680f20-4c38-430c-9eae-a845102e3539@googlegroups.com> > Telling us what platform you're on, your OS, Python version and the > > actual GUI helps in cases like this. > > > > -- > > My fellow Pythonistas, ask not what our language can do for you, ask > > what you can do for our language. > > > > Mark Lawrence Hello again. I forgot to tell you: I'm in Windows OS, Python 3.4.1, using tkinter. From maxc at me.com Fri Oct 10 15:49:57 2014 From: maxc at me.com (Max Countryman) Date: Fri, 10 Oct 2014 12:49:57 -0700 Subject: [ANN] Atomos 0.1.0 - Atomic primitives for Python Message-ID: <0F3B4252-95C8-42F5-BF8D-365D09C51E79@me.com> Hi, I would like to announce the initial release of Atomos, a library that provides atomic primitives a la java.util.concurrent.atomic as well as a Python implementation of Clojure?s atoms. Atomos targets applications which benefit from threads and wish to eliminate race conditions between them by synchronizing shared state mutation. Traditionally locks are one solution to this problem. However Atomos provides high-level abstractions over locks that allow the developer to think in terms of these abstractions instead of locks. In other words, Atomos does locking for you behind the scenes provided you participate in its API. Check out the project on Github for more info and a detailed description of usage: https://github.com/maxcountryman/atomos Features: * Atomic wrappers around int, long, float, and boolean * Generalized atomic wrapper around arbitrary object types * Compare-and-set * Atomicity without having to think in terms of locks * Atoms! (http://clojure.org/atoms ) Thanks, Max -------------- next part -------------- An HTML attachment was scrubbed... URL: From alister.nospam.ware at ntlworld.com Fri Oct 10 16:05:10 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Fri, 10 Oct 2014 20:05:10 GMT Subject: [OT] spelling colour / color was Re: Toggle References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> <877g099dgb.fsf@elektro.pacujo.net> <87y4sneok9.fsf@elektro.pacujo.net> Message-ID: On Fri, 10 Oct 2014 22:01:58 +0300, Marko Rauhamaa wrote: > alister : > >> On Thu, 09 Oct 2014 23:48:36 +0300, Marko Rauhamaa wrote: >> >>> "-ize" is standard everywhere in the English-speaking world. >> >> Not in England! > > > > Both -ize and -ise are valid in England. > >>> why wouldn't you use American English instead of your native variant >>> of English? >>> >> Because I am English, I use English English > > How can you expect the French to use English if you are not willing to > make the token gesture of using American spelling in the names of your > variables? > > > Marko Would the French tolerate me using an alternative Variant (Canadian or Carribean)? I think not UK English as spoken in England is the definitive version. The clue is in the Name - English not American -- Whenever anyone says, "theoretically," they really mean, "not really." -- Dave Parnas From steve at bellissimmo.com Fri Oct 10 16:39:18 2014 From: steve at bellissimmo.com (Simmo) Date: Fri, 10 Oct 2014 21:39:18 +0100 Subject: Python and sqlite versions In-Reply-To: References: <543830EF.8090008@bellissimmo.com> Message-ID: On 10/10/2014 20:31, Zachary Ware wrote: > On Fri, Oct 10, 2014 at 2:18 PM, Simmo wrote: >> For the record, I'm on Windows 7 > > In that case (if I'm remembering correctly, I'm not on Windows at the > moment), you could probably back up C:\Python33\DLLs\sqlite3.dll > somewhere (just in case) and copy the sqlite3.dll you got with the > sqlite3 distribution into that folder, and Python should be happy to > use the newer version of sqlite3. > That's got to be worth a punt. What's the worst that can happen... Thanks again Zach From zachary.ware+pylist at gmail.com Fri Oct 10 16:48:50 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 10 Oct 2014 15:48:50 -0500 Subject: Python and sqlite versions In-Reply-To: References: <543830EF.8090008@bellissimmo.com> Message-ID: On Fri, Oct 10, 2014 at 3:39 PM, Simmo wrote: > On 10/10/2014 20:31, Zachary Ware wrote: >> >> On Fri, Oct 10, 2014 at 2:18 PM, Simmo wrote: >>> >>> For the record, I'm on Windows 7 >> >> >> In that case (if I'm remembering correctly, I'm not on Windows at the >> moment), you could probably back up C:\Python33\DLLs\sqlite3.dll >> somewhere (just in case) and copy the sqlite3.dll you got with the >> sqlite3 distribution into that folder, and Python should be happy to >> use the newer version of sqlite3. >> > That's got to be worth a punt. What's the worst that can happen... > > Thanks again Zach No problem, glad I could help :) -- Zach From juan0christian at gmail.com Fri Oct 10 18:22:29 2014 From: juan0christian at gmail.com (Juan Christian) Date: Fri, 10 Oct 2014 19:22:29 -0300 Subject: Flask and Django Message-ID: So, I'm already familiar with Flask and I fell comfortable using it, but I see that no one uses it in "real business", everywhere I look regarding jobs and web dev, people always talk about Django, no one mentions Flask, no one uses Flask. I'm coding a personal tool using Flask but I feel the need to "convert" it to Django because no ones seems to give attention to Flask, but no matter what, I don't like, I don't fully understand Django, there are tons of conventions, code generations and and too much red tape. Maybe that's because I feel the Django doc a bit confuse, I tried reading (and practicing!) tutorials, official doc, books, and so on, but I can't quite understand the whole thing. Is Flask really underestimated? Can you guys mention "big name" companies or people using it? Does it have real value in real world business? -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Fri Oct 10 18:51:03 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 11 Oct 2014 09:51:03 +1100 Subject: Python and sqlite versions In-Reply-To: References: <543830EF.8090008@bellissimmo.com> Message-ID: On Sat, Oct 11, 2014 at 7:39 AM, Simmo wrote: > On 10/10/2014 20:31, Zachary Ware wrote: >> In that case (if I'm remembering correctly, I'm not on Windows at the >> moment), you could probably back up C:\Python33\DLLs\sqlite3.dll >> somewhere (just in case) and copy the sqlite3.dll you got with the >> sqlite3 distribution into that folder, and Python should be happy to >> use the newer version of sqlite3. >> > That's got to be worth a punt. What's the worst that can happen... > The worst? You could have nasty failures out of Python, segfaults, stuff like that. In theory, it might even be able to corrupt your database files, although I suspect not. So try it out with the memory backend, make sure stuff's working, and make sure you did back up the previous DLL (like he said to, but this is important enough to be repeated). Rolling back should be easy and safe. :) ChrisA From ghosh.parthapratim.ukzn at gmail.com Sat Oct 11 00:55:19 2014 From: ghosh.parthapratim.ukzn at gmail.com (Partha Pratim Ghosh) Date: Sat, 11 Oct 2014 04:55:19 +0000 (UTC) Subject: Error with saving animation Message-ID: Dear All, I am having a problem with saving the output of an animation as a file. I provide here two listing, first the small program which otherwise works well, except while executing the last few lines to save the output produces error which I also provide: 1. the program test.py : from matplotlib import animation as anim from matplotlib import pyplot as plt import numpy as np fig = plt.figure() plt.axis([-1,1,-1,1]) abcissa, = plt.plot([],[], color='black') graph, = plt.plot([], [], color='blue') t, = plt.plot([],[], color='red') def init(): ''' set the basic graph and put slate clean for blit''' x = np.arange(-1,1,0.01)# the x-values y = np.sin(np.pi/2 * x) abcissa.set_data(x, 0) graph.set_data(x, y) return abcissa, graph def animate(i): p = -1 + i*0.02 tx = [p-1,p+1] ty = [np.sin(np.pi/2 * p) - np.pi/2 * np.cos(np.pi/2 *p), np.sin(np.pi/2 * p) + np.pi/2 * np.cos(np.pi/2 *p)] t.set_data(tx, ty) return t, ani = anim.FuncAnimation(fig, animate, init_func=init, frames=100, interval=30, blit=True) plt.show() Writer = anim.writers['ffmpeg'] writer = Writer(fps=15, bitrate=1800) ani.save('test.mp4', writer=writer) 2. Error output ani.save('test.mp4', writer=writer) File "/usr/lib/python3/dist-packages/matplotlib/animation.py", line 719, in save writer.grab_frame(**savefig_kwargs) File "/usr/lib/python3/dist-packages/matplotlib/animation.py", line 205, in grab_frame dpi=self.dpi, **savefig_kwargs) File "/usr/lib/python3/dist-packages/matplotlib/figure.py", line 1422, in savefig self.canvas.print_figure(*args, **kwargs) File "/usr/lib/python3/dist-packages/matplotlib/backend_bases.py", line 2225, in print_figure self.figure.dpi = origDPI File "/usr/lib/python3/dist-packages/matplotlib/figure.py", line 385, in _set_dpi self.dpi_scale_trans.clear().scale(dpi, dpi) File "/usr/lib/python3/dist-packages/matplotlib/transforms.py", line 1786, in clear self._mtx = np.identity(3) File "/usr/lib/python3/dist-packages/numpy/core/numeric.py", line 2053, in identity from numpy import eye File "", line 2280, in _handle_fromlist UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte ' Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.4/idlelib/run.py", line 121, in main seq, request = rpc.request_queue.get(block=True, timeout=0.05) File "/usr/lib/python3.4/queue.py", line 175, in get raise Empty queue.Empty During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/matplotlib/backends/tkagg.py", line 13, in blit tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array)) _tkinter.TclError: this isn't a Tk application During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in __call__ return self.func(*args) File "/usr/lib/python3.4/tkinter/__init__.py", line 585, in callit func(*args) File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 363, in idle_draw self.draw() File "/usr/lib/python3/dist-packages/matplotlib/backends/backend_tkagg.py", line 349, in draw tkagg.blit(self._tkphoto, self.renderer._renderer, colormode=2) File "/usr/lib/python3/dist-packages/matplotlib/backends/tkagg.py", line 20, in blit tk.call("PyAggImagePhoto", photoimage, id(aggimage), colormode, id(bbox_array)) _tkinter.TclError: this isn't a Tk application Please can someone help me out of this problem. With my regards, partha From sandra.baror at gmail.com Sat Oct 11 03:59:38 2014 From: sandra.baror at gmail.com (sandra.baror at gmail.com) Date: Sat, 11 Oct 2014 00:59:38 -0700 (PDT) Subject: Cant get my tshark pharse to work In-Reply-To: References: Message-ID: <3d4596e9-f763-497b-918f-56fab2983754@googlegroups.com> On Thursday, October 9, 2014 9:46:10 PM UTC+3, Tal Bar-Or wrote: > Hello All, > > > > I am writing some code to get captured wiresahrk pcap file , using popen.subprocess and extract some table csv format related to SMB, but for some reason i can get the csv when using off-course regular cmd line its work > > The code as follow below , maybe someone with exprience with such can help > > Please advice > > Thanks > > > > import socket,subprocess > > import os,time > > > > sharkCall = ["tshark","-i" ,"1", "-w",os.getcwd() +'/smbsession.pcap'] > > sharkProc = subprocess.Popen(sharkCall,executable="C:/Program Files/Wireshark/tshark.exe") > > localip = socket.gethostbyname(socket.gethostname()) > > > > a = 0 > > > > while a ==0: > > a = sharkProc.pid > > time.sleep(2) > > > > > > ipflt = '' > > > > listip = socket.gethostbyname_ex('media.isilon.gefen.local')[2] > > > > for ip in listip: > > ipflt= ipflt+ "ip.addr==" + ip + "||" > > ipflt = ipflt + "ip.addr==" + localip > > > > if ipflt.endswith('||'): > > ipflt = ipflt[:-2] > > print (ipflt) > > b= os.path.getsize("//media.isilon.gofn.local/Media/New Text Document.txt") > > #statinfo > > print(b) > > > > > > #time.sleep(2) > > sharkProc.kill() > > tsharkCall = ["tshark","-r",'C:/traces_test/smbsession.pcap',"-Y",ipflt,"-T","fields","-e","ip.src","-e","ip.dst","-e","smb.file",\ > > "-e","smb.path","-e","smb.time","-e","tcp.time_delta", "-E","header=y","-E","separator=,","-E","quote=d","-E","occurrence=f",\ > > '> '+os.getcwd() +'/tracetemp.csv'] > > tsharkProc = subprocess.Popen(tsharkCall,executable="C:/Program Files/Wireshark/tshark.exe") > > > > a = 0 > > > > while a ==0: > > a = tsharkProc.pid > > time.sleep(2) > > print ('Finished') the problematic code where sharkCall = ["tshark","-r",'C:/traces_test/smbsession.pcap',"-Y",ipflt,"-T","fields","-e","ip.src","-e","ip.dst","-e","smb.file",\ "-e","smb.path","-e","smb.time","-e","tcp.time_delta", "-E","header=y","-E","separator=,","-E","quote=d","-E","occurrence=f",\ '> '+os.getcwd() +'/tracetemp.csv'] tsharkProc = subprocess.Popen(tsharkCall,executable="C:/Program Files/Wireshark/tshark.exe") i changed it to as follows below and now its works , thanks tsharkCall = '"' +os.environ["ProgramFiles"]+'/Wireshark/tshark.exe"' +" -r "+os.getcwd() +'/smbsession.pcap'+" -Y "+'"'+toto+'"'+" -T fields -e ip.src -e ip.dst -e smb.file -e smb.path -e smb.time -e tcp.time_delta -E header=y -E separator=, -E quote=d -E occurrence=f > "+os.getcwd() +"/trac_session.csv" tsharkProc = subprocess.Popen(tsharkCall,shell=True) From auriocus at gmx.de Sat Oct 11 05:37:51 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Sat, 11 Oct 2014 11:37:51 +0200 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> <877g099dgb.fsf@elektro.pacujo.net> <87y4sneok9.fsf@elektro.pacujo.net> Message-ID: Am 10.10.14 22:05, schrieb alister: > Would the French tolerate me using an alternative Variant (Canadian or > Carribean)? I think not > > UK English as spoken in England is the definitive version. The clue is in > the Name - English not American I tend to agree that British English is the "correct" version for me, since I'm European, though not British. The usage of -ise in verbs, however, is a newer attempt to set the British English apart from the American: http://blog.oxforddictionaries.com/2011/03/ize-or-ise/ and http://www.oxforddictionaries.com/words/ize-ise-or-yse Being a non-native English speaker/writer, I myself stick to the recommendations of the Oxford dictionary. Christian From marko at pacujo.net Sat Oct 11 06:33:44 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 11 Oct 2014 13:33:44 +0300 Subject: [OT] spelling colour / color was Re: Toggle References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5437868a$0$13011$c3e8da3$5496439d@news.astraweb.com> <877g08nsno.fsf@elektro.pacujo.net> <87y4somc3q.fsf@elektro.pacujo.net> Message-ID: <87y4sm3ng7.fsf@elektro.pacujo.net> Dennis Lee Bieber : > And then there is REXX... Which deliberately has both centre() and > center() in its standard library -- and they do the same thing... I'm getting a new appreciation for Lisp's age-old "car" and "cdr". The scientists have done this international thing for centuries. Their single-letter naming might be the secret of their glorious success. Obscure acronyms for the win. Marko From rosuav at gmail.com Sat Oct 11 07:03:20 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 11 Oct 2014 22:03:20 +1100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: <87y4sm3ng7.fsf@elektro.pacujo.net> References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5437868a$0$13011$c3e8da3$5496439d@news.astraweb.com> <877g08nsno.fsf@elektro.pacujo.net> <87y4somc3q.fsf@elektro.pacujo.net> <87y4sm3ng7.fsf@elektro.pacujo.net> Message-ID: On Sat, Oct 11, 2014 at 9:33 PM, Marko Rauhamaa wrote: > I'm getting a new appreciation for Lisp's age-old "car" and "cdr". > > The scientists have done this international thing for centuries. Their > single-letter naming might be the secret of their glorious success. > > Obscure acronyms for the win. If it means nothing to anybody, nobody's at a disadvantage compared to anyone else... ChrisA From mal at europython.eu Sat Oct 11 07:18:28 2014 From: mal at europython.eu (M.-A. Lemburg) Date: Sat, 11 Oct 2014 13:18:28 +0200 Subject: EuroPython Workgroups: Call for Volunteers Message-ID: <54391204.6020102@europython.eu> (This post is also available for online reading at: http://www.europython-society.org/post/99718376575/europython-workgroups-call-for-volunteers) Dear EuroPython community, the EuroPython Society is happy to announce a new organizational concept that we'd like to put in place for the next EuroPython conferences: the EuroPython Workgroups. Motivation ---------- In the past, the EPS granted permission to use the brand to local organizers based on a set of requirements, and the local organizing team then had to run the event in collaboration with the EPS. Most of the work was centered around the local team. This model no longer scales and doesn?t encourage the community to take part in the organization process. The workload and the financial risks of running such a big conference for the local teams is very high. Proposed New Structure (Workgroups) ----------------------------------- The biggest change is the introduction of permanent workgroups integrated with EPS and its activities. This change is designed to address the issues mentioned above in a way which allows our community to get more involved, while at the same time reducing the risk and work load on individual teams. Workgroups will be coordinated by the EuroPython Society board based on the community feedback and proposals, from their definition and creation to their implementation. The key workgroups we have identified so far are: * Conference Administration (contracts, venue contact, ticket support, satellite conferences, legal support, insurance, licensing) * Finance (budget, controlling, accounting, billing, invoicing, taxes, payment system administration, Treasurer needs be part of this WG) * Sponsors (sponsor contacts, sponsor logistics, room/booth assignment, recruiting session, jobs fair, exhibit hall, startup row) * Communications (press, community relations, diversity/outreach/CoC, CoC contact, announcements, social media, attendee tools, volunteer coordination, mailing lists) * Support (helpdesk, attendee support contact, visa help, travel management, chat support for attendees) * Financial Aid (setup, grant selection, aid organisation) * Marketing/Design (brochures, advertisements, banners, flyers, travel guide, t-shirts, lanyards, badges, panels, logo) * Program (talk selection, scheduling, session chairs, sprint/openspace/keynote/lightning talks/poster session organization, Young Coders session, Python for Teachers) * Web (web site support, ticket system, administration, backups, payment system integration, hosting, chat support for attendees) * Media (video recording, live streaming, live translations, uploads to YouTube and archive.org) * On-site Team (on-site support, local contact, help with venue selection, help with catering selection, partner program, social events, buddy program, internet access, venue contact, catering contact, on-site logistics) All of these workgroups, except for the On-site Team, will remain active when changing location. We expect to keep institutional knowledge within the organization and make transitions to new locations easier by using this approach. The EuroPython Society collects and reviews the applications to each workgroup. The EPS board will then vote on the chair and a set of permanent workgroup members with (workgroup internal) voting rights and then have the workgroup chair appoint additional (non-voting) members as necessary. Workgroups will be confirmed/reestablished by board vote every year, this allows non-voting members to become voting members in the following year. Workgroups and board will update, coordinate and plan activities on a regular basis. While every workgroup will be responsible for its own coordination and establish a workflow that best fits its needs, we expect all workgroups to integrate and interact with other workgroups to create a productive work environment. To simplify and speed up the workgroup setup, we will create a set of workgroup guidelines which aim at collecting the institutional knowledge gathered over the years. We will put these guidelines up for comment in the coming weeks. Call for Volunteers ------------------- Please help us build EuroPython and keep making it better and better every year. If you want to help, please apply for one or more workgroups which you feel match your interests and experience. If you'd like to help, but don't have enough experience, yet are willing to learn, please apply as well. To apply please send an email to board at europython.eu with your details, the motivation for applying (basically why and how you think you could help) and the workgroup(s) you'd like to apply for. Just to clarify: We will issue a separate Call for Participation (CFP) for the On-site Team, so you don't need to apply for this workgroup before we have selected an On-site Team. Thank you, -- EuroPython Society From none at mailinator.com Sat Oct 11 07:45:07 2014 From: none at mailinator.com (mm0fmf) Date: Sat, 11 Oct 2014 12:45:07 +0100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> <877g099dgb.fsf@elektro.pacujo.net> <87y4sneok9.fsf@elektro.pacujo.net> Message-ID: <7L8_v.450636$NQ4.108421@fx26.am4> On 11/10/2014 10:37, Christian Gollwitzer wrote: > Being a non-native English speaker/writer, I myself stick to the > recommendations of the Oxford dictionary. > > Christian But you do realise the Oxford dictionary is different to English usage and is renowned for using what is known as Oxford spelling? You wont find -ize used by the BBC in content for the UK nor will you find British newspapers using it. The Oxford spellings are so far out on their own you can set en-GB as a language tag or en-GB-oed. From vs at it.uu.se Sat Oct 11 11:20:00 2014 From: vs at it.uu.se (Virgil Stokes) Date: Sat, 11 Oct 2014 17:20:00 +0200 Subject: Butterflow installation on windows Message-ID: <54394AA0.4060704@it.uu.se> The butterflow package (https://pypi.python.org/pypi/butterflow/0.1.4a1) has recently been released. I would like to know if anyone has been able to install it on a windows platform. From simon+python at bleah.co.uk Sat Oct 11 10:45:09 2014 From: simon+python at bleah.co.uk (Simon Ward) Date: Sat, 11 Oct 2014 15:45:09 +0100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> <877g099dgb.fsf@elektro.pacujo.net> <87y4sneok9.fsf@elektro.pacujo.net> Message-ID: <4f91261a-0363-469d-ba99-7a8bdfbcbe56@email.android.com> On 11 October 2014 10:37:51 BST, Christian Gollwitzer wrote: >I tend to agree that British English is the "correct" version for me, >since I'm European, though not British. > >The usage of -ise in verbs, however, is a newer attempt to set the >British English apart from the American: > > http://blog.oxforddictionaries.com/2011/03/ize-or-ise/ and > http://www.oxforddictionaries.com/words/ize-ise-or-yse > >Being a non-native English speaker/writer, I myself stick to the >recommendations of the Oxford dictionary. Oxford Dictionaries online is not just British English, it derives common usage from a corpus of English used around the world: http://www.oxforddictionaries.com/words/what-are-the-main-differences-between-the-oed-and-odo http://www.oxforddictionaries.com/words/the-oxford-english-corpus Simon From buzzard at invalid.invalid Sat Oct 11 11:26:43 2014 From: buzzard at invalid.invalid (duncan smith) Date: Sat, 11 Oct 2014 16:26:43 +0100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: <7L8_v.450636$NQ4.108421@fx26.am4> References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> <877g099dgb.fsf@elektro.pacujo.net> <87y4sneok9.fsf@elektro.pacujo.net> <7L8_v.450636$NQ4.108421@fx26.am4> Message-ID: <54394c37$0$48107$862e30e2@ngroups.net> On 11/10/14 12:45, mm0fmf wrote: > On 11/10/2014 10:37, Christian Gollwitzer wrote: >> Being a non-native English speaker/writer, I myself stick to the >> recommendations of the Oxford dictionary. >> >> Christian > > But you do realise the Oxford dictionary is different to English usage > and is renowned for using what is known as Oxford spelling? You wont > find -ize used by the BBC in content for the UK nor will you find > British newspapers using it. > [snip] I don't know about the BBC etc. but it pretty much corresponds to my usage. I tend to use 'ize', but not for words like analyse (where for whatever reason it just doesn't look right with a 'z' - maybe because realization is fine but analyzis is not). I suspect some non-US English speakers, when faced with the option, assume the 'z' might be a US spelling and opt for the 's' instead. A useful rule of thumb perhaps, that might make 's' common usage for e.g. the BBC / newspapers. But 'z' is still used by some of us outside the media. The media have their own quirks when it comes to English. The BBC regularly use "top of" / "bottom of" in the sense of "start of" / "end of", but I don't know any British people who would (currently) use that in conversation. (This only started a few years ago, and the first time I heard it I had to work out what it meant from context.) Duncan From jab at math.brown.edu Sat Oct 11 13:42:55 2014 From: jab at math.brown.edu (jab at math.brown.edu) Date: Sat, 11 Oct 2014 10:42:55 -0700 (PDT) Subject: bidict Message-ID: Dear comp.lang.python, I wrote a library called bidict providing a bidirectional mapping data structure a few years ago and got some great feedback from people here. Recently I put some more work into it and would love to get some feedback on the API, implementation, and whatever else I can do to help users find it and make sure it meets their needs. The code can be found at: https://github.com/jab/bidict And docs are at: http://bidict.readthedocs.org Constructive feedback gratefully received. Thanks for reading. From wrw at mac.com Sat Oct 11 15:55:46 2014 From: wrw at mac.com (William Ray Wing) Date: Sat, 11 Oct 2014 15:55:46 -0400 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> <877g099dgb.fsf@elektro.pacujo.net> <87y4sneok9.fsf@elektro.pacujo.net> <7L8_v.450636$NQ4.108421@fx26.am4> <54394c37$0$48107$862e30e2@ngroups.net> Message-ID: <5CFA4996-5718-49B7-B8C1-21F70F33054B@mac.com> On Oct 11, 2014, at 3:20 PM, Dennis Lee Bieber wrote: > On Sat, 11 Oct 2014 16:26:43 +0100, duncan smith > declaimed the following: > > >> The media have their own quirks when it comes to English. The BBC >> regularly use "top of" / "bottom of" in the sense of "start of" / "end >> of", but I don't know any British people who would (currently) use that >> in conversation. (This only started a few years ago, and the first time >> I heard it I had to work out what it meant from context.) >> > > That usage I think is ancient... I'm sure I've heard it back when there > was a reasonable BBC World Service (along with VOA, Radio Netherlands, and > etc. running on Short Wave"... > > Top of the Hour? Of course, musicians have used it for years, as in ?Take it from the top.? And (with reference to the earlier discussion), just because something is specified in the Oxford English Dictionary, doesn?t mean it is universally approved of. Take the ?Oxford Comma? for example. -Bill From timr at probo.com Sat Oct 11 16:55:30 2014 From: timr at probo.com (Tim Roberts) Date: Sat, 11 Oct 2014 13:55:30 -0700 Subject: Python 3.4.1 on W2K? References: <1412553844.20683.YahooMailNeo@web181605.mail.ne1.yahoo.com> Message-ID: Michael Torrie wrote: > >That's really interesting. I looked briefly at the page. How does your >python extension work with xywrite? Does it manipulate xywrite >documents or does it tie in at runtime with Xywrite somehow? If so, how >does it do this? Crossing the divide into a 16-bit app is pretty >impressive. Actually, Microsoft made it pretty easy to call 32-bit DLLs in a 16-bit process and vice versa. That's why many of us were surprised when they did not provide the same capability in the 32/64 transition. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From buzzard at invalid.invalid Sat Oct 11 19:40:42 2014 From: buzzard at invalid.invalid (duncan smith) Date: Sun, 12 Oct 2014 00:40:42 +0100 Subject: [OT] spelling colour / color was Re: Toggle In-Reply-To: References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> <877g099dgb.fsf@elektro.pacujo.net> <87y4sneok9.fsf@elektro.pacujo.net> <7L8_v.450636$NQ4.108421@fx26.am4> <54394c37$0$48107$862e30e2@ngroups.net> Message-ID: <5439bffe$0$48338$862e30e2@ngroups.net> On 11/10/14 20:55, William Ray Wing wrote: > On Oct 11, 2014, at 3:20 PM, Dennis Lee Bieber wrote: > >> On Sat, 11 Oct 2014 16:26:43 +0100, duncan smith >> declaimed the following: >> >> >>> The media have their own quirks when it comes to English. The BBC >>> regularly use "top of" / "bottom of" in the sense of "start of" / "end >>> of", but I don't know any British people who would (currently) use that >>> in conversation. (This only started a few years ago, and the first time >>> I heard it I had to work out what it meant from context.) >>> >> >> That usage I think is ancient... I'm sure I've heard it back when there >> was a reasonable BBC World Service (along with VOA, Radio Netherlands, and >> etc. running on Short Wave"... >> >> Top of the Hour? > > Of course, musicians have used it for years, as in ?Take it from the top.? > [snip] I think it must be a more recent thing with BBC (TV) presenters / newsreaders (I rarely listen to radio); or, at least, it has become a lot more common. I can see it makes perfect sense with e.g. sheet music. You start again at the top. It was the "top / bottom of the [TV] programme" that I didn't immediately get, because I was thinking of a timeline running left to right (perhaps rather than the script used by the presenters). Duncan From georg at python.org Sun Oct 12 03:38:31 2014 From: georg at python.org (Georg Brandl) Date: Sun, 12 Oct 2014 09:38:31 +0200 Subject: [RELEASED] Python 3.2.6, Python 3.3.6 Message-ID: <543A2FF7.5060207@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team, I'm happy to announce the release of Python 3.2.6 and 3.3.6. Both are security-fix releases, which are provided source-only on python.org. The list of security-related issues fixed in the releases is given in the changelogs: https://hg.python.org/cpython/raw-file/v3.2.6/Misc/NEWS https://hg.python.org/cpython/raw-file/v3.3.6/Misc/NEWS To download the releases visit one of: https://www.python.org/downloads/release/python-326/ https://www.python.org/downloads/release/python-336/ These are production versions, please report any bugs to http://bugs.python.org/ Enjoy! - -- Georg Brandl, Release Manager georg at python.org (on behalf of the entire python-dev team and contributors) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2 iEYEARECAAYFAlQ6L/cACgkQN9GcIYhpnLBxIwCeLqjXeIOxGA2vkjbkN5Ic6j2u 7WcAoKgFaB4drMX5ZOVUJ4VLyNTcfycN =KLlw -----END PGP SIGNATURE----- From rustompmody at gmail.com Sun Oct 12 04:37:09 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 12 Oct 2014 01:37:09 -0700 (PDT) Subject: Parse bad xml file In-Reply-To: References: <9bb1f027-dc72-43c1-9301-e2105225f75a@googlegroups.com> Message-ID: <5ec9e1d2-2951-43cd-9ec2-b8a0777be51c@googlegroups.com> On Friday, October 10, 2014 6:03:58 PM UTC+5:30, David Jobes wrote: > On Friday, October 10, 2014 8:21:17 AM UTC-4, Peter Otten wrote: > That did it, thank you, and in a lot fewer lines of code than i had, i was trying to use strings and regex. i will read up more on the xml.etree stuff. Those who parse xml/html with re's should read this -- http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 From rorocodeath at gmail.com Sun Oct 12 08:55:51 2014 From: rorocodeath at gmail.com (roro codeath) Date: Sun, 12 Oct 2014 20:55:51 +0800 Subject: TypeError: 'kwarg' is an invalid keyword argument for this function Message-ID: How to implement it in my class? class Str(str): def __init__(self, *args, **kwargs): pass Str('smth', kwarg='a') # How to implement in my class class C: def __init__(self): pass class C2(C): def __init__(self, *args, **kwargs): pass C2(kwarg='a') -------------- next part -------------- An HTML attachment was scrubbed... URL: From fomcl at yahoo.com Sun Oct 12 09:33:05 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Sun, 12 Oct 2014 13:33:05 +0000 (UTC) Subject: what is the easiest way to install multiple Python versions? Message-ID: <1749456658.291277.1413120785276.JavaMail.yahoo@jws10751.mail.gq1.yahoo.com> Hi, (sorry for cross-posting) A few days ago I needed to check whether some Python code ran with Python 2.6. What is the easiest way to install another Python version along side the default Python version? My own computer is Debian Linux 64 bit, but a platform-independent solution would be best. Possible solutions that I am aware of -make altinstall *). This is what I tried (see below), but not all modules could be built. I gave up because I was in a hurry -Pythonbrew. This project is dead -Deadsnakes -Anaconda -Tox? I only know this is as a cross-version/implementation test runner -Vagrant. This is what I eventually did, and this was very simple. I ran Ubuntu 10.0.4 LTS, which uses Python 2.6, and used Vagrant SSH to run and check my code in Python 2.6 (and I replaced a dict comprehension with a list comprehension, for example) - ... What is the recommended way? I don't expect/hope that I'd ever need something lower than Python 2.5 Thank you. Albert-Jan *) Make altinstall sudo apt-get install libsqlite3-dev libbz2-dev libgdbm-dev libncurses5-dev tk-dev zlib1g-dev wget https://www.python.org/ftp/python/2.6.8/Python-2.6.8.tgz tar -zxvf Python-2.6.8.tgz cd Python-2.6.8/ ./configure --prefix=/usr/local make # see 'failed stuff' below sudo make altinstall mkvirtualenv -p /usr/local/bin/python2.6 python26 # ImportError: No module named zlib # Failed stuff Failed to find the necessary bits to build these modules: _bsddb _curses _curses_panel _hashlib _sqlite3 _ssl bsddb185 bz2 dbm dl gdbm imageop linuxaudiodev ossaudiodev readline sunaudiodev zlib ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 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 juan0christian at gmail.com Sun Oct 12 09:49:17 2014 From: juan0christian at gmail.com (Juan Christian) Date: Sun, 12 Oct 2014 10:49:17 -0300 Subject: Flask and Django In-Reply-To: References: Message-ID: Anyone? On Fri, Oct 10, 2014 at 7:22 PM, Juan Christian wrote: > So, I'm already familiar with Flask and I fell comfortable using it, but I > see that no one uses it in "real business", everywhere I look regarding > jobs and web dev, people always talk about Django, no one mentions Flask, > no one uses Flask. > > I'm coding a personal tool using Flask but I feel the need to "convert" it > to Django because no ones seems to give attention to Flask, but no matter > what, I don't like, I don't fully understand Django, there are tons of > conventions, code generations and and too much red tape. > > Maybe that's because I feel the Django doc a bit confuse, I tried reading > (and practicing!) tutorials, official doc, books, and so on, but I can't > quite understand the whole thing. > > Is Flask really underestimated? Can you guys mention "big name" companies > or people using it? Does it have real value in real world business? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rustompmody at gmail.com Sun Oct 12 09:46:04 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 12 Oct 2014 06:46:04 -0700 (PDT) Subject: TypeError: 'kwarg' is an invalid keyword argument for this function In-Reply-To: References: Message-ID: Whats the problem?? Seems to work (python 2.7.8) [Ive added a line so that that you can see] class C: def __init__(self): pass class C2(C): def __init__(self, *args, **kwargs): self.dic = kwargs pass x = C2(kwarg='a') y = C2(kwarg='a', kwarg2=8) ======================== >>> x.dic {'kwarg': 'a'} >>> y.dic {'kwarg': 'a', 'kwarg2': 8} >>> From rosuav at gmail.com Sun Oct 12 10:06:07 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 01:06:07 +1100 Subject: Flask and Django In-Reply-To: References: Message-ID: On Sat, Oct 11, 2014 at 9:22 AM, Juan Christian wrote: > So, I'm already familiar with Flask and I fell comfortable using it, but I > see that no one uses it in "real business", everywhere I look regarding jobs > and web dev, people always talk about Django, no one mentions Flask, no one > uses Flask. I can't really say about job postings, but presumably you've done the searches and found that to be the case. But there are plenty of jobs around that don't specifically name the technologies you have to use. If you're asked to create a web site from nothing, it doesn't much matter what you use, as long as you get the job done. The other thing to note is that job postings and resumes form a feedback loop. Why bother mentioning Flask on your resume, if no employers ever ask about it? Why bother looking for Flask programmers, if nobody ever mentions having experience with it? My personal recommendation: Stick to Flask. It's a good system, and there's no reason to run away from it. (That said, I've yet to use Django, and I've used Flask for exactly one web site, which is why I didn't respond to you when you first posted.) Learn Django if you feel you need to, but don't avoid Flask just because nobody ever asks you about it for a job posting. ChrisA From rosuav at gmail.com Sun Oct 12 10:20:05 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 01:20:05 +1100 Subject: what is the easiest way to install multiple Python versions? In-Reply-To: <1749456658.291277.1413120785276.JavaMail.yahoo@jws10751.mail.gq1.yahoo.com> References: <1749456658.291277.1413120785276.JavaMail.yahoo@jws10751.mail.gq1.yahoo.com> Message-ID: On Mon, Oct 13, 2014 at 12:33 AM, Albert-Jan Roskam wrote: > *) Make altinstall > sudo apt-get install libsqlite3-dev libbz2-dev libgdbm-dev libncurses5-dev tk-dev zlib1g-dev > wget https://www.python.org/ftp/python/2.6.8/Python-2.6.8.tgz > tar -zxvf Python-2.6.8.tgz > cd Python-2.6.8/ > ./configure --prefix=/usr/local > make # see 'failed stuff' below > sudo make altinstall > mkvirtualenv -p /usr/local/bin/python2.6 python26 # ImportError: No module named zlib > > > # Failed stuff > Failed to find the necessary bits to build these modules: > _bsddb _curses _curses_panel > _hashlib _sqlite3 _ssl > bsddb185 bz2 dbm > dl gdbm imageop > linuxaudiodev ossaudiodev readline > sunaudiodev zlib Generally, this is the method I would recommend. For a start, run this: sudo apt-get build-dep python This is in place of your explicit "apt-get install" command; Debian keeps track of the dev packages needed to rebuild a given program, and will go fetch them for you. After that, just look at exactly what packages you're still lacking. You may well find that you don't have all the dependencies for all Python modules, as some of them might not be included in a basic "apt-get install python" installation; the solution is a bit more "apt-get build-dep" work, or some manual hunting down of dev packages (which may well be easier in some situations). But what version of Debian are you after, and why are you trying to build a 2.6.8 from source? On Debian Wheezy, getting hold of Python 2.6 should be as easy as: $ sudo apt-get install python2.6 I believe Squeeze ships 2.6 as its standard system Python, so it's even easier. Are you on the unreleased Jessie? And why do you even need 2.6 as opposed to 2.7? ChrisA From martijnperdaan at gmail.com Sun Oct 12 10:24:52 2014 From: martijnperdaan at gmail.com (martijnperdaan at gmail.com) Date: Sun, 12 Oct 2014 07:24:52 -0700 (PDT) Subject: what is wrong with this script and how do I get the value in a php script Message-ID: <05f27d81-372d-4242-bc62-e738e23680d4@googlegroups.com> what is wrong with this script and how do I get the value Rij1 and Rij2 and Rij3 and Rij4 and Rij5 and Rij6 in a php script import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN) GPIO.setup(18, GPIO.IN) GPIO.setup(21, GPIO.IN) GPIO.setup(22, GPIO.IN) GPIO.setup(23, GPIO.IN) GPIO.setup(24, GPIO.IN) Rij1 = 0 Rij2 = 0 Rij3 = 0 Rij4 = 0 Rij5 = 0 Rij6 = 0 while True: PRij1 = GPIO.input(17) PRij2 = GPIO.input(18) PRij3 = GPIO.input(21) PRij4 = GPIO.input(22) PRij5 = GPIO.input(23) PRij6 = GPIO.input(24) if (PRij1 == False): Rij1 = Rij1 + 1 while PRij1 == False: PRij1 = GPIO.input(17) if (PRij2 == False): Rij2 = Rij2 + 1 while PRij2 == False: PRij2 = GPIO.input(18) if (PRij3 == False): Rij3 = Rij3 + 1 while PRij3 == False: PRij3 = GPIO.input(21) if (PRij4 == False): Rij4 = Rij4 + 1 while PRij4 == False: PRij4 = GPIO.input(22) if (PRij5 == False): Rij5 = Rij5 + 1 while PRij5 == False: PRij5 = GPIO.input(23) if (PRij6 == False): Rij6 = Rij6 + 1 while PRij6 == False: PRij6 = GPIO.input(24) Totaal = Rij1 + Rij2 + Rij3 + Rij4 + Rij5 + Rij6 print Totaal From usethisid2014 at gmail.com Sun Oct 12 12:15:35 2014 From: usethisid2014 at gmail.com (Gayathri J) Date: Sun, 12 Oct 2014 21:45:35 +0530 Subject: what is the easiest way to install multiple Python versions? In-Reply-To: <1749456658.291277.1413120785276.JavaMail.yahoo@jws10751.mail.gq1.yahoo.com> References: <1749456658.291277.1413120785276.JavaMail.yahoo@jws10751.mail.gq1.yahoo.com> Message-ID: I have been using Anaconda's (Continnum) conda installation for system installation (python 2.7) and for python 3 conda lets us maintain diferent environments with different python and different combinations of other packages like numpy etc... sure not to disappoint! On 10/12/14, Albert-Jan Roskam wrote: > Hi, > > (sorry for cross-posting) > > A few days ago I needed to check whether some Python code ran with Python > 2.6. What is the easiest way to install another Python version along side > the default Python version? My own computer is Debian Linux 64 bit, but a > platform-independent solution would be best. > > Possible solutions that I am aware of > > -make altinstall *). This is what I tried (see below), but not all modules > could be built. I gave up because I was in a hurry > -Pythonbrew. This project is dead > -Deadsnakes > -Anaconda > -Tox? I only know this is as a cross-version/implementation test runner > -Vagrant. This is what I eventually did, and this was very simple. I ran > Ubuntu 10.0.4 LTS, which uses Python 2.6, and used Vagrant SSH to run and > check my code in Python 2.6 (and I replaced a dict comprehension with a list > comprehension, for example) > - ... > > What is the recommended way? I don't expect/hope that I'd ever need > something lower than Python 2.5 > > Thank you. > > Albert-Jan > > > *) Make altinstall > sudo apt-get install libsqlite3-dev libbz2-dev libgdbm-dev libncurses5-dev > tk-dev zlib1g-dev > wget https://www.python.org/ftp/python/2.6.8/Python-2.6.8.tgz > tar -zxvf Python-2.6.8.tgz > cd Python-2.6.8/ > ./configure --prefix=/usr/local > make # see 'failed stuff' below > sudo make altinstall > mkvirtualenv -p /usr/local/bin/python2.6 python26 # ImportError: No module > named zlib > > > # Failed stuff > Failed to find the necessary bits to build these modules: > _bsddb _curses _curses_panel > _hashlib _sqlite3 _ssl > bsddb185 bz2 dbm > dl gdbm imageop > linuxaudiodev ossaudiodev readline > sunaudiodev zlib > > > > > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > > 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? > > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ > -- > https://mail.python.org/mailman/listinfo/python-list > From pkpearson at nowhere.invalid Sun Oct 12 13:01:37 2014 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 12 Oct 2014 17:01:37 GMT Subject: what is wrong with this script and how do I get the value in a php script References: <05f27d81-372d-4242-bc62-e738e23680d4@googlegroups.com> Message-ID: On Sun, 12 Oct 2014 07:24:52 -0700 (PDT), martijnperdaan at gmail.com wrote: > what is wrong with this script and how do I get the value Rij1 and > Rij2 and Rij3 and Rij4 and Rij5 and Rij6 in a php script > > import RPi.GPIO as GPIO > GPIO.setmode(GPIO.BCM) > > GPIO.setup(17, GPIO.IN) > GPIO.setup(18, GPIO.IN) > GPIO.setup(21, GPIO.IN) > GPIO.setup(22, GPIO.IN) > GPIO.setup(23, GPIO.IN) > GPIO.setup(24, GPIO.IN) > > Rij1 = 0 > Rij2 = 0 > Rij3 = 0 > Rij4 = 0 > Rij5 = 0 > Rij6 = 0 > > > while True: > PRij1 = GPIO.input(17) > PRij2 = GPIO.input(18) > PRij3 = GPIO.input(21) > PRij4 = GPIO.input(22) > PRij5 = GPIO.input(23) > PRij6 = GPIO.input(24) > > if (PRij1 == False): > Rij1 = Rij1 + 1 > while PRij1 == False: > PRij1 = GPIO.input(17) [snip] I regret that I can't solve your problem, but perhaps I can move the conversation in a useful direction. If this is a question about RPi.GPIO, it would be good to phrase it as the simplest possible question about RPi.GPIO. If it's *not* a question about RPi.GPIO, it would be useful to replace the references to RPi.GPIO with some artificial substitute, so that people who don't have RPi.GPIO on their systems can contribute to the discussion. For example, I don't know what type of object is returned by GPIO.input. Your code appears to assume that it's True or False, but I don't know whether that's a valid assumption. When asking why something doesn't work, one greatly improves one's chances of getting a prompt and useful answer if one reveals precisely (1) what one desires, and (2) what one gets. Finally, the code you posted is indented in a way that is not legal Python, leaving people to guess at what you intended to post. And finally finally, why do you call this a PHP script? This is a Python newsgroup. -- To email me, substitute nowhere->runbox, invalid->com. From shivaji_tn at yahoo.com Sun Oct 12 13:08:00 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Sun, 12 Oct 2014 17:08:00 +0000 (UTC) Subject: while loop - multiple condition Message-ID: Why is the second part of while condition not being checked? while ans.lower() != 'yes' or ans.lower()[0] != 'y': ans = input('Do you like python?') My intention is if either of the conditions are true the loop should break. But the condition after 'or' doesn't seem to evaluate. Thanks, Shiva. From rosuav at gmail.com Sun Oct 12 13:13:04 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 04:13:04 +1100 Subject: while loop - multiple condition In-Reply-To: References: Message-ID: On Mon, Oct 13, 2014 at 4:08 AM, Shiva wrote: > Why is the second part of while condition not being checked? > > while ans.lower() != 'yes' or ans.lower()[0] != 'y': > ans = input('Do you like python?') > > > My intention is if either of the conditions are true the loop should break. > But the condition after 'or' doesn't seem to evaluate. The loop will continue while either part is true - that's what "or" means. Is that what you intended it to be doing? ChrisA From breamoreboy at yahoo.co.uk Sun Oct 12 13:20:06 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 12 Oct 2014 18:20:06 +0100 Subject: Butterflow installation on windows In-Reply-To: <54394AA0.4060704@it.uu.se> References: <54394AA0.4060704@it.uu.se> Message-ID: On 11/10/2014 16:20, Virgil Stokes wrote: > The butterflow package (https://pypi.python.org/pypi/butterflow/0.1.4a1) > has recently been released. I would like to know if anyone has been able > to install it on a windows platform. Short answer no. Long answer follows. c:\Users\Mark\PythonIssues>pip install -U --pre butterflow Downloading/unpacking butterflow Downloading butterflow-0.1.4a1.tar.gz Running setup.py (path:C:\Users\Mark\AppData\Local\Temp\pip_build_Mark\butterflow\setup.py) egg_info for package butterflow Traceback (most recent call last): File "", line 17, in File "C:\Users\Mark\AppData\Local\Temp\pip_build_Mark\butterflow\setup.py", line 287, in py_includes = pkg_config_res('--cflags', 'python2') File "C:\Users\Mark\AppData\Local\Temp\pip_build_Mark\butterflow\setup.py", line 205, in pkg_config_res env=get_extra_envs()).stdout.read() File "C:\Python34\lib\subprocess.py", line 858, in __init__ restore_signals, start_new_session) File "C:\Python34\lib\subprocess.py", line 1111, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified Complete output from command python setup.py egg_info: Traceback (most recent call last): File "", line 17, in File "C:\Users\Mark\AppData\Local\Temp\pip_build_Mark\butterflow\setup.py", line 287, in py_includes = pkg_config_res('--cflags', 'python2') File "C:\Users\Mark\AppData\Local\Temp\pip_build_Mark\butterflow\setup.py", line 205, in pkg_config_res env=get_extra_envs()).stdout.read() File "C:\Python34\lib\subprocess.py", line 858, in __init__ restore_signals, start_new_session) File "C:\Python34\lib\subprocess.py", line 1111, in _execute_child startupinfo) FileNotFoundError: [WinError 2] The system cannot find the file specified ---------------------------------------- Cleaning up... Command python setup.py egg_info failed with error code 1 in C:\Users\Mark\AppData\Local\Temp\pip_build_Mark\butterflow Storing debug log for failure in C:\Users\Mark\pip\pip.log Quoting from http://pip.readthedocs.org/en/latest/reference/pip_install.html#options for the --pre flag "Include pre-release and development versions. By default, pip only finds stable versions." Looking at the output above and at the URL you quote I doubt that it'll work for me as it seems to be Python 2 only. The URL also lists a load of dependancies and I've no idea whether or not you could get them for Windows or not. There's only one way to find out, so would you like to give it a go and let us know how you get on? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From shivaji_tn at yahoo.com Sun Oct 12 13:21:02 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Sun, 12 Oct 2014 17:21:02 +0000 (UTC) Subject: while loop - multiple condition References: Message-ID: > The loop will continue while either part is true - that's what "or" > means. Is that what you intended it to be doing? > > ChrisA > Yes......however, the second part of the or condition doesn't get evaluated. So if I enter a 'y' - I expect the second part to evaluate and the loop to break - but that doesn't seem to happen. From roy at panix.com Sun Oct 12 13:28:35 2014 From: roy at panix.com (Roy Smith) Date: Sun, 12 Oct 2014 13:28:35 -0400 Subject: while loop - multiple condition References: Message-ID: In article , Shiva wrote: > Why is the second part of while condition not being checked? > > while ans.lower() != 'yes' or ans.lower()[0] != 'y': > ans = input('Do you like python?') > > > My intention is if either of the conditions are true the loop should break. > But the condition after 'or' doesn't seem to evaluate. A general rule of programming (be it Python or any other language) is to break up complicated code into smaller pieces which can be understood and tested in isolation. Your 'while' condition is kind of hairy. There's a couple of complicated expressions, a logical conjuction, and two different negated comparisons. That's a lot to understand all at once. I would factor that out into a little function: ------------------------------------------------------- def is_yes(answer): if answer.lower() == 'yes': return True if answer.lower()[0] == 'y': return True return False while is_yes(ans): ans = input('Do you like python?') ------------------------------------------------------- Now, you can play around with your is_yes() function in an interactive session and see what it returns for various inputs, in isolation from the rest of your program: print is_yes('y') print is_yes('yes') print is_yes('no') print is_yes('you bet your sweet bippy') From rosuav at gmail.com Sun Oct 12 13:31:47 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 04:31:47 +1100 Subject: while loop - multiple condition In-Reply-To: References: Message-ID: On Mon, Oct 13, 2014 at 4:21 AM, Shiva wrote: >> The loop will continue while either part is true - that's what "or" >> means. Is that what you intended it to be doing? >> >> ChrisA >> > > > Yes......however, the second part of the or condition doesn't get evaluated. > So if I enter a 'y' - I expect the second part to evaluate and the loop to > break - but that doesn't seem to happen. Break it down into separate parts and have a look at what's happening. while ans.lower() != 'yes' or ans.lower()[0] != 'y': ans = input('Do you like python?') print("ans.lower() = {!r}; first cond = {!r}, second cond {!r}, disjunction {!r}".format( ans.lower(), (ans.lower() != 'yes'), (ans.lower()[0] != 'y'), (ans.lower() != 'yes' or ans.lower()[0] != 'y') )) The while loop will continue so long as the disjunction is True. See what it's actually doing. This is fundamental Boolean logic, a basic skill of programming. You're going to need to master this. Look at the different pieces, and get your head around what the 'or' operator actually does. ChrisA From shivaji_tn at yahoo.com Sun Oct 12 13:59:25 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Sun, 12 Oct 2014 17:59:25 +0000 (UTC) Subject: while loop - multiple condition References: Message-ID: Bit confusing to use in While loop - Should have used the 'and' condition instead of OR- then it works fine. for OR both condition need to be false to produce a false output and break the loop. More of SET operations. Thanks, Shiva From rosuav at gmail.com Sun Oct 12 14:03:31 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 05:03:31 +1100 Subject: while loop - multiple condition In-Reply-To: References: Message-ID: On Mon, Oct 13, 2014 at 4:59 AM, Shiva wrote: > Bit confusing to use in While loop - Should have used the 'and' condition > instead of OR- then it works fine. > for OR both condition need to be false to produce a false output and break > the loop. Correct, what you're looking for here is indeed an 'and' (also called a conjunction, as opposed to the disjunction of 'or'). Both operators are important; and you need to understand what they do so you know when to use each. ChrisA From denismfmcmahon at gmail.com Sun Oct 12 14:36:08 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sun, 12 Oct 2014 18:36:08 +0000 (UTC) Subject: what is wrong with this script and how do I get the value in a php script References: <05f27d81-372d-4242-bc62-e738e23680d4@googlegroups.com> Message-ID: On Sun, 12 Oct 2014 07:24:52 -0700, martijnperdaan wrote: > what is wrong with this script and how do I get the value Rij1 and Rij2 > and Rij3 and Rij4 and Rij5 and Rij6 in a php script I can see several pythonic errors in your script, however as for "what is wrong", I see no indication from you of what you expect it to do, what output you expect, what error messages you get when you try and run it etc. Perhaps a better subject would have been "how to read gpio on raspberry pi" It also helps if you can reduce your code example to the minimum needed to demonstrate the error. In this case, I would suggest that once you can read one input correctly, you should be able to expand that code to read all inputs. The code below might help (uses 2.x style print): import RPi.GPIO as GPIO GPIO.setmode(mode) GPIO.setup(17, GPIO.IN) if GPIO.input(17) == GPIO.HIGH: print True else: print False -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Sun Oct 12 14:43:10 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 05:43:10 +1100 Subject: Toggle In-Reply-To: <543acaa2$0$12115$b1db1813$79461190@news.astraweb.com> References: <9MxZv.411008$J62.18700@fx03.am4> <543acaa2$0$12115$b1db1813$79461190@news.astraweb.com> Message-ID: On Mon, Oct 13, 2014 at 5:38 AM, Tony the Tiger wrote: >> colour = 'red' if colour == 'blue' else 'blue' > > I call that a subtle bug that most likely will jump up and bite your > behind when you least expect it. More generally, I'd say that this is solving a (very) slightly different problem: it's providing a "toggle with default" feature, where the part after the else is the default. If you don't want a default, that's a bug. I've known times when that default makes life a lot easier, in which case it'd be a feature. ChrisA From ian.g.kelly at gmail.com Sun Oct 12 14:45:14 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sun, 12 Oct 2014 12:45:14 -0600 Subject: TypeError: 'kwarg' is an invalid keyword argument for this function In-Reply-To: References: Message-ID: On Sun, Oct 12, 2014 at 6:55 AM, roro codeath wrote: > How to implement it in my class? > > class Str(str): > def __init__(self, *args, **kwargs): > pass > > Str('smth', kwarg='a') The error is coming from the __new__ method. Because str is an immutable type, you should override the __new__ method, not __init__. Example: class Str(str): def __new__(cls, *args, **kwargs): return super().__new__(cls, args[0]) >>> Str('smth', kwarg='a') 'smth' From marko at pacujo.net Sun Oct 12 15:16:56 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 12 Oct 2014 22:16:56 +0300 Subject: while loop - multiple condition References: Message-ID: <878uklcd3r.fsf@elektro.pacujo.net> Chris Angelico : > On Mon, Oct 13, 2014 at 4:59 AM, Shiva > wrote: >> Bit confusing to use in While loop - Should have used the 'and' condition >> instead of OR- then it works fine. >> for OR both condition need to be false to produce a false output and break >> the loop. > > Correct, what you're looking for here is indeed an 'and' (also called > a conjunction, as opposed to the disjunction of 'or'). Both operators > are important; and you need to understand what they do so you know > when to use each. The corrected version while ans.lower() != 'yes' and ans.lower()[0] != 'y': ans = input('Do you like python?') is equivalent with while ans.lower()[0] != 'y': ans = input('Do you like python?') Marko From rosuav at gmail.com Sun Oct 12 15:22:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 06:22:24 +1100 Subject: while loop - multiple condition In-Reply-To: <878uklcd3r.fsf@elektro.pacujo.net> References: <878uklcd3r.fsf@elektro.pacujo.net> Message-ID: On Mon, Oct 13, 2014 at 6:16 AM, Marko Rauhamaa wrote: > The corrected version > > while ans.lower() != 'yes' and ans.lower()[0] != 'y': > ans = input('Do you like python?') > > is equivalent with > > while ans.lower()[0] != 'y': It's true that the first part is redundant, but trimming that out wouldn't have taught the OP about boolean logic :) ChrisA From denismfmcmahon at gmail.com Sun Oct 12 15:35:35 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sun, 12 Oct 2014 19:35:35 +0000 (UTC) Subject: while loop - multiple condition References: Message-ID: On Sun, 12 Oct 2014 17:08:00 +0000, Shiva wrote: > while ans.lower() != 'yes' or ans.lower()[0] != 'y': while ans.lower() is not equal to "yes" or ans.lower()[0] is not equal to "y" the loop will continue to run Note that if ans.lower() == 'y', then the first clause ( ans.lower() != 'yes' ) is true, so the loop will continue to run, ignoring the result of the second clause ( ans.lower()[0] != 'y' ), This will also be the case if you reverse the order of the clauses. It seems that you need a better understanding of combinatorial logic, perhaps http://www.ee.surrey.ac.uk/Projects/Labview/boolalgebra/ index.html#booleantheorems will help. -- Denis McMahon, denismfmcmahon at gmail.com From ryanshuell at gmail.com Sun Oct 12 16:17:58 2014 From: ryanshuell at gmail.com (Ryan Shuell) Date: Sun, 12 Oct 2014 13:17:58 -0700 (PDT) Subject: How to install and run a script? Message-ID: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> I'm an absolute noob to Python, although I have been programming in several other languages for over 10 years. I'm trying to install and run some scripts, and I'm not having much success. I followed the steps at this site. https://docs.python.org/2/install/ I have Python 2.7.6 Shell. If I type this: python setup.py install I get this: SyntaxError: invalid syntax If I try this: setup.py beautifulsoup I get this: SyntaxError: invalid syntax If I got to File > Open . . . . navigate to a folder and open the setup.py file and hit F5 . . . . it looks like it runs, but I can't tell what it does for sure, and then nothing works after that. For instance, I downloaded something called 'Flask'. I put that folder in my Python27 folder, and typed 'pip install Flask' and I keep getting errors. Any idea how to run a simple program??? From rosuav at gmail.com Sun Oct 12 16:27:38 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 07:27:38 +1100 Subject: How to install and run a script? In-Reply-To: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> References: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> Message-ID: On Mon, Oct 13, 2014 at 7:17 AM, Ryan Shuell wrote: > I'm an absolute noob to Python, although I have been programming in several other languages for over 10 years. > > I'm trying to install and run some scripts, and I'm not having much success. > > I followed the steps at this site. > https://docs.python.org/2/install/ > > I have Python 2.7.6 Shell. > > If I type this: > python setup.py install > > I get this: > SyntaxError: invalid syntax Hi! The commands you're looking at need to be run from your regular shell; I'm guessing you may be on Windows, so that would be the command prompt (cmd.exe). But rather than playing with setup.py directly, you should now be able to use pip, which is also run from the command line: C:\>pip install flask C:\>\python27\Scripts\pip install flask The first version works if you've added the appropriate directories to your PATH, the second is where the executable is actually found. I have several Pythons installed, so I didn't let it put itself into PATH; chances are you can take the easy route. ChrisA From abhi.darkness at gmail.com Sun Oct 12 16:28:26 2014 From: abhi.darkness at gmail.com (Abhiram) Date: Mon, 13 Oct 2014 01:58:26 +0530 Subject: Fwd: How to install and run a script? References: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> Message-ID: <127FBA2B-B52E-4F26-A066-5148ADB81BD8@gmail.com> Begin forwarded message: > From: Ryan Shuell > Subject: How to install and run a script? > Date: 13 October 2014 1:47:58 am IST > To: python-list at python.org > > I'm an absolute noob to Python, although I have been programming in several other languages for over 10 years. > > I'm trying to install and run some scripts, and I'm not having much success. > > I followed the steps at this site. > https://docs.python.org/2/install/ > > I have Python 2.7.6 Shell. > > If I type this: > python setup.py install > > I get this: > SyntaxError: invalid syntax > Have you completed installation? If you type ?Python? in Cmd, or ?Python? in terminal, do you get the Python prompt ?>>>? ? My guess is that your Python installation?s executable isn?t in the Windows / Linux $PATH variable. Give us more details so we can help you out further. :) Thanks Abhiram ?Py,Py,Py your boat. Gently down the IOstream" -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Sun Oct 12 16:35:48 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 12 Oct 2014 21:35:48 +0100 Subject: How to install and run a script? In-Reply-To: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> References: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> Message-ID: On 12/10/2014 21:17, Ryan Shuell wrote: > I'm an absolute noob to Python, although I have been programming in several other languages for over 10 years. > > I'm trying to install and run some scripts, and I'm not having much success. > > I followed the steps at this site. > https://docs.python.org/2/install/ You're looking at the wrong docs. Having said that I'd just grab pip, see http://pip.readthedocs.org/en/latest/installing.html Once it's successfully installed just pip install beautifulsoup -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From python.list at tim.thechases.com Sun Oct 12 16:42:35 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 12 Oct 2014 15:42:35 -0500 Subject: while loop - multiple condition In-Reply-To: <878uklcd3r.fsf@elektro.pacujo.net> References: <878uklcd3r.fsf@elektro.pacujo.net> Message-ID: <20141012154235.767b21cc@bigbox.christie.dr> On 2014-10-12 22:16, Marko Rauhamaa wrote: > is equivalent with > > while ans.lower()[0] != 'y': > ans = input('Do you like python?') And still better improved with while ans[:1].lower() != 'y': ans = input('Do you like python?') in the event that len(ans)==0 (a situation which will crash the various current examples). It also only expends the effort to lowercase 0-or-1 characters, rather than lowercasing an entire string just to throw away everything except the first character. -tkc From steve+comp.lang.python at pearwood.info Sun Oct 12 18:56:02 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 13 Oct 2014 09:56:02 +1100 Subject: while loop - multiple condition References: <878uklcd3r.fsf@elektro.pacujo.net> Message-ID: <543b0706$0$13005$c3e8da3$5496439d@news.astraweb.com> Tim Chase wrote: > On 2014-10-12 22:16, Marko Rauhamaa wrote: >> is equivalent with >> >> while ans.lower()[0] != 'y': >> ans = input('Do you like python?') > > And still better improved with > > while ans[:1].lower() != 'y': > ans = input('Do you like python?') The intention is to loop forever until the victim breaks down and accepts that they like Python, by entering "yes" or "y". I'm pretty sure that entering "yellow" or "you've got to be kidding" should not break the loop. When you have multiple clauses in the condition, it's easier to reason about them if you write the clauses as positive statements rather than negative statements, that is, "something is true" rather than "something is not true", and then use `not` to reverse it if you want to loop *until* the overall condition is true. When checking for equality against multiple values, instead of: x == a or x == b or x == c it is usually easier to use `in`: x in (a, b, c) So we have: # loop so long as the victim answers "yes" or "y" while ans.lower() in ('yes', 'y'): ans = input('Do you like python? Well, do you?') # loop until the victim answers "yes" or "y" while not (ans.lower() in ('yes', 'y')): ans = input('Do you like python? Well, do you?') both of which work fine if the user stays mum by entering the empty string. You can also write: while ans.lower() not in ('yes', 'y'): ans = input('Do you like python? Well, do you?') if you prefer. In my opinion, that's the most readable version of all. One last note: if you are using Python 3.3 or better, you can support international text better by using the casefold() method rather than lower(). In this case, it won't make a difference, but the technically correct method for doing case-insensitive comparisons is to casefold both strings rather than lower- or upper-case them. -- Steven From tjreedy at udel.edu Sun Oct 12 20:49:09 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 12 Oct 2014 20:49:09 -0400 Subject: TypeError: 'kwarg' is an invalid keyword argument for this function In-Reply-To: References: Message-ID: On 10/12/2014 2:45 PM, Ian Kelly wrote: > On Sun, Oct 12, 2014 at 6:55 AM, roro codeath wrote: >> How to implement it in my class? >> >> class Str(str): >> def __init__(self, *args, **kwargs): >> pass >> >> Str('smth', kwarg='a') > > The error is coming from the __new__ method. Because str is an > immutable type, you should override the __new__ method, not __init__. or, if one is mere adding a method, do not add __new__ either. > Example: > > class Str(str): > def __new__(cls, *args, **kwargs): > return super().__new__(cls, args[0]) > >>>> Str('smth', kwarg='a') > 'smth' > -- Terry Jan Reedy From rosuav at gmail.com Sun Oct 12 20:51:02 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 11:51:02 +1100 Subject: while loop - multiple condition In-Reply-To: <6l7m3apud9b3jg4pid3p9rpvuun699m3gl@4ax.com> References: <6l7m3apud9b3jg4pid3p9rpvuun699m3gl@4ax.com> Message-ID: On Mon, Oct 13, 2014 at 11:43 AM, Dennis Lee Bieber wrote: > ONE: Python uses short circuit evaluation: for an OR, the second clause > is only looked at if the first clause is FALSE (for an AND, the first > clause has to be TRUE before the second is evaluated). Short-circuiting doesn't actually matter here, incidentally. It could be eagerly evaluated and nothing would be different. ChrisA From tjreedy at udel.edu Sun Oct 12 20:54:45 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 12 Oct 2014 20:54:45 -0400 Subject: what is the easiest way to install multiple Python versions? In-Reply-To: <1749456658.291277.1413120785276.JavaMail.yahoo@jws10751.mail.gq1.yahoo.com> References: <1749456658.291277.1413120785276.JavaMail.yahoo@jws10751.mail.gq1.yahoo.com> Message-ID: On 10/12/2014 9:33 AM, Albert-Jan Roskam wrote: > A few days ago I needed to check whether some Python code ran with > Python 2.6. What is the easiest way to install another Python version > along side the default Python version? My own computer is Debian > Linux 64 bit, but a platform-independent solution would be best. Installation is platform dependent. On Windows, the answer would simply be 'get the PSF x.y installer and run it'. -- Terry Jan Reedy From ryanshuell at gmail.com Sun Oct 12 22:05:01 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Sun, 12 Oct 2014 19:05:01 -0700 (PDT) Subject: How to install and run a script? In-Reply-To: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> References: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> Message-ID: <6d282d09-fa5f-4d3a-aaed-5c15f8f9b56f@googlegroups.com> On Sunday, October 12, 2014 4:18:19 PM UTC-4, ryguy7272 wrote: > I'm an absolute noob to Python, although I have been programming in several other languages for over 10 years. > > > > I'm trying to install and run some scripts, and I'm not having much success. > > > > I followed the steps at this site. > > https://docs.python.org/2/install/ > > > > I have Python 2.7.6 Shell. > > > > If I type this: > > python setup.py install > > > > I get this: > > SyntaxError: invalid syntax > > > > > > If I try this: > > setup.py beautifulsoup > > > > I get this: > > SyntaxError: invalid syntax > > > > > > If I got to File > Open . . . . navigate to a folder and open the setup.py file and hit F5 . . . . it looks like it runs, but I can't tell what it does for sure, and then nothing works after that. For instance, I downloaded something called 'Flask'. I put that folder in my Python27 folder, and typed 'pip install Flask' and I keep getting errors. > > > > Any idea how to run a simple program??? Ahhhhh!!! I didn't know I needed to run it from the command prompt! Ok, not it makes sense, and everything works. Thanks to all! From rustompmody at gmail.com Sun Oct 12 22:31:28 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 12 Oct 2014 19:31:28 -0700 (PDT) Subject: what is the easiest way to install multiple Python versions? In-Reply-To: References: Message-ID: <2aad8f7f-3dbe-4bf5-9f16-93801c6d5394@googlegroups.com> On Sunday, October 12, 2014 7:06:14 PM UTC+5:30, Albert-Jan Roskam wrote: > Hi, > > A few days ago I needed to check whether some Python code ran with Python 2.6. What is the easiest way to install another Python version along side the default Python version? My own computer is Debian Linux 64 bit, but a platform-independent solution would be best. > > > > Possible solutions that I am aware of > > > > -make altinstall *). This is what I tried (see below), but not all modules could be built. I gave up because I was in a hurry > > -Pythonbrew. This project is dead > > -Deadsnakes > > -Anaconda > > -Tox? I only know this is as a cross-version/implementation test runner > > -Vagrant. This is what I eventually did, and this was very simple. I ran Ubuntu 10.0.4 LTS, which uses Python 2.6, and used Vagrant SSH to run and check my code in Python 2.6 (and I replaced a dict comprehension with a list comprehension, for example) Hearing a bit about docker nowadays. Here's why its supposedly better than a VM: https://www.docker.com/whatisdocker/ Downsides?? No idea! From ryanshuell at gmail.com Sun Oct 12 22:55:29 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Sun, 12 Oct 2014 19:55:29 -0700 (PDT) Subject: problem with pytz Message-ID: I just tried running the code from here. http://www.thealgoengineer.com/2014/download_sp500_data/ I got this error. Traceback (most recent call last): File "C:/Python27/stock_data.py", line 4, in import pytz ImportError: No module named pytz So, I got here and download the files. https://pypi.python.org/pypi/pytz/#downloads I run this: python setup.py install I get this error. python: can't open file 'setup.py': [Errno 2] No such file or directory I tried this: easy_install --upgrade pytz Now, that seems like it downloaded and installed. So, I re-run the program, and I get the same error I had initially. Traceback (most recent call last): File "C:/Python27/stock_data.py", line 4, in import pytz ImportError: No module named pytz I don't get it. I go to the path 'C:\Python27\pytz' and the folder is right there! It's right there! It's a little frustrating because all my problems seem to be exactly the same, which is running scripts that should run easily...bu nothing actually runs. What else do I need to do to make this thing work? From breamoreboy at yahoo.co.uk Sun Oct 12 23:15:35 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 13 Oct 2014 04:15:35 +0100 Subject: problem with pytz In-Reply-To: References: Message-ID: On 13/10/2014 03:55, ryguy7272 wrote: > I just tried running the code from here. > http://www.thealgoengineer.com/2014/download_sp500_data/ > > I got this error. > Traceback (most recent call last): > File "C:/Python27/stock_data.py", line 4, in Please don't put your code here, what happens when you upgrade your Python version? > import pytz > ImportError: No module named pytz > > So, I got here and download the files. > https://pypi.python.org/pypi/pytz/#downloads > > I run this: > python setup.py install > > I get this error. > python: can't open file 'setup.py': [Errno 2] No such file or directory > > I tried this: > easy_install --upgrade pytz > > > Now, that seems like it downloaded and installed. So, I re-run the program, and I get the same error I had initially. > Traceback (most recent call last): > File "C:/Python27/stock_data.py", line 4, in > import pytz > ImportError: No module named pytz > > > I don't get it. I go to the path 'C:\Python27\pytz' and the folder is right there! It's right there! It's a little frustrating because all my problems seem to be exactly the same, which is running scripts that should run easily...bu nothing actually runs. What else do I need to do to make this thing work? > It should be in c:\python27\lib\site-packages. It's also far easier to use pip to install code. It's already available as an option with 3.4 and I think will be automatically included with 3.5 Finally it looks as if you're using googlegroups. If that is the case would you please read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing and single line paragraphs. Better yet access this list via https://mail.python.org/mailman/listinfo/python-list, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ben+python at benfinney.id.au Mon Oct 13 02:36:47 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 13 Oct 2014 17:36:47 +1100 Subject: Caching: Access a local file, but ensure it is up-to-date from a remote URL Message-ID: <85r3ycxyps.fsf@benfinney.id.au> Howdy all, I'm hoping that the problem I currently have is one already solved, either in the Python standard library, or with some well-tested obvious code. A program I'm working on needs to access a set of files locally; they're just normal files. But those files are local cached copies of documents available at remote URLs ? each file has a canonical URL for that file's content. I'd like an API for ?get_file_from_cache? that looks something like:: file_urls = { "foo.txt": "http://example.org/spam/", "bar.data": "https://example.net/beans/flonk.xml", } for (filename, url) in file_urls.items(): infile = get_file_from_cache(filename, canonical=url) do_stuff_with(infile.read()) * If the local file's modification timestamp is not significantly earlier than the Last-Modified timestamp for the document at the corresponding URL, ?get_file_from_cache? just returns the file object without changing the file. * The local file might be out of date (its modification timestamp may be significantly older than the Last-Modified timestamp from the corresponding URL). In that case, ?get_file_from_cache? should first read the document's contents into the file, then return the file object. * The local file may not yet exist. In that case, ?get_file_from_cache? should first read the document content from the corresponding URL, create the local file, and then return the file object. * The remote URL may not be available for some reason. In that case, ?get_file_from_cache? should simply return the file object, or if that can't be done, raise an error. So this is something similar to an HTTP object cache. Except where those are usually URL-focussed with the local files a hidden implementation detail, I want an API that focusses on the local files, with the remote requests a hidden implementation detail. Does anything like this exist in the Python library, or as simple code using it? With or without the specifics of HTTP and URLs, is there some generic caching recipe already implemented with the standard library? This local file cache (ignoring the spcifics of URLs and network access) seems like exactly the kind of thing that is easy to get wrong in countless ways, and so should have a single obvious implementation available. Am I in luck? What do you advise? -- \ ?If consumers even know there's a DRM, what it is, and how it | `\ works, we've already failed.? ?Peter Lee, Disney corporation, | _o__) 2005 | Ben Finney From rosuav at gmail.com Mon Oct 13 03:51:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 18:51:24 +1100 Subject: Caching: Access a local file, but ensure it is up-to-date from a remote URL In-Reply-To: <85r3ycxyps.fsf@benfinney.id.au> References: <85r3ycxyps.fsf@benfinney.id.au> Message-ID: On Mon, Oct 13, 2014 at 5:36 PM, Ben Finney wrote: > So this is something similar to an HTTP object cache. Except where those > are usually URL-focussed with the local files a hidden implementation > detail, I want an API that focusses on the local files, with the remote > requests a hidden implementation detail. Potential issue: You may need some metadata storage as well as the actual files. Or can you just ignore the Varies header etc etc etc, and pretend that this URL represents a single blob of data no matter what? I'm also dubious about relying on FS timestamps for critical data, as it's very easy to bump the timestamp to current, which would make your program think that the contents are fresh; but if that's truly the only metadata needed, that might be safe to accept. One way you could possibly do this is to pick up a URL-based cache (even something stand-alone like Squid), and then create symlinks from your canonically-named local files to the implementation-detail storage space for the cache. Then you probe the URL and return its contents. That guarantees that you're playing nicely with the rules of HTTP (particularly if you have chained proxies, proxy authentication, etc, etc - if you're deploying this to arbitrary locations, that might be an issue), but at the expense of complexity. ChrisA From rosuav at gmail.com Mon Oct 13 03:54:11 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 18:54:11 +1100 Subject: what is the easiest way to install multiple Python versions? In-Reply-To: <2aad8f7f-3dbe-4bf5-9f16-93801c6d5394@googlegroups.com> References: <2aad8f7f-3dbe-4bf5-9f16-93801c6d5394@googlegroups.com> Message-ID: On Mon, Oct 13, 2014 at 1:31 PM, Rustom Mody wrote: > Hearing a bit about docker nowadays. > > Here's why its supposedly better than a VM: > https://www.docker.com/whatisdocker/ > > Downsides?? No idea! One obvious downside is that it doesn't allow guests to modify the OS at all. A VM gives you an entire OS, so you can use and manipulate anything. If you don't *need* all that flexibility, then a VM is paying an unnecessary cost, ergo Docker will have no downside. ChrisA From rustompmody at gmail.com Mon Oct 13 04:00:10 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 13 Oct 2014 01:00:10 -0700 (PDT) Subject: what is the easiest way to install multiple Python versions? In-Reply-To: References: <2aad8f7f-3dbe-4bf5-9f16-93801c6d5394@googlegroups.com> Message-ID: <75b69c05-a245-48c2-a910-a3e34ac5792b@googlegroups.com> On Monday, October 13, 2014 1:24:27 PM UTC+5:30, Chris Angelico wrote: > On Mon, Oct 13, 2014 at 1:31 PM, Rustom Mody wrote: > > Hearing a bit about docker nowadays. > > Here's why its supposedly better than a VM: > > https://www.docker.com/whatisdocker/ > > Downsides?? No idea! > One obvious downside is that it doesn't allow guests to modify the OS > at all. A VM gives you an entire OS, so you can use and manipulate > anything. If you don't *need* all that flexibility, then a VM is > paying an unnecessary cost, ergo Docker will have no downside. Was talking of more pragmatic downsides eg "Does it really work?" :-) [Docker is still quite new] From alister.nospam.ware at ntlworld.com Mon Oct 13 04:09:49 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Mon, 13 Oct 2014 08:09:49 GMT Subject: Toggle References: <9MxZv.411008$J62.18700@fx03.am4> <543acaa2$0$12115$b1db1813$79461190@news.astraweb.com> Message-ID: On Mon, 13 Oct 2014 05:43:10 +1100, Chris Angelico wrote: > On Mon, Oct 13, 2014 at 5:38 AM, Tony the Tiger > wrote: >>> colour = 'red' if colour == 'blue' else 'blue' >> >> I call that a subtle bug that most likely will jump up and bite your >> behind when you least expect it. > > More generally, I'd say that this is solving a (very) slightly different > problem: it's providing a "toggle with default" feature, > where the part after the else is the default. If you don't want a > default, that's a bug. I've known times when that default makes life a > lot easier, in which case it'd be a feature. > > ChrisA if the value of colour is being set by user input & an incorrect value can be set the the error is in not validating user input and more complex solutions are definitely req. If the value is being set within the program itself and colour gets set to an incorrect value the bug lies elsewhere in the program. this looks like a simple requirement to alternate the colour of a GUI element so it is unlikely that incorrect values will be set. sometimes it is easy to get carried away & overcomplicate a simple task, I tend to follow the "KISS" principle wherever possible -- 40 isn't old. If you're a tree. From gelonida at gmail.com Mon Oct 13 04:31:56 2014 From: gelonida at gmail.com (Gelonida N) Date: Mon, 13 Oct 2014 10:31:56 +0200 Subject: while loop - multiple condition In-Reply-To: References: Message-ID: On 10/12/2014 07:08 PM, Shiva wrote: > while ans.lower() != 'yes' or ans.lower()[0] != 'y': > ans = input('Do you like python?') I personally consider double negations less intuitive than following: while not( ans.lower() == 'yes' and ans.lower()[0] == 'y' ): Reading this line yoy would have noticed as wellm that what you really wanted would have been: while not( ans.lower() == 'yes' or ans.lower()[0] == 'y' ): I would write the coder differently. With your code you have to pre-initialze the variable ans. I personally consider it also more 'intuitive' / easier to understand if I can see the break conditiion. to many nots / != / negations can be confusing as you noticed yourself. Taking into account the Steven's suggestion about using the 'in' expression it could be: while True: ans = input('Do you like python?') if ans.lower() in ('yes', 'y'): break From robin at reportlab.com Mon Oct 13 05:49:27 2014 From: robin at reportlab.com (Robin Becker) Date: Mon, 13 Oct 2014 10:49:27 +0100 Subject: windows 7 pysqlite build error Message-ID: <543BA027.8010504@chamonix.reportlab.co.uk> I am getting this error trying to use a python27 pip install of stuff which ends up requiring pysqlite>=2.6.3,<2.7 > building 'pysqlite2._sqlite' extension > > creating build\temp.win-amd64-2.7 > > creating build\temp.win-amd64-2.7\Release > > creating build\temp.win-amd64-2.7\Release\src > > c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\amd64\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -DMODULE_NAM > E=\"pysqlite2.dbapi2\" -DSQLITE_OMIT_LOAD_EXTENSION=1 -IC:\python27\include -IC:\Users\rptlab\tmp\tenv\PC /Tcsrc/ > module.c /Fobuild\temp.win-amd64-2.7\Release\src/module.obj > module.c > > c:\users\rptlab\tmp\tmcallister\build\pysqlite\src\connection.h(33) : fatal error C1083: Cannot open include file: 'sqli > te3.h': No such file or directory > > error: command 'c:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\BIN\\amd64\\cl.exe' failed with exit status 2 > > ---------------------------------------- > Cleaning up... I do have the various compilers installed and other extensions are building OK, so is this an error in pysqlite or in my general setup? The include path looks like it might relate to Python builds. I suppose it's feasible that pyqslite builds need to be installed specially. I don't remember this happening on my old win32 XP system, but that died and I now am forced to use 64bit win7. -- Robin Becker From davea at davea.name Mon Oct 13 06:04:20 2014 From: davea at davea.name (Dave Angel) Date: Mon, 13 Oct 2014 06:04:20 -0400 (EDT) Subject: TypeError: 'kwarg' is an invalid keyword argument for this function References: Message-ID: Ian Kelly Wrote in message: > On Sun, Oct 12, 2014 at 6:55 AM, roro codeath wrote: >> How to implement it in my class? >> >> class Str(str): >> def __init__(self, *args, **kwargs): >> pass >> >> Str('smth', kwarg='a') > > The error is coming from the __new__ method. Because str is an > immutable type, you should override the __new__ method, not __init__. > Example: > > class Str(str): > def __new__(cls, *args, **kwargs): > return super().__new__(cls, args[0]) > >>>> Str('smth', kwarg='a') > 'smth' > It would also help to spell it the same. In the OP's implementation, he defined kwargs, and tried to use it as kwarg. -- DaveA From __peter__ at web.de Mon Oct 13 07:33:00 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 13 Oct 2014 13:33 +0200 Subject: TypeError: 'kwarg' is an invalid keyword argument for this function References: Message-ID: Dave Angel wrote: > Ian Kelly Wrote in > message: >> On Sun, Oct 12, 2014 at 6:55 AM, roro codeath >> wrote: >>> How to implement it in my class? >>> >>> class Str(str): >>> def __init__(self, *args, **kwargs): >>> pass >>> >>> Str('smth', kwarg='a') >> >> The error is coming from the __new__ method. Because str is an >> immutable type, you should override the __new__ method, not __init__. >> Example: >> >> class Str(str): >> def __new__(cls, *args, **kwargs): >> return super().__new__(cls, args[0]) >> >>>>> Str('smth', kwarg='a') >> 'smth' >> > > It would also help to spell it the same. In the OP's > implementation, he defined kwargs, and tried to use it as > kwarg. That is consistent as should become clear when using something completely different: >>> class Str(str): ... def __init__(self, *args, **kwargs): pass ... >>> Str("smth", alpha="beta") Traceback (most recent call last): File "", line 1, in TypeError: 'alpha' is an invalid keyword argument for this function From venugopal.reddy at tspl.com Mon Oct 13 07:39:33 2014 From: venugopal.reddy at tspl.com (Venugopal Reddy) Date: Mon, 13 Oct 2014 04:39:33 -0700 (PDT) Subject: Jython or Pyton issue-- Kindly Help me.... Message-ID: <91eb3378-958d-45e0-8741-a800ae681260@googlegroups.com> Dear All, How to write a program for reading or parsing the XML file in Sub root Wise. For ex: Below XMl, I want to read/ parse first country details and here also two year tag values are there.. Here I need to read/parse first year value only measn '2008' Only..After that I need to read second country details. Please help me .. i am struggling to get this solution.. 1 2008 2009> 141100 4 2011 59900 68 2011 13600 From rosuav at gmail.com Mon Oct 13 07:59:00 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 13 Oct 2014 22:59:00 +1100 Subject: while loop - multiple condition In-Reply-To: References: Message-ID: On Mon, Oct 13, 2014 at 7:31 PM, Gelonida N wrote: > Taking into account the Steven's suggestion about using the 'in' expression > it could be: > > > while True: > ans = input('Do you like python?') > if ans.lower() in ('yes', 'y'): > break Or, even simpler: Use an active condition. while input('Do you like python?') not in ('yes', 'y'): pass ChrisA From marko at pacujo.net Mon Oct 13 08:09:19 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Mon, 13 Oct 2014 15:09:19 +0300 Subject: while loop - multiple condition References: Message-ID: <87d29wmas0.fsf@elektro.pacujo.net> Chris Angelico : > Or, even simpler: Use an active condition. > > while input('Do you like python?') not in ('yes', 'y'): pass Instead of the traditional "pull" technology, you could take advantage of the state-of-the-art "push" approach: print("You must love python -- everybody does!") Marko From skip.montanaro at gmail.com Mon Oct 13 08:10:09 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Mon, 13 Oct 2014 07:10:09 -0500 Subject: while loop - multiple condition In-Reply-To: References: Message-ID: On Mon, Oct 13, 2014 at 6:59 AM, Chris Angelico wrote: > while input('Do you like python?') not in ('yes', 'y'): pass Unfortunately, you probably have to account for people who SHOUT: while input('Do you like python?').lower() not in ('yes', 'y'): pass Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Mon Oct 13 09:46:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 14 Oct 2014 00:46:53 +1100 Subject: while loop - multiple condition In-Reply-To: References: Message-ID: On Mon, Oct 13, 2014 at 11:10 PM, Skip Montanaro wrote: > On Mon, Oct 13, 2014 at 6:59 AM, Chris Angelico wrote: >> >> while input('Do you like python?') not in ('yes', 'y'): pass > > > Unfortunately, you probably have to account for people who SHOUT: > > while input('Do you like python?').lower() not in ('yes', 'y'): pass > > Welcome to collaborative editing. I make a change and introduce a bug. Fortunately, someone else can, just like that, fix that bug. Thanks! :) ChrisA From rosuav at gmail.com Mon Oct 13 09:48:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 14 Oct 2014 00:48:25 +1100 Subject: while loop - multiple condition In-Reply-To: <87d29wmas0.fsf@elektro.pacujo.net> References: <87d29wmas0.fsf@elektro.pacujo.net> Message-ID: On Mon, Oct 13, 2014 at 11:09 PM, Marko Rauhamaa wrote: > Chris Angelico : > >> Or, even simpler: Use an active condition. >> >> while input('Do you like python?') not in ('yes', 'y'): pass > > Instead of the traditional "pull" technology, you could take advantage > of the state-of-the-art "push" approach: > > print("You must love python -- everybody does!") Nay, there is love in excess. I thank heaven there are many pythons in England; but if thou lovest them all, I withdraw my thanks! -- Colonel Fairfax ChrisA From rosuav at gmail.com Mon Oct 13 09:50:27 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 14 Oct 2014 00:50:27 +1100 Subject: what is the easiest way to install multiple Python versions? In-Reply-To: <75b69c05-a245-48c2-a910-a3e34ac5792b@googlegroups.com> References: <2aad8f7f-3dbe-4bf5-9f16-93801c6d5394@googlegroups.com> <75b69c05-a245-48c2-a910-a3e34ac5792b@googlegroups.com> Message-ID: On Mon, Oct 13, 2014 at 7:00 PM, Rustom Mody wrote: > On Monday, October 13, 2014 1:24:27 PM UTC+5:30, Chris Angelico wrote: >> On Mon, Oct 13, 2014 at 1:31 PM, Rustom Mody wrote: >> > Hearing a bit about docker nowadays. >> > Here's why its supposedly better than a VM: >> > https://www.docker.com/whatisdocker/ >> > Downsides?? No idea! > >> One obvious downside is that it doesn't allow guests to modify the OS >> at all. A VM gives you an entire OS, so you can use and manipulate >> anything. If you don't *need* all that flexibility, then a VM is >> paying an unnecessary cost, ergo Docker will have no downside. > > Was talking of more pragmatic downsides eg "Does it really work?" :-) > [Docker is still quite new] Ah, I can't help you there. I've never used Docker. ChrisA From ned at nedbatchelder.com Mon Oct 13 10:31:28 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Mon, 13 Oct 2014 10:31:28 -0400 Subject: what is the easiest way to install multiple Python versions? In-Reply-To: <1749456658.291277.1413120785276.JavaMail.yahoo@jws10751.mail.gq1.yahoo.com> References: <1749456658.291277.1413120785276.JavaMail.yahoo@jws10751.mail.gq1.yahoo.com> Message-ID: On 10/12/14 9:33 AM, Albert-Jan Roskam wrote: > Hi, > > (sorry for cross-posting) > > A few days ago I needed to check whether some Python code ran with Python 2.6. What is the easiest way to install another Python version along side the default Python version? My own computer is Debian Linux 64 bit, but a platform-independent solution would be best. > > Possible solutions that I am aware of > > -make altinstall *). This is what I tried (see below), but not all modules could be built. I gave up because I was in a hurry > -Pythonbrew. This project is dead > -Deadsnakes > -Anaconda > -Tox? I only know this is as a cross-version/implementation test runner > -Vagrant. This is what I eventually did, and this was very simple. I ran Ubuntu 10.0.4 LTS, which uses Python 2.6, and used Vagrant SSH to run and check my code in Python 2.6 (and I replaced a dict comprehension with a list comprehension, for example) > - ... > > What is the recommended way? I don't expect/hope that I'd ever need something lower than Python 2.5 I use pythonz: http://saghul.github.io/pythonz/ It lets me specify not just the version I want, but the implementation I want: I can install CPython 2.6.1, PyPy 2.0.2, and Jython 2.5.3 all the same way. -- Ned Batchelder, http://nedbatchelder.com From ian.g.kelly at gmail.com Mon Oct 13 11:43:24 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 13 Oct 2014 09:43:24 -0600 Subject: Jython or Pyton issue-- Kindly Help me.... In-Reply-To: <91eb3378-958d-45e0-8741-a800ae681260@googlegroups.com> References: <91eb3378-958d-45e0-8741-a800ae681260@googlegroups.com> Message-ID: On Mon, Oct 13, 2014 at 5:39 AM, Venugopal Reddy wrote: > Dear All, > > How to write a program for reading or parsing the XML file in Sub root Wise. I don't know what "Sub root Wise" is. You can find an overview of Python's XML parsing interfaces at https://docs.python.org/2/library/xml.html. I would recommend using the ElementTree API unless you have a specific reason to use something else. From rgaddi at technologyhighland.invalid Mon Oct 13 12:12:48 2014 From: rgaddi at technologyhighland.invalid (Rob Gaddi) Date: Mon, 13 Oct 2014 09:12:48 -0700 Subject: while loop - multiple condition References: <878uklcd3r.fsf@elektro.pacujo.net> <543b0706$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: <20141013091248.1ffd94a0@rg.highlandtechnology.com> On Mon, 13 Oct 2014 09:56:02 +1100 Steven D'Aprano wrote: > > When you have multiple clauses in the condition, it's easier to reason about > them if you write the clauses as positive statements rather than negative > statements, that is, "something is true" rather than "something is not > true", and then use `not` to reverse it if you want to loop *until* the > overall condition is true. > I was just explaining this concept to a young pup the other day. De Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but the positive logic flavor is substantially less error-prone. People are fundamentally not as good at thinking about inverted logic. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From rustompmody at gmail.com Mon Oct 13 12:26:57 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 13 Oct 2014 09:26:57 -0700 (PDT) Subject: while loop - multiple condition In-Reply-To: <20141013091248.1ffd94a0@rg.highlandtechnology.com> References: <878uklcd3r.fsf@elektro.pacujo.net> <543b0706$0$13005$c3e8da3$5496439d@news.astraweb.com> <20141013091248.1ffd94a0@rg.highlandtechnology.com> Message-ID: On Monday, October 13, 2014 9:43:03 PM UTC+5:30, Rob Gaddi wrote: > On Mon, 13 Oct 2014 09:56:02 +1100 > Steven D'Aprano wrote: > > When you have multiple clauses in the condition, it's easier to reason about > > them if you write the clauses as positive statements rather than negative > > statements, that is, "something is true" rather than "something is not > > true", and then use `not` to reverse it if you want to loop *until* the > > overall condition is true. > I was just explaining this concept to a young pup the other day. De > Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but > the positive logic flavor is substantially less error-prone. People > are fundamentally not as good at thinking about inverted logic. Curious: Which of - (not (p and q)) - ((not p) or (not q)) is more positive (less negative)?? From rgaddi at technologyhighland.invalid Mon Oct 13 12:43:08 2014 From: rgaddi at technologyhighland.invalid (Rob Gaddi) Date: Mon, 13 Oct 2014 09:43:08 -0700 Subject: while loop - multiple condition References: <878uklcd3r.fsf@elektro.pacujo.net> <543b0706$0$13005$c3e8da3$5496439d@news.astraweb.com> <20141013091248.1ffd94a0@rg.highlandtechnology.com> Message-ID: <20141013094308.7d4ea20c@rg.highlandtechnology.com> On Mon, 13 Oct 2014 09:26:57 -0700 (PDT) Rustom Mody wrote: > On Monday, October 13, 2014 9:43:03 PM UTC+5:30, Rob Gaddi wrote: > > On Mon, 13 Oct 2014 09:56:02 +1100 > > Steven D'Aprano wrote: > > > When you have multiple clauses in the condition, it's easier to reason about > > > them if you write the clauses as positive statements rather than negative > > > statements, that is, "something is true" rather than "something is not > > > true", and then use `not` to reverse it if you want to loop *until* the > > > overall condition is true. > > > I was just explaining this concept to a young pup the other day. De > > Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but > > the positive logic flavor is substantially less error-prone. People > > are fundamentally not as good at thinking about inverted logic. > > Curious: Which of > > - (not (p and q)) > - ((not p) or (not q)) > > is more positive (less negative)?? The first is asking you to compare positive conditions (p and q) and negate the entire thing (NAND). The second asks you to think about the combination of two different "not true" pieces of logic (OR of two inverted inputs). The first is pretty straightforward, and I usually see people get it right. The second gets screwed up as often as not. And of course, any combination of ands and ors should be broken into multiple statements with a descriptive variable name in the middle or all hope is lost. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From rustompmody at gmail.com Mon Oct 13 13:12:13 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 13 Oct 2014 10:12:13 -0700 (PDT) Subject: while loop - multiple condition In-Reply-To: <20141013094308.7d4ea20c@rg.highlandtechnology.com> References: <878uklcd3r.fsf@elektro.pacujo.net> <543b0706$0$13005$c3e8da3$5496439d@news.astraweb.com> <20141013091248.1ffd94a0@rg.highlandtechnology.com> <20141013094308.7d4ea20c@rg.highlandtechnology.com> Message-ID: <1b9fa5ce-45da-4aa8-a849-394a033e1c9d@googlegroups.com> On Monday, October 13, 2014 10:13:20 PM UTC+5:30, Rob Gaddi wrote: > On Mon, 13 Oct 2014 09:26:57 -0700 (PDT) > Rustom Mody wrote: > > On Monday, October 13, 2014 9:43:03 PM UTC+5:30, Rob Gaddi wrote: > > > On Mon, 13 Oct 2014 09:56:02 +1100 > > > Steven D'Aprano wrote: > > > > When you have multiple clauses in the condition, it's easier to reason about > > > > them if you write the clauses as positive statements rather than negative > > > > statements, that is, "something is true" rather than "something is not > > > > true", and then use `not` to reverse it if you want to loop *until* the > > > > overall condition is true. > > > I was just explaining this concept to a young pup the other day. De > > > Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but > > > the positive logic flavor is substantially less error-prone. People > > > are fundamentally not as good at thinking about inverted logic. > > Curious: Which of > > - (not (p and q)) > > - ((not p) or (not q)) > > is more positive (less negative)?? > The first is asking you to compare positive conditions (p and q) and > negate the entire thing (NAND). The second asks you to think about > the combination of two different "not true" pieces of logic > (OR of two inverted inputs). The first is pretty straightforward, and > I usually see people get it right. The second gets screwed up as often > as not. > And of course, any combination of ands and ors should be broken into > multiple statements with a descriptive variable name in the middle or > all hope is lost. Yeah I guess 2 nots is one more than one! However (to my eyes) while i < N and a[i] != X: looks less negative than while not (i==N or a[i] == X): [Of course i < N is not identical to i != N ] From rwang at avnera.com Mon Oct 13 13:38:48 2014 From: rwang at avnera.com (Rff) Date: Mon, 13 Oct 2014 10:38:48 -0700 (PDT) Subject: How to select every other line from a text file? Message-ID: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Hi, I have a text file. Now it is required to select every other line of that text to generate a new text file. I have read through Python grammar, but still lack the idea at the beginning of the task. Could you tell me some methods to get this? Thanks, From rosuav at gmail.com Mon Oct 13 13:46:33 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 14 Oct 2014 04:46:33 +1100 Subject: How to select every other line from a text file? In-Reply-To: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: On Tue, Oct 14, 2014 at 4:38 AM, Rff wrote: > I have a text file. Now it is required to select every other line of that text to > generate a new text file. I have read through Python grammar, but still lack the > idea at the beginning of the task. Could you tell me some methods to get this? > There are a few ways of doing this. I'm guessing this is probably a homework assignment, so I won't give you the code as-is, but here are a few ideas: 1) Iterate over the file (line by line), alternating between writing the line out and not writing the line out. 2) Read the file into a list of lines, then slice the list with a step of 2, and write those lines out. 3) Iterate over the file, but also consume an extra line at the top or bottom of the loop. 4) Read the entire file into a string, then abuse regular expressions violently until they do what you want. And there are other ways, too. Show us some code and we can help you with it; but at the moment, this is fairly open-ended. ChrisA From gordon at panix.com Mon Oct 13 13:48:46 2014 From: gordon at panix.com (John Gordon) Date: Mon, 13 Oct 2014 17:48:46 +0000 (UTC) Subject: How to select every other line from a text file? References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: In <3be64ca8-d2e7-493a-b4f3-ef114f581450 at googlegroups.com> Rff writes: > Hi, > I have a text file. Now it is required to select every other line of that > text to generate a new text file. I have read through Python grammar, but > still lack the idea at the beginning of the task. Could you tell me some > methods to get this? Initialize a counter variable to zero. (Or one, depending if you want to select odd or even lines.) Each time you read a line from the file, add one to the counter. If the counter is odd, process the line; otherwise use the 'continue' statement to start the loop over and read another line. -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From gary.herron at islandtraining.com Mon Oct 13 13:50:43 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Mon, 13 Oct 2014 10:50:43 -0700 Subject: How to select every other line from a text file? In-Reply-To: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: <543C10F3.60609@islandtraining.com> On 10/13/2014 10:38 AM, Rff wrote: > Hi, > I have a text file. Now it is required to select every other line of that text to > generate a new text file. I have read through Python grammar, but still lack the > idea at the beginning of the task. Could you tell me some methods to get this? > > > Thanks, Read in your lines, keeping a counter as you go. "Select" those lines whose counter is even (or odd -- you didn't say which you wanted). So now some questions for you: * Do you know how to open a file and read in all the lines? * Do you know how to count as you do so? * Do you know how to test for evenness? (Use count%2 will be zero for even count values.) * Do you know how to write lines to an output file? Gary Herron -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Mon Oct 13 14:02:24 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 13 Oct 2014 19:02:24 +0100 Subject: How to select every other line from a text file? In-Reply-To: References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: On 13/10/2014 18:48, John Gordon wrote: > In <3be64ca8-d2e7-493a-b4f3-ef114f581450 at googlegroups.com> Rff writes: > >> Hi, >> I have a text file. Now it is required to select every other line of that >> text to generate a new text file. I have read through Python grammar, but >> still lack the idea at the beginning of the task. Could you tell me some >> methods to get this? > > Initialize a counter variable to zero. (Or one, depending if you want to > select odd or even lines.) > > Each time you read a line from the file, add one to the counter. > > If the counter is odd, process the line; otherwise use the 'continue' > statement to start the loop over and read another line. > Why bother to initialise a counter when you can get the enumerate function to do all the work for you? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From emile at fenx.com Mon Oct 13 14:11:53 2014 From: emile at fenx.com (emile) Date: Mon, 13 Oct 2014 11:11:53 -0700 Subject: How to select every other line from a text file? In-Reply-To: References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: On 10/13/2014 11:02 AM, Mark Lawrence wrote: > Why bother to initialise a counter when you can get the enumerate > function to do all the work for you? I see it as a question of addressing the audience. Emile From slyost at ilstu.edu Mon Oct 13 14:13:23 2014 From: slyost at ilstu.edu (slyost at ilstu.edu) Date: Mon, 13 Oct 2014 11:13:23 -0700 (PDT) Subject: scipy errors and gfortran Message-ID: <18d6bf8c-4265-49cc-b49c-3795b615aa44@googlegroups.com> Trying to get scipy 0.14 running on python 3.4.1 on SLES 11 SP2 LINUX system. Scipy seemed to compile fine using the command "python setup.py install" but when I try the scipy.test("full"), I get errors regarding gfortran. I am using GCC(gfortran) version 4.9.1. The error states that /usr/lib/libgfortran.so.3: version 'gfortran_1.4' was not found (required by....). Google tells me that this is the name of the symbol node whatever that means. What do I need to do to fix these errors? Please help. From joel.goldstick at gmail.com Mon Oct 13 14:45:53 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 13 Oct 2014 14:45:53 -0400 Subject: How to select every other line from a text file? In-Reply-To: References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: On Mon, Oct 13, 2014 at 2:11 PM, emile wrote: > On 10/13/2014 11:02 AM, Mark Lawrence wrote: > >> Why bother to initialise a counter when you can get the enumerate >> function to do all the work for you? > > > I see it as a question of addressing the audience. > > Emile I don't agree with the idea of using a counter. Its not pythonic, and I'm assuming the OP is just starting to learn python. Not apropos to the OP, but what came up in my mind was to write a generator function that returns every other line. This would separate the reading from the writing code. > > > > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From invalid at invalid.invalid Mon Oct 13 15:04:56 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 13 Oct 2014 19:04:56 +0000 (UTC) Subject: How to select every other line from a text file? References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: On 2014-10-13, Chris Angelico wrote: > On Tue, Oct 14, 2014 at 4:38 AM, Rff wrote: >> I have a text file. Now it is required to select every other line of that text to >> generate a new text file. I have read through Python grammar, but still lack the >> idea at the beginning of the task. Could you tell me some methods to get this? >> > > There are a few ways of doing this. I'm guessing this is probably a > homework assignment, so I won't give you the code as-is, but here are > a few ideas: > > 1) Iterate over the file (line by line), alternating between writing > the line out and not writing the line out. > > 2) Read the file into a list of lines, then slice the list with a step > of 2, and write those lines out. > > 3) Iterate over the file, but also consume an extra line at the top or > bottom of the loop. > > 4) Read the entire file into a string, then abuse regular expressions > violently until they do what you want. I'd vote for #3. Or write a generator that does something similar when given a parameter object that implements readline(). Of course, the _real_ answer is: os.system("sed -n 'g;n;p' '%s'" % filename) ;) -- Grant Edwards grant.b.edwards Yow! Didn't I buy a 1951 at Packard from you last March gmail.com in Cairo? From python.list at tim.thechases.com Mon Oct 13 13:55:55 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 13 Oct 2014 12:55:55 -0500 Subject: How to select every other line from a text file? In-Reply-To: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: <20141013125555.6dfdf8b3@bigbox.christie.dr> On 2014-10-13 10:38, Rff wrote: > Hi, > I have a text file. Now it is required to select every other line > of that text to generate a new text file. I have read through > Python grammar, but still lack the idea at the beginning of the > task. Could you tell me some methods to get this? You could force a re-read from the file each line: with open("x.txt") as f: for line in f: do_something(line) next(f) # discard/consume the next line Or, if you have it read into memory already, you could use slicing with a stride of 2: with open("x.txt") as f: data = f.readlines() interesting = data[::2] # start with the 1st line # interesting = data[1::2] # start with the 2nd line Or, if the file was large and you didn't want to have it all in memory at the same time, you could use itertools.islice() from itertools import islice with open("x.txt") as f: interesting = islice(f, 0, None, 2) # start with 1st line #interesting = islice(f, 1, None, 2) # start with 2nd line Note that in the last one, you get an iterator back, so you'd have to either turn it into a list or iterate over it. -tkc From python.list at tim.thechases.com Mon Oct 13 15:12:35 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 13 Oct 2014 14:12:35 -0500 Subject: How to select every other line from a text file? In-Reply-To: References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: <20141013141235.4c551f37@bigbox.christie.dr> On 2014-10-13 14:45, Joel Goldstick wrote: > Not apropos to the OP, but what came up in my mind was to write a > generator function that returns every other line. This would > separate the reading from the writing code. You mean like offset = 0 # or 1 if you prefer for line in itertools.islice(source_iter, offset, None, 2): do_something(line) ? -tkc From emile at fenx.com Mon Oct 13 16:01:24 2014 From: emile at fenx.com (emile) Date: Mon, 13 Oct 2014 13:01:24 -0700 Subject: How to select every other line from a text file? In-Reply-To: <20141013141235.4c551f37@bigbox.christie.dr> References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> <20141013141235.4c551f37@bigbox.christie.dr> Message-ID: On 10/13/2014 12:12 PM, Tim Chase wrote: > You mean like > > offset = 0 # or 1 if you prefer > for line in itertools.islice(source_iter, offset, None, 2): > do_something(line) I certainly did. Learning the python standard library is different from learning python and each in its own time. Emile From tjreedy at udel.edu Mon Oct 13 17:00:14 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 13 Oct 2014 17:00:14 -0400 Subject: windows 7 pysqlite build error In-Reply-To: <2ido3a9jlp6okee0aju5dgvq7qmku4ht49@4ax.com> References: <543BA027.8010504@chamonix.reportlab.co.uk> <2ido3a9jlp6okee0aju5dgvq7qmku4ht49@4ax.com> Message-ID: On 10/13/2014 4:31 PM, Dennis Lee Bieber wrote: > On Mon, 13 Oct 2014 10:49:27 +0100, Robin Becker > declaimed the following: > >>> c:\users\rptlab\tmp\tmcallister\build\pysqlite\src\connection.h(33) : fatal error C1083: Cannot open include file: 'sqli >>> te3.h': No such file or directory Did \n get stuck in the name of the file in connection.h, or is that purely an artifact of the error reporting? >>> error: command 'c:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\BIN\\amd64\\cl.exe' failed with exit status 2 > >> I do have the various compilers installed and other extensions are building OK, >> so is this an error in pysqlite or in my general setup? The include path looks >> like it might relate to Python builds. I suppose it's feasible that pyqslite >> builds need to be installed specially. I don't remember this happening on my old >> win32 XP system, but that died and I now am forced to use 64bit win7. > > Off hand, you don't have the SQLite3 /development package/. > > PySQLite is just an adapter to the sqlite3 DLL; the sqlite3.h file > would be part of the source code for sqlite3, not part of pysqlite itself. > -- Terry Jan Reedy From torriem at gmail.com Mon Oct 13 18:08:33 2014 From: torriem at gmail.com (Michael Torrie) Date: Mon, 13 Oct 2014 16:08:33 -0600 Subject: Flask and Django In-Reply-To: References: Message-ID: <543C4D61.7090800@gmail.com> On 10/10/2014 04:22 PM, Juan Christian wrote: > Maybe that's because I feel the Django doc a bit confuse, I tried reading > (and practicing!) tutorials, official doc, books, and so on, but I can't > quite understand the whole thing. > > Is Flask really underestimated? Can you guys mention "big name" companies > or people using it? Does it have real value in real world business? Nothing wrong with using Flask, especially for a personal project, or even something commercial. That said, Django is pretty easy to get started with. I have done very little web development ever, and I can fairly easily get going with Django. The tutorials are quite good. If you have problems with them, you can get help on the django mailing lists and forums, I am sure. Django does seem to get a lot of attention. It's getting to be a huge framework, with lots of bells and whistles, but I'm pretty sure you can still use as much or as little of it as you need, and even discard parts of it, such as the native Django database persistance API, and use, say, sqalchemy. From torriem at gmail.com Mon Oct 13 18:08:36 2014 From: torriem at gmail.com (Michael Torrie) Date: Mon, 13 Oct 2014 16:08:36 -0600 Subject: while loop - multiple condition In-Reply-To: <1b9fa5ce-45da-4aa8-a849-394a033e1c9d@googlegroups.com> References: <878uklcd3r.fsf@elektro.pacujo.net> <543b0706$0$13005$c3e8da3$5496439d@news.astraweb.com> <20141013091248.1ffd94a0@rg.highlandtechnology.com> <20141013094308.7d4ea20c@rg.highlandtechnology.com> <1b9fa5ce-45da-4aa8-a849-394a033e1c9d@googlegroups.com> Message-ID: <543C4D64.2050305@gmail.com> On 10/13/2014 11:12 AM, Rustom Mody wrote: > On Monday, October 13, 2014 10:13:20 PM UTC+5:30, Rob Gaddi wrote: >> On Mon, 13 Oct 2014 09:26:57 -0700 (PDT) >> Rustom Mody wrote: > >>> On Monday, October 13, 2014 9:43:03 PM UTC+5:30, Rob Gaddi wrote: >>>> On Mon, 13 Oct 2014 09:56:02 +1100 >>>> Steven D'Aprano wrote: >>>>> When you have multiple clauses in the condition, it's easier to reason about >>>>> them if you write the clauses as positive statements rather than negative >>>>> statements, that is, "something is true" rather than "something is not >>>>> true", and then use `not` to reverse it if you want to loop *until* the >>>>> overall condition is true. >>>> I was just explaining this concept to a young pup the other day. De >>>> Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but >>>> the positive logic flavor is substantially less error-prone. People >>>> are fundamentally not as good at thinking about inverted logic. >>> Curious: Which of >>> - (not (p and q)) >>> - ((not p) or (not q)) >>> is more positive (less negative)?? > >> The first is asking you to compare positive conditions (p and q) and >> negate the entire thing (NAND). The second asks you to think about >> the combination of two different "not true" pieces of logic >> (OR of two inverted inputs). The first is pretty straightforward, and >> I usually see people get it right. The second gets screwed up as often >> as not. > >> And of course, any combination of ands and ors should be broken into >> multiple statements with a descriptive variable name in the middle or >> all hope is lost. > > Yeah I guess 2 nots is one more than one! > > However (to my eyes) > while i < N and a[i] != X: > > looks less negative than > > while not (i==N or a[i] == X): > > [Of course i < N is not identical to i != N ] Right it should have been not (i >= N or a[i] == X) to be equivalent. In assembler it's often best to reverse the condition and then use the opposite jump mnemonic. IE, if the test is to see if a number not zero, use the jump if zero command instead. Often it reduces the number of jumps required and eliminates the need to jump over the body of the "if" block. if a != 0 then jump to bigger jump to end bigger: blah blah end: vs if a == 0 then jump to end blah blah end: From denismfmcmahon at gmail.com Mon Oct 13 19:54:09 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Mon, 13 Oct 2014 23:54:09 +0000 (UTC) Subject: How to select every other line from a text file? References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: On Mon, 13 Oct 2014 10:38:48 -0700, Rff wrote: > I have a text file. Now it is required to select every other line of > that text to > generate a new text file. I have read through Python grammar, but still > lack the idea at the beginning of the task. Could you tell me some > methods to get this? So this could be written as an algorithm something like: 1/ open the input file 2/ open the output file 3/ while there are lines to read from the input file 3/1/ read a line from the input file 3/2/ if I should output this line 3/2/1/ write line to output file 4/ close the input file 5/ close the output file Or in several other ways, and once you have an algorithm, you can start coding it (or implementing it in the programming language of your choice, whichever form of words best pleases your perfesser). -- Denis McMahon, denismfmcmahon at gmail.com From drsalists at gmail.com Mon Oct 13 20:34:49 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 13 Oct 2014 17:34:49 -0700 Subject: How to select every other line from a text file? In-Reply-To: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> References: <3be64ca8-d2e7-493a-b4f3-ef114f581450@googlegroups.com> Message-ID: On Mon, Oct 13, 2014 at 10:38 AM, Rff wrote: > Hi, > I have a text file. Now it is required to select every other line of that text to > generate a new text file. I have read through Python grammar, but still lack the > idea at the beginning of the task. Could you tell me some methods to get this? Perhaps something like: http://stromberg.dnsalias.org/svn/every-nth/trunk It uses zip and itertools.cycle. It's CPython 3.x though - if you need 2.x, you'd probably use xrange instead of range, and izip instead of zip. From sagarddd at gmail.com Mon Oct 13 21:47:08 2014 From: sagarddd at gmail.com (Sagar Deshmukh) Date: Mon, 13 Oct 2014 18:47:08 -0700 (PDT) Subject: Need help in pulling SQL query out of log file... Message-ID: <6200437a-b90a-4b60-b287-bd5b7fe37e9d@googlegroups.com> Hi, I have a log file which has lot of information like..SQL query.. number of records read...records loaded etc.. My requirement is i would like to read the SQL query completly and write it to another txt file.. also the log file may not be always same so can not make static choices... my logfile is like below : *****LOg file starts****** Fri Aug 08 16:00:04 2014 : WRITER_1_*_1> WRT_8005 Writer run started. Fri Aug 08 16:00:04 2014 : READER_1_2_1> BLKR_16007 Reader run started. Fri Aug 08 16:00:04 2014 : WRITER_1_*_1> WRT_8158 *****START LOAD SESSION***** Load Start Time: Fri Aug 08 16:00:04 2014 Target tables: EIS_REQUEST_LOG_26MAYBKP T_delta_parm_file Fri Aug 08 16:00:04 2014 : READER_1_2_1> RR_4010 SQ instance [SQ_Shortcut_to_EIS_REQUEST_LOG] SQL Query [SELECT EIS_REQUEST_LOG_26MAYBKP.RqstId, EIS_REQUEST_LOG_26MAYBKP.RQSTLoadStatCd FROM EIS_REQUEST_LOG_26MAYBKP] Fri Aug 08 16:00:04 2014 : READER_1_2_1> RR_4049 RR_4049 SQL Query issued to database : (Fri Aug 08 16:00:04 2014) Fri Aug 08 16:00:04 2014 : READER_1_2_1> RR_4035 SQL Error [ FnName: Prepare -- [Teradata][ODBC Teradata Driver][Teradata Database] Object 'EIS_REQUEST_LOG_26MAYBKP' does not exist. ]. Fri Aug 08 16:00:04 2014 : READER_1_2_1> BLKR_16004 ERROR: Prepare failed. Fri Aug 08 16:00:04 2014 : READER_1_1_1> RR_4029 SQ Instance [SQ_RSTS_Tables] User specified SQL Query [--- Approved By ICC Team------- ---SELECT A.LOGSYS , ---D."/BIC/NIGNRCSYS" , ---B.ODSNAME , ---C.ODSNAME_TECH , ---C.PARTNO , ---C.REQUEST , ---E.SID ---FROM ---sapbzd."RSISOSMAP" A, ---sapbzd."RSTSODS" B, ---sapbzd."RSTSODSPART" C, ---sapbzd."/BIC/PNIGNRCSYS" D, ---sapbzd."/BI0/SREQUID" E, ---sapbzd."RSMONMESS" F ---WHERE A.OLTPSOURCE = ('ZNK_SHP_DDLN_CREATE_BE','ZNK_KNVP2_BD','ZNK_ZVBW_RTN_ORD_ITM_BN','2LIS_02_SCL_BE','ZNK_FX_CRCY_HIS_BE','ZNK_PO_FX_CALC_LOG_BD','2LIS_12_VCHDR_BE','2LIS_02_HDR_BN','ZNK_SHP_DDLN_CHANGE_BD','1_CO_PAGL11000N1_BE','0CUSTOMER_ATTR_BE','2LIS_08TRTLP_BD','2LIS_02_SCN_BD','2LIS_02_HDR_BD','2LIS_13_VDITM_BE','0CO_OM_CCA_9_BE','ZNK_SO_BDSI_OPNDMD_BE','2LIS_11_VAHDR_BE','ZNK_ZVBW_MBEW_BE','2LIS_13_VDHDR_BN','ZNK_SHP_DDLN_CHANGE_BE','NK_ADDR_NUMBR_BN','0CUSTOMER_TEXT_BE','6DB_J_3ABD_DELTA_AFFL_AD','0MAT_PLANT_ATTR_BE','ZNK_BDCPV_BD','1_CO_PAGL11000N1_BD','2LIS_11_VASTI_BD','ZNK_ZVBW_MSKU_BE','ZNK_SHP_DDLN_CREATE_BD','0SCEM_1_BC','2LIS_11_VAHDR_BD','2LIS_11_VASCL_BD','0MATERIAL_TEXT_BE','0MATERIAL_ATTR_BE','ZNK_BDCPV_BE','2LIS_02_ITM_BN','2LIS_11_VASCL_BE','2LIS_11_VAITM_BN','NK_ADDR_NUMBR_BE','2LIS_08TRTK_BE','ZNK_SD_LIKPPS_BN','2LIS_03_BF_BE','ZNK_SO_BDBS_ALLOC_BD','ZNK_TD_3AVASSO_BN','0EC_PCA_3_BD','ZNK_TD_3AVAP_BE','2LIS_11_VAITM_BE','0CUST_SALES_ATTR_BN','0EC_PCA_3_BE','2LIS_13_VDITM_BN','2LIS_11_VASTH_BD','2LIS_13_VDITM_BD','0CUST_SALES_ATTR_BD','ZNK_TD_3AVASSO_BD','2LIS_02_SCN_BE','2LIS_08TRTS_BD','0CUSTOMER_ATTR_BN','ZNK_TD_3AVASSO_BE','ZNK_ZVBW_MSLB_BE','ZNK_TD_3AVAP_BD','0CUSTOMER_TEXT_BN','6DB_J_3ABD_DELTA_US_AD','0CUSTOMER_TEXT_BD','2LIS_11_VAHDR_BN','ZNK_SO_BDBS_ALLOC_BN','0GL_ACCOUNT_TEXT_BE','0GL_ACCOUNT_TEXT_BD','2LIS_11_VAITM_BD','ZNK_TD_3AVATL_BE','ZNK_SO_BDBS_ALLOC_BE','ZNK_EBAN_BE','ZNK_SO_BDSI_OPNDMD_BN','ZNK_SD_LIKPPS_BD','ZNK_ZVBW_RTN_ORD_ITM_BE','2LIS_08TRTS_BN','2LIS_02_HDR_BE','ZNK_TD_3AVATL_BD','ZNK_VBPA_BE','ZNK_FX_CRCY_HIS_BD','2LIS_13_VDHDR_BE','NK_ADDR_NUMBR_BD','2LIS_12_VCITM_BD','2LIS_08TRTK_BD','2LIS_11_VASCL_BN','ZNK_ZVBW_MCHB_BE','6DB_J_3ABD_SCL_DELTA_AP_AE','ZNK_SO_BDSI_OPNDMD_BD','ZNK_KNVP2_BE','0MAT_SALES_ATTR_BE','ZNK_TD_3AVAP_BN','2LIS_13_VDHDR_BD','0GL_ACCOUNT_ATTR_BD','2LIS_02_SCL_BD','ZNK_VBPA_BD','2LIS_02_ITM_BD','ZNK_TD_3AVATL_BN','ZNK_ZVBW_RTN_ORD_ITM_BD','ZNK_PO_FX_CALC_LOG_BE','6DB_J_3ABD_DELTA_EMEA_AD','0GL_ACCOUNT_ATTR_BE','2LIS_03_BF_BD','2! LIS_11_V ASTI_BE','0CO_OM_CCA_9_BD','0CUST_SALES_ATTR_BE','2LIS_12_VCITM_BE','0CUSTOMER_ATTR_BD','2LIS_02_ITM_BE','2LIS_08TRTLP_BE','2LIS_12_VCHDR_BD','ZNK_EBAN_BD','2LIS_08TRTS_BE','2LIS_02_SCL_BN','2LIS_11_VASTH_BE','ZNK_SD_LIKPPS_BE') ---AND A.LOGSYS = D."/BIC/NKLOGSYST" ---AND A.OBJVERS = 'A' ---AND A.TRANSTRU = B.ODSNAME ---AND B.DATETO = 99990101 ---AND B.OBJSTAT = 'ACT' ---AND B.ODSNAME_TECH = C.ODSNAME_TECH ---AND C.DELFLAG <> 'X' ---AND D."/BIC/NIGNRCSYS" = ('R3_PRA','R3_PRD','R3_PRF','EM_EMP') ---AND D.OBJVERS = 'A' ---AND E.REQUID = C.REQUEST ---AND F.RNR = C.REQUEST ---AND F.MSGNO = '344' ---AND F.AUFRUFER = '09'--- SELECT A.LOGSYS , D."/BIC/NIGNRCSYS" , B.ODSNAME , C.ODSNAME_TECH , C.PARTNO , C.REQUEST , E.SID FROM sapbzd."RSISOSMAP" A, sapbzd."RSTSODS" B, sapbzd."RSTSODSPART" C, sapbzd."/BIC/PNIGNRCSYS" D, sapbzd."/BI0/SREQUID" E, sapbzd."RSMONMESS" F WHERE A.OLTPSOURCE in ('ZNK_SHP_DDLN_CREATE_BE','ZNK_KNVP2_BD','ZNK_ZVBW_RTN_ORD_ITM_BN','2LIS_02_SCL_BE','ZNK_FX_CRCY_HIS_BE','ZNK_PO_FX_CALC_LOG_BD','2LIS_12_VCHDR_BE','2LIS_02_HDR_BN','ZNK_SHP_DDLN_CHANGE_BD','1_CO_PAGL11000N1_BE','0CUSTOMER_ATTR_BE','2LIS_08TRTLP_BD','2LIS_02_SCN_BD','2LIS_02_HDR_BD','2LIS_13_VDITM_BE','0CO_OM_CCA_9_BE','ZNK_SO_BDSI_OPNDMD_BE','2LIS_11_VAHDR_BE','ZNK_ZVBW_MBEW_BE','2LIS_13_VDHDR_BN','ZNK_SHP_DDLN_CHANGE_BE','NK_ADDR_NUMBR_BN','0CUSTOMER_TEXT_BE','6DB_J_3ABD_DELTA_AFFL_AD','0MAT_PLANT_ATTR_BE','ZNK_BDCPV_BD','1_CO_PAGL11000N1_BD','2LIS_11_VASTI_BD','ZNK_ZVBW_MSKU_BE','ZNK_SHP_DDLN_CREATE_BD','0SCEM_1_BC','2LIS_11_VAHDR_BD','2LIS_11_VASCL_BD','0MATERIAL_TEXT_BE','0MATERIAL_ATTR_BE','ZNK_BDCPV_BE','2LIS_02_ITM_BN','2LIS_11_VASCL_BE','2LIS_11_VAITM_BN','NK_ADDR_NUMBR_BE','2LIS_08TRTK_BE','ZNK_SD_LIKPPS_BN','2LIS_03_BF_BE','ZNK_SO_BDBS_ALLOC_BD','ZNK_TD_3AVASSO_BN','0EC_PCA_3_BD','ZNK_TD_3AVAP_BE','2LIS_11_VAITM_BE','0CUST_SALES_ATTR_BN','0EC_PCA_3_BE','2LIS_13_VDITM_BN','2LIS_11_VASTH_BD','2LIS_13_VDITM_BD','0CUST_SALES_ATTR_BD','ZNK_TD_3AVASSO_BD','2LIS_02_SCN_BE','2LIS_08TRTS_BD','0CUSTOMER_ATTR_BN','ZNK_TD_3AVASSO_BE','ZNK_ZVBW_MSLB_BE','ZNK_TD_3AVAP_BD','0CUSTOMER_TEXT_BN','6DB_J_3ABD_DELTA_US_AD','0CUSTOMER_TEXT_BD','2LIS_11_VAHDR_BN','ZNK_SO_BDBS_ALLOC_BN','0GL_ACCOUNT_TEXT_BE','0GL_ACCOUNT_TEXT_BD','2LIS_11_VAITM_BD','ZNK_TD_3AVATL_BE','ZNK_SO_BDBS_ALLOC_BE','ZNK_EBAN_BE','ZNK_SO_BDSI_OPNDMD_BN','ZNK_SD_LIKPPS_BD','ZNK_ZVBW_RTN_ORD_ITM_BE','2LIS_08TRTS_BN','2LIS_02_HDR_BE','ZNK_TD_3AVATL_BD','ZNK_VBPA_BE','ZNK_FX_CRCY_HIS_BD','2LIS_13_VDHDR_BE','NK_ADDR_NUMBR_BD','2LIS_12_VCITM_BD','2LIS_08TRTK_BD','2LIS_11_VASCL_BN','ZNK_ZVBW_MCHB_BE','6DB_J_3ABD_SCL_DELTA_AP_AE','ZNK_SO_BDSI_OPNDMD_BD','ZNK_KNVP2_BE','0MAT_SALES_ATTR_BE','ZNK_TD_3AVAP_BN','2LIS_13_VDHDR_BD','0GL_ACCOUNT_ATTR_BD','2LIS_02_SCL_BD','ZNK_VBPA_BD','2LIS_02_ITM_BD','ZNK_TD_3AVATL_BN','ZNK_ZVBW_RTN_ORD_ITM_BD','ZNK_PO_FX_CALC_LOG_BE','6DB_J_3ABD_DELTA_EMEA_AD','0GL_ACCOUNT_ATTR_BE','2LIS_03_BF_BD','2LIS_11_V! ASTI_BE' ,'0CO_OM_CCA_9_BD','0CUST_SALES_ATTR_BE','2LIS_12_VCITM_BE','0CUSTOMER_ATTR_BD','2LIS_02_ITM_BE','2LIS_08TRTLP_BE','2LIS_12_VCHDR_BD','ZNK_EBAN_BD','2LIS_08TRTS_BE','2LIS_02_SCL_BN','2LIS_11_VASTH_BE','ZNK_SD_LIKPPS_BE') AND A.LOGSYS = D."/BIC/NKLOGSYST" AND A.OBJVERS = 'A' AND A.TRANSTRU = B.ODSNAME AND B.DATETO = 99990101 AND B.OBJSTAT = 'ACT' AND B.ODSNAME_TECH = C.ODSNAME_TECH AND C.DELFLAG <> 'X' AND D."/BIC/NIGNRCSYS" in ('R3_PRA','R3_PRD','R3_PRF','EM_EMP') AND D.OBJVERS = 'A' AND E.REQUID = C.REQUEST AND F.RNR = C.REQUEST AND F.MSGNO = '344' AND F.AUFRUFER = '09'] Fri Aug 08 16:00:04 2014 : READER_1_1_1> RR_4049 RR_4049 SQL Query issued to database : (Fri Aug 08 16:00:04 2014) Fri Aug 08 16:00:04 2014 : WRITER_1_*_1> WRT_8333 Rolling back all the targets due to fatal session error. Fri Aug 08 16:00:04 2014 : WRITER_1_*_1> WRT_8325 Final rollback executed for the target [Shortcut_to_EIS_REQUEST_LOG_DFX] at end of load Fri Aug 08 16:00:04 2014 : WRITER_1_*_1> WRT_8035 Load complete time: Fri Aug 08 16:00:04 2014 LOAD SUMMARY ============ WRT_8036 Target: EIS_REQUEST_LOG_26MAYBKP (Instance Name: [Shortcut_to_EIS_REQUEST_LOG_DFX]) WRT_8044 No data loaded for this target WRT_8036 Target: T_delta_parm_file (Instance Name: [Shortcut_to_T_delta_parm_file]) WRT_8044 No data loaded for this target *****Log file ends****** Please help me on this.... From torriem at gmail.com Tue Oct 14 01:19:43 2014 From: torriem at gmail.com (Michael Torrie) Date: Mon, 13 Oct 2014 23:19:43 -0600 Subject: How to install and run a script? In-Reply-To: <6d282d09-fa5f-4d3a-aaed-5c15f8f9b56f@googlegroups.com> References: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> <6d282d09-fa5f-4d3a-aaed-5c15f8f9b56f@googlegroups.com> Message-ID: <543CB26F.8020107@gmail.com> On 10/12/2014 08:05 PM, ryguy7272 wrote: > Ahhhhh!!! I didn't know I needed to run it from the command prompt! Ok, not it makes sense, and everything works. > > Thanks to all! You don't have to run python apps from the command line. Apps that throw up windows can usually be run by double-clicking the py file in windows. But apps that communicate solely on the terminal or console have to be run in that environment. From wuwei23 at gmail.com Tue Oct 14 01:39:54 2014 From: wuwei23 at gmail.com (alex23) Date: Tue, 14 Oct 2014 15:39:54 +1000 Subject: Need help in pulling SQL query out of log file... In-Reply-To: <6200437a-b90a-4b60-b287-bd5b7fe37e9d@googlegroups.com> References: <6200437a-b90a-4b60-b287-bd5b7fe37e9d@googlegroups.com> Message-ID: On 14/10/2014 11:47 AM, Sagar Deshmukh wrote: > I have a log file which has lot of information like..SQL query.. number of records read...records loaded etc.. > My requirement is i would like to read the SQL query completly and write it to another txt file.. Generally we encourage people to post what they've tried to the list. It helps us identify what you know and what you need help with. However, given: > the log file may not be always same so can not make static choices... You'll probably want to use regular expressions: https://docs.python.org/howto/regex.html Regexps let you search through the text for known patterns and extract any that match. To extract all SQL query sections, you'll need to come up with a way of uniquely identifying them from all other sections. Looking at your example log file, it looks like they're all of the format: SQL Query [] From that we can determine that all SQL queries are prefixed by 'SQL Query [' and suffixed by ']', so the content you want is everything between those markers. So a possible regular expression might be: SQL Query \[(.*?)\] To quickly explain this: 1. "SQL Query " matches on that string 2. Because [] have meaning for regexes, to match on literal brackets you need to escape them via \[ and \] 3. ( ) is a group, whats contained in here will be returned 4. .* means to grab all matching text 5. ? means to do an "ungreedy" grab ie it'll stop at the first \] it encounters. Pulling the queries out of your log file should be as simple as: import re log = open('logfile').read() queries = re.findall("SQL Query \[(.*?)\]", log, re.DOTALL) Because the queries can fall across multiple lines, the re.DOTALL flag is required to treat EOL markers as characters. Hope this helps. From wuwei23 at gmail.com Tue Oct 14 01:55:11 2014 From: wuwei23 at gmail.com (alex23) Date: Tue, 14 Oct 2014 15:55:11 +1000 Subject: TypeError: 'kwarg' is an invalid keyword argument for this function In-Reply-To: References: Message-ID: On 13/10/2014 8:04 PM, Dave Angel wrote: > It would also help to spell it the same. In the OP's > implementation, he defined kwargs, and tried to use it as > kwarg. That's perfectly okay, though: if `kwargs` is the name used to reference the dictionary of keyword arguments, `kwarg` would be an instance of a keyword argument. From sagarddd at gmail.com Tue Oct 14 02:09:54 2014 From: sagarddd at gmail.com (Sagar Deshmukh) Date: Mon, 13 Oct 2014 23:09:54 -0700 (PDT) Subject: Need help in pulling SQL query out of log file... In-Reply-To: References: <6200437a-b90a-4b60-b287-bd5b7fe37e9d@googlegroups.com> Message-ID: <1bdfe07b-45f4-4549-959e-3eb176a8b055@googlegroups.com> On Monday, 13 October 2014 22:40:07 UTC-7, alex23 wrote: > On 14/10/2014 11:47 AM, Sagar Deshmukh wrote: > > > I have a log file which has lot of information like..SQL query.. number of records read...records loaded etc.. > > > My requirement is i would like to read the SQL query completly and write it to another txt file.. > > > > Generally we encourage people to post what they've tried to the list. It > > helps us identify what you know and what you need help with. > > > > However, given: > > > > > the log file may not be always same so can not make static choices... > > > > You'll probably want to use regular expressions: > > > > https://docs.python.org/howto/regex.html > > > > Regexps let you search through the text for known patterns and extract > > any that match. To extract all SQL query sections, you'll need to come > > up with a way of uniquely identifying them from all other sections. > > Looking at your example log file, it looks like they're all of the format: > > > > SQL Query [] > > > > From that we can determine that all SQL queries are prefixed by 'SQL > > Query [' and suffixed by ']', so the content you want is everything > > between those markers. So a possible regular expression might be: > > > > SQL Query \[(.*?)\] > > > > To quickly explain this: > > > > 1. "SQL Query " matches on that string > > 2. Because [] have meaning for regexes, to match on literal > > brackets you need to escape them via \[ and \] > > 3. ( ) is a group, whats contained in here will be returned > > 4. .* means to grab all matching text > > 5. ? means to do an "ungreedy" grab ie it'll stop at the first \] > > it encounters. > > > > Pulling the queries out of your log file should be as simple as: > > > > import re > > > > log = open('logfile').read() > > queries = re.findall("SQL Query \[(.*?)\]", log, re.DOTALL) > > > > Because the queries can fall across multiple lines, the re.DOTALL flag > > is required to treat EOL markers as characters. > > > > Hope this helps. Hi, This helps and its working... Thank you so much.... From wxjmfauth at gmail.com Tue Oct 14 02:34:54 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Mon, 13 Oct 2014 23:34:54 -0700 (PDT) Subject: while loop - multiple condition In-Reply-To: References: <878uklcd3r.fsf@elektro.pacujo.net> <543b0706$0$13005$c3e8da3$5496439d@news.astraweb.com> <20141013091248.1ffd94a0@rg.highlandtechnology.com> <20141013094308.7d4ea20c@rg.highlandtechnology.com> <1b9fa5ce-45da-4aa8-a849-394a033e1c9d@googlegroups.com> Message-ID: <4359ed6d-b92f-4dde-8564-0742898b70a8@googlegroups.com> Le mardi 14 octobre 2014 00:09:08 UTC+2, Michael Torrie a ?crit?: > On 10/13/2014 11:12 AM, Rustom Mody wrote: > > > On Monday, October 13, 2014 10:13:20 PM UTC+5:30, Rob Gaddi wrote: > > >> On Mon, 13 Oct 2014 09:26:57 -0700 (PDT) > > >> Rustom Mody wrote: > > > > > >>> On Monday, October 13, 2014 9:43:03 PM UTC+5:30, Rob Gaddi wrote: > > >>>> On Mon, 13 Oct 2014 09:56:02 +1100 > > >>>> Steven D'Aprano wrote: > > >>>>> When you have multiple clauses in the condition, it's easier to reason about > > >>>>> them if you write the clauses as positive statements rather than negative > > >>>>> statements, that is, "something is true" rather than "something is not > > >>>>> true", and then use `not` to reverse it if you want to loop *until* the > > >>>>> overall condition is true. > > >>>> I was just explaining this concept to a young pup the other day. De > > >>>> Morgan's lets you say that (not (p and q)) == ((not p) or (not q)), but > > >>>> the positive logic flavor is substantially less error-prone. People > > >>>> are fundamentally not as good at thinking about inverted logic. > > >>> Curious: Which of > > >>> - (not (p and q)) > > >>> - ((not p) or (not q)) > > >>> is more positive (less negative)?? > > > > > >> The first is asking you to compare positive conditions (p and q) and > > >> negate the entire thing (NAND). The second asks you to think about > > >> the combination of two different "not true" pieces of logic > > >> (OR of two inverted inputs). The first is pretty straightforward, and > > >> I usually see people get it right. The second gets screwed up as often > > >> as not. > > > > > >> And of course, any combination of ands and ors should be broken into > > >> multiple statements with a descriptive variable name in the middle or > > >> all hope is lost. > > > > > > Yeah I guess 2 nots is one more than one! > > > > > > However (to my eyes) > > > while i < N and a[i] != X: > > > > > > looks less negative than > > > > > > while not (i==N or a[i] == X): > > > > > > [Of course i < N is not identical to i != N ] > > > > Right it should have been not (i >= N or a[i] == X) to be equivalent. > > > > In assembler it's often best to reverse the condition and then use the > > opposite jump mnemonic. IE, if the test is to see if a number not zero, > > use the jump if zero command instead. Often it reduces the number of > > jumps required and eliminates the need to jump over the body of the "if" > > block. > > > > if a != 0 then jump to bigger > > jump to end > > bigger: > > blah > > blah > > end: > > > > vs > > > > if a == 0 then jump to end > > blah > > blah > > end: On the side of logic. Nothing can beat this mathematical absurdity (in the logical sense of the term) called Flexible String Representation. Simply unbelievable. jmf From breamoreboy at yahoo.co.uk Tue Oct 14 03:30:20 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 14 Oct 2014 08:30:20 +0100 Subject: How to install and run a script? In-Reply-To: <543CB26F.8020107@gmail.com> References: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> <6d282d09-fa5f-4d3a-aaed-5c15f8f9b56f@googlegroups.com> <543CB26F.8020107@gmail.com> Message-ID: On 14/10/2014 06:19, Michael Torrie wrote: > On 10/12/2014 08:05 PM, ryguy7272 wrote: >> Ahhhhh!!! I didn't know I needed to run it from the command prompt! Ok, not it makes sense, and everything works. >> >> Thanks to all! > > You don't have to run python apps from the command line. Apps that > throw up windows can usually be run by double-clicking the py file in > windows. But apps that communicate solely on the terminal or console > have to be run in that environment. > No, you need to double click a pyw file to get a windows app, py files always give you a console. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From faceofoblivionofficial at gmail.com Tue Oct 14 04:04:38 2014 From: faceofoblivionofficial at gmail.com (Revenant) Date: Tue, 14 Oct 2014 01:04:38 -0700 (PDT) Subject: Code Review for Paper, Rock, Scissors Message-ID: Hi all! I'm new to Python and programming in general, and am trying to learn as much as I can about it. Anyway, for a basic first program I made a simple game of Paper, Rock, Scissors. For this program, I incorporated a main menu that presented three different options, allowed the user to play a game of Paper, Rock, Scissors, allowed them to play the game again, and most importantly checked the user's input to make sure the program doesn't fail due to errors. One thing I want to try to add is a "Press any key to continue" function that occurs at the end of the program when the user decides to quit. I looked at some options online, but haven't quite figured it out yet. As previously stated, I am new to Python and would also like to see if any of you programming gurus have some suggestions about how I can simplify code, and also if there are any other good starter programs to work on to improve my skills. Thanks for reading! Code is below: # Creates the main menu. def menu(): # Sets the scores to 0. global playerscore global compscore global draws playerscore = 0 compscore = 0 draws = 0 menuselection = input('Please enter a selection: (Play/Help/About): ') # Checks for an invalid selection. while menuselection != 'Play' and menuselection != 'play' and menuselection != 'Help' and menuselection != 'help' \ and menuselection != 'About' and menuselection != 'about': print('You have entered an invalid selection.') menuselection = input('\nPlease type a selection: (Play/Help/About): ') else: if menuselection == 'Play' or menuselection == 'play': play() elif menuselection == 'Help' or menuselection == 'help': instructions() else: about() # Creates the game. def play(): global playerscore global compscore global draws # Player chooses Paper, Rock, or Scissors. playerselect = input('\nPlease choose Paper, Rock, or Scissors: ') # Checks for an invalid selection. while playerselect != 'Paper' and playerselect != 'paper' and playerselect != 'Rock' and playerselect != 'rock' \ and playerselect != 'Scissors' and playerselect != 'scissors': print('You have entered an invalid selection.') playerselect = input('\nPlease choose Paper, Rock, or Scissors: ') else: if playerselect == 'Paper' or playerselect == 'paper': print('\nYou have selected Paper.') playerselect = 1 elif playerselect == 'Rock' or playerselect == 'rock': print('\nYou have selected Rock.') playerselect = 2 else: print('\nYou have selected Scissors.') playerselect = 3 # Computer chooses Paper, Rock, or Scissors. import random compselect = random.randint(1, 3) if compselect == 1: print('The Computer has selected Paper') elif compselect == 2: print('The Computer has selected Rock.') else: print('The Computer has selected Scissors.') # Results if player selects paper. if playerselect == 1 and compselect == 1: print('Draw!') draws += 1 score() else: if playerselect == 1 and compselect == 2: print('Paper beats rock. You win!') playerscore += 1 score() elif playerselect == 1 and compselect == 3: print('Paper is beaten by scissors. You lose!') compscore += 1 score() # Results if player selects rock. if playerselect == 2 and compselect == 2: print('Draw!') draws += 1 score() else: if playerselect == 2 and compselect == 1: print('Rock is beaten by paper. You lose!') compscore += 1 score() elif playerselect == 2 and compselect == 3: print('Rock beats scissors. You win!') playerscore += 1 score() # Results if player selects rock. if playerselect == 3 and compselect == 3: print('Draw!') draws += 1 score() else: if playerselect == 3 and compselect == 1: print('Scissors beat paper. You win!') playerscore += 1 score() elif playerselect == 3 and compselect == 2: print('Scissors are beaten by rock. You lose!') compscore += 1 score() again() # Determines if the player wants to play another game. def again(): replay = input('\nDo you want to play again (Y/N)? ') while replay != 'Y' and replay != 'y' and replay != 'N' and replay != 'n': print('You have entered an invalid selection.') replay = input('\nDo you want to play again (Y/N)? ') else: if replay == 'Y' or replay == 'y': play() else: print('\nThanks for playing!') # Creates the instructions. def instructions(): print('\nPaper, Rock, Scissors is a simple game played against a computer opponent.') print('The player will have a choice of selecting paper, rock, or scissors.') print('The player\'s result will be compared with that of the computer to determine who wins the round.') print('In the event that both the player and the computer have the same selection, the round will end in a tie.') print('\nPaper beats rock but loses to scissors.') print('\nRock beats scissors but loses to paper.') print('\nScissors beats paper but loses to rock.') print('\nGood luck, and have fun!\n') menu() # Creates the about section. def about(): print('\nPaper, Rock, Scissors\n\nVersion 1.0\n\nCreated by , 07 October 2014\n') menu() # Calculates score. def score(): print('\nCurrent Scores: ') print('\nPlayer Score:', playerscore) print('\nComputer Score:', compscore) print('\nDraws:', draws) # Start of program operations. print('Welcome to Paper, Rock, Scissors!\n') menu() From zondo42 at gmail.com Tue Oct 14 04:39:46 2014 From: zondo42 at gmail.com (Glenn Hutchings) Date: Tue, 14 Oct 2014 01:39:46 -0700 (PDT) Subject: Code Review for Paper, Rock, Scissors In-Reply-To: References: Message-ID: <2abcabe0-c8b1-4386-b6e5-4fcfa48a3b5e@googlegroups.com> Hi there! Welcome to Python. On Tuesday, 14 October 2014 09:04:51 UTC+1, Revenant wrote: > I am new to Python and would also like to see if any of you programming > gurus have some suggestions about how I can simplify code, and also if > there are any other good starter programs to work on to improve my > skills. I'm sure you'll get a lot of helpful advice here. Here's a start: you have a lot of places where you're comparing variables to the capitalized and lower-case versions of the same string. You could halve that number if you converted your input to lowercase first. For example: if menuselection == 'play' or menuselection == 'Play': changes to: if menuselection.lower() == 'play': There are plenty of other string methods you might find useful. From venugopal.reddy at tspl.com Tue Oct 14 05:46:44 2014 From: venugopal.reddy at tspl.com (Venugopal Reddy) Date: Tue, 14 Oct 2014 02:46:44 -0700 (PDT) Subject: Jython or Pyton issue-- Kindly Help me.... In-Reply-To: References: <91eb3378-958d-45e0-8741-a800ae681260@googlegroups.com> Message-ID: <552277f6-fb5b-44de-a0d4-7c7fe480d265@googlegroups.com> Ok, I will explain my problem in details : I have below XML: 1 2008 2009> 141100 4 2011 59900 68 2011 13600 >From I want output below format: Countryname Rank Year gdppc Liechtenstein 1 2008 141100 Singapore 4 2011 59900 Panama 68 2011 13600 Please help how to do it.. On Monday, October 13, 2014 9:14:27 PM UTC+5:30, Ian wrote: > On Mon, Oct 13, 2014 at 5:39 AM, Venugopal Reddy > > wrote: > > > Dear All, > > > > > > How to write a program for reading or parsing the XML file in Sub root Wise. > > > > I don't know what "Sub root Wise" is. You can find an overview of > > Python's XML parsing interfaces at > > https://docs.python.org/2/library/xml.html. I would recommend using > > the ElementTree API unless you have a specific reason to use something > > else. From davea at davea.name Tue Oct 14 06:23:47 2014 From: davea at davea.name (Dave Angel) Date: Tue, 14 Oct 2014 06:23:47 -0400 (EDT) Subject: Code Review for Paper, Rock, Scissors References: Message-ID: Revenant Wrote in message: > > .... > One thing I want to try to add is a "Press any key to continue" function that occurs at the end of the program when the user decides to quit. I looked at some options online, but haven't quite figured it out yet. > Use the curses function getch, as documented on: https://docs.python.org/3/howto/curses.html Or if you're on Windows, try msvcrt.getch. If you're writing code that needs to be portable, look at: http://code.activestate.com/recipes/577977-get-single-keypress/ > As previously stated, I am new to Python and would also like to see if any of you programming gurus have some suggestions about how I can simplify code, and also if there are any other good starter programs to work on to improve my skills. > > Thanks for reading! Code is below: > > > # Creates the main menu. > def menu(): > # Sets the scores to 0. > global playerscore > global compscore > global draws > playerscore = 0 > compscore = 0 > draws = 0 > menuselection = input('Please enter a selection: (Play/Help/About): ') Save yourself trouble by using the lower method on the result of each input function. I'll assume that for subsequent comments. > # Checks for an invalid selection. > while menuselection != 'Play' and menuselection != 'play' and menuselection != 'Help' and menuselection != 'help' \ > and menuselection != 'About' and menuselection != 'about': Simplify to: while menuselection not in ("play", "help", "about"): > print('You have entered an invalid selection.') > menuselection = input('\nPlease type a selection: (Play/Help/About): ') > else: > if menuselection == 'Play' or menuselection == 'play': > play() > elif menuselection == 'Help' or menuselection == 'help': > instructions() > else: > about() > func = {"play":play, "help":instructions, "about":about} func[menuselection]() > > # Creates the game. > def play(): > global playerscore > global compscore > global draws > # Player chooses Paper, Rock, or Scissors. > playerselect = input('\nPlease choose Paper, Rock, or Scissors: ') > # Checks for an invalid selection. > while playerselect != 'Paper' and playerselect != 'paper' and playerselect != 'Rock' and playerselect != 'rock' \ > and playerselect != 'Scissors' and playerselect != 'scissors': Again use playerselect not in ("pap... form > print('You have entered an invalid selection.') > playerselect = input('\nPlease choose Paper, Rock, or Scissors: ') > else: > if playerselect == 'Paper' or playerselect == 'paper': > print('\nYou have selected Paper.') > playerselect = 1 > elif playerselect == 'Rock' or playerselect == 'rock': > print('\nYou have selected Rock.') > playerselect = 2 > else: > print('\nYou have selected Scissors.') > playerselect = 3 > # Computer chooses Paper, Rock, or Scissors. > import random > compselect = random.randint(1, 3) You could make life a little easier by using 0 to 2 instead, here and above. > if compselect == 1: > print('The Computer has selected Paper') > elif compselect == 2: > print('The Computer has selected Rock.') > else: > print('The Computer has selected Scissors.') print (None, "paper", "rock", "scissors")[compselect]) The next section can be simplified a lot by exploiting some symmetries. diff = (playerselect - compselect ) % 3 This number will be zero for a draw, 1 for computer win, and 2 for player win. So you can have 3 cases below instead of 9. > # Results if player selects paper. > if playerselect == 1 and compselect == 1: > print('Draw!') > draws += 1 > score() > else: > if playerselect == 1 and compselect == 2: > print('Paper beats rock. You win!') > playerscore += 1 > score() > elif playerselect == 1 and compselect == 3: > print('Paper is beaten by scissors. You lose!') > compscore += 1 > score() > # Results if player selects rock. > if playerselect == 2 and compselect == 2: > print('Draw!') > draws += 1 > score() > else: > if playerselect == 2 and compselect == 1: > print('Rock is beaten by paper. You lose!') > compscore += 1 > score() > elif playerselect == 2 and compselect == 3: > print('Rock beats scissors. You win!') > playerscore += 1 > score() > # Results if player selects rock. > if playerselect == 3 and compselect == 3: > print('Draw!') > draws += 1 > score() > else: > if playerselect == 3 and compselect == 1: > print('Scissors beat paper. You win!') > playerscore += 1 > score() > elif playerselect == 3 and compselect == 2: > print('Scissors are beaten by rock. You lose!') > compscore += 1 > score() > again() This makes me a little nervous. You have mutual recursion going on between functions play and again. It probably won't matter here, but it's a bad habit to get into. What you really should do is something like def play_once (): (current body of play function, but without ref to again) def play (): while True: play_once () if not again(): break And change again so it returns True or False > > # Determines if the player wants to play another game. > def again(): > replay = input('\nDo you want to play again (Y/N)? ') > while replay != 'Y' and replay != 'y' and replay != 'N' and replay != 'n': > print('You have entered an invalid selection.') > replay = input('\nDo you want to play again (Y/N)? ') > else: > if replay == 'Y' or replay == 'y': > play() Replace the call to play () with return True > else: > print('\nThanks for playing!') > return False > > # Creates the instructions. > def instructions(): > print('\nPaper, Rock, Scissors is a simple game played against a computer opponent.') > print('The player will have a choice of selecting paper, rock, or scissors.') > print('The player\'s result will be compared with that of the computer to determine who wins the round.') > print('In the event that both the player and the computer have the same selection, the round will end in a tie.') > print('\nPaper beats rock but loses to scissors.') > print('\nRock beats scissors but loses to paper.') > print('\nScissors beats paper but loses to rock.') > print('\nGood luck, and have fun!\n') > menu() > > > # Creates the about section. > def about(): > print('\nPaper, Rock, Scissors\n\nVersion 1.0\n\nCreated by , 07 October 2014\n') > menu() > > > # Calculates score. > def score(): > print('\nCurrent Scores: ') > print('\nPlayer Score:', playerscore) > print('\nComputer Score:', compscore) > print('\nDraws:', draws) > > > # Start of program operations. > print('Welcome to Paper, Rock, Scissors!\n') > menu() > -- DaveA From davea at davea.name Tue Oct 14 06:30:42 2014 From: davea at davea.name (Dave Angel) Date: Tue, 14 Oct 2014 06:30:42 -0400 (EDT) Subject: How to install and run a script? References: <9e37d62a-9391-44fc-8fa2-089ae81acfc5@googlegroups.com> <6d282d09-fa5f-4d3a-aaed-5c15f8f9b56f@googlegroups.com> <543CB26F.8020107@gmail.com> Message-ID: Michael Torrie Wrote in message: > On 10/12/2014 08:05 PM, ryguy7272 wrote: >> Ahhhhh!!! I didn't know I needed to run it from the command prompt! Ok, not it makes sense, and everything works. >> >> Thanks to all! > > You don't have to run python apps from the command line. Apps that > throw up windows can usually be run by double-clicking the py file in > windows. But apps that communicate solely on the terminal or console > have to be run in that environment. > > > If the command he's typing starts python xxxx Then he needs to run it from the cmd prompt. -- DaveA From __peter__ at web.de Tue Oct 14 06:43:51 2014 From: __peter__ at web.de (Peter Otten) Date: Tue, 14 Oct 2014 12:43:51 +0200 Subject: Jython or Pyton issue-- Kindly Help me.... References: <91eb3378-958d-45e0-8741-a800ae681260@googlegroups.com> <552277f6-fb5b-44de-a0d4-7c7fe480d265@googlegroups.com> Message-ID: Venugopal Reddy wrote: > Ok, I will explain my problem in details : > > I have below XML: > > > > > 1 > 2008 > 2009> > 141100 > > > > > 4 > 2011 > 59900 > > > > 68 > 2011 > 13600 > > > > > > > From I want output below format: > > Countryname Rank Year gdppc > Liechtenstein 1 2008 141100 > Singapore 4 2011 59900 > Panama 68 2011 13600 > > Please help how to do it.. Read up on elementtree: http://pymotw.com/2/xml/etree/ElementTree/parse.html You can load the data from the file with parse(), get the countries with findall(), the name with country_node.attrib["name"], and rank, year and gdppc with country_node.find("rank").text etc. If you run into problems come back with some code of yours. From robin at reportlab.com Tue Oct 14 07:20:57 2014 From: robin at reportlab.com (Robin Becker) Date: Tue, 14 Oct 2014 12:20:57 +0100 Subject: windows 7 pysqlite build error In-Reply-To: References: <543BA027.8010504@chamonix.reportlab.co.uk> <2ido3a9jlp6okee0aju5dgvq7qmku4ht49@4ax.com> Message-ID: <543D0719.4080302@chamonix.reportlab.co.uk> On 13/10/2014 22:00, Terry Reedy wrote: > On 10/13/2014 4:31 PM, Dennis Lee Bieber wrote: >> On Mon, 13 Oct 2014 10:49:27 +0100, Robin Becker >> declaimed the following: >> >>>> c:\users\rptlab\tmp\tmcallister\build\pysqlite\src\connection.h(33) : fatal >>>> error C1083: Cannot open include file: 'sqli >>>> te3.h': No such file or directory > > Did \n get stuck in the name of the file in connection.h, or is that purely an > artifact of the error reporting? > it's an artefact. >>>> error: command 'c:\\Program Files (x86)\\Microsoft Visual Studio >>>> 9.0\\VC\\BIN\\amd64\\cl.exe' failed with exit status 2 >> >>> I do have the various compilers installed and other extensions are building OK, >>> so is this an error in pysqlite or in my general setup? The include path looks >>> like it might relate to Python builds. I suppose it's feasible that pyqslite >>> builds need to be installed specially. I don't remember this happening on my old >>> win32 XP system, but that died and I now am forced to use 64bit win7. >> >> Off hand, you don't have the SQLite3 /development package/. >> >> PySQLite is just an adapter to the sqlite3 DLL; the sqlite3.h file >> would be part of the source code for sqlite3, not part of pysqlite itself. >> > > OK so I need to install sqlite3 prior to the pip install. This stuff gets tested more on linux and I suppose it's already there. -- Robin Becker From ryanshuell at gmail.com Tue Oct 14 08:16:43 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Tue, 14 Oct 2014 05:16:43 -0700 (PDT) Subject: I'm looking to start a team of developers, quants, and financial experts, to setup and manage an auto-trading-money-making-machine Message-ID: <2447a61b-57c7-4477-adf1-d5f73588b8bb@googlegroups.com> I'm looking to start a team of developers, quants, and financial experts, to setup and manage an auto-trading-money-making-machine #1) Setup a VM; must be a Windows machine (maybe Azure) #2) Load & configure the software (Matlab, Python, R, Excel, and SQL Server) #3) Develop and test code (Matlab or Python....most likely) #4) Hook into trading tool for order execution (system to be determined; depends on API) #5) Setup a corporate business structure (this is virtually done, we just need to flip a switch) #5) Shop around for clients (if we have a real money-making machine, this should be super-easy) Just so you know, I've done this kind of thing before, using Excel and VBA, as well as an execution program called Sterling Trader. It was quite profitable, and typically had less than 1 down day in a 22-trading-day month. The system was profitable about 95% of the time. However, I don't want to use Excel for this project; I want this to be a real system. I think we can use Matlab, or Python. If this is project turns out to be very profitable, I know we can raise capital very quickly and very easily. At the beginning, I believe it will take a fair amount of work, but if we put in the effort, we can have a system that constantly monitors the equity markets during trading hours, finds the best profit opportunities, according to the trading strategies that we deploy, and once it is setup and running, we really won't have to do a whole lot. Ideally, once you turn it on, the whole process will require almost no intervention. I know this can be done; many banks have groups that do exactly what I'm proposing here. The top hedge funds do this too. In conclusion, I think the trading strategies that we choose to employ should be easy to setup and test (a well-defined Google search will reveal countless trading strategies). I think getting the data should be pretty easy as well (we can load all kinds of indices into the tool). I think the hard part will be developing the automation processes; the tool will have to follow MANY rules and run all by itself. Finally, as neither Matlab nor Python are really execution tools, we'll have to connect to some type of system that allows us to send trade orders. This may, or may not, present somewhat of a challenge. As an alternative, if we decide we don't want to manage money for other people, we could setup the business as a subscription service, and charge users, let's say $25k/year or whatever, and let people run simulations in our hosted environment, and they can manage money themselves...we simply provide all kinds of analytic tools for them to do what they want to do. Hopefully everyone is close to New York City or Washington DC, or somewhere close, like Boston or Philadelphia. From skip.montanaro at gmail.com Tue Oct 14 08:28:13 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 14 Oct 2014 07:28:13 -0500 Subject: I'm looking to start a team of developers, quants, and financial experts, to setup and manage an auto-trading-money-making-machine In-Reply-To: <2447a61b-57c7-4477-adf1-d5f73588b8bb@googlegroups.com> References: <2447a61b-57c7-4477-adf1-d5f73588b8bb@googlegroups.com> Message-ID: On Tue, Oct 14, 2014 at 7:16 AM, ryguy7272 wrote: > I'm looking to start a team of developers, quants, and financial experts, > to setup and manage an auto-trading-money-making-machine > Two things: 1. That's obviously much easier said than done. (I happen to develop automated trading systems for a trading firm in Chicago. Like other firms, we have lots of developers, quants and financial experts on staff. Even for a well-established company, success isn't guaranteed.) 2. You'd probably be better off with a posting to the Python Job Board (once it's back up and running). Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From marko at pacujo.net Tue Oct 14 08:28:51 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 14 Oct 2014 15:28:51 +0300 Subject: I'm looking to start a team of developers, quants, and financial experts, to setup and manage an auto-trading-money-making-machine References: <2447a61b-57c7-4477-adf1-d5f73588b8bb@googlegroups.com> Message-ID: <87tx36ltrw.fsf@elektro.pacujo.net> ryguy7272 : > I'm looking to start a team of developers, quants, and financial > experts, to setup and manage an auto-trading-money-making-machine This has already been done: http://en.wikipedia.org/wiki/Sampo Marko From vijnaana at gmail.com Tue Oct 14 09:33:10 2014 From: vijnaana at gmail.com (vijnaana bhairava) Date: Tue, 14 Oct 2014 06:33:10 -0700 (PDT) Subject: CLI framework using python In-Reply-To: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> References: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> Message-ID: Hi Folks, The requirement is to develop a CLI framework in python for a linux router. The suggestions i got is to use PyCli/Cliff. Not sure which would be the right choice! Also, a few APIs are mentioned here: https://pythonhosted.org/pyCLI/#module-cli.app Since i couldn't find any actual implementation which uses pyCli, i can't figure out how to make use of pyCLI. Another question i have is whether it uses argparse? If so, what value add does PYCLI do? Regards, vij On Thursday, October 9, 2014 5:50:51 PM UTC+5:30, vijnaana bhairava wrote: > Hi, > > > > I need to develop a python CLI framework. > > > > For example if i need to set an ip address in linux: > > > > ifconfig eth0 172.16.25.125 > > > > I should be able to use python to do the above. > > > > 1. The user will execute a python script to which i will pass the params eth0 and ip address (something like ifconf.py eth0 172.16.25.125) > > > > 2. Within the script i grab the params and do something to the effect of user executing 'ifconfig eth0 172.16.25.125' from the shell. > > > > 3. There are other such commands for which i will be using python scripts. I came across pyCLI, but it doesn't have much documentation, so couldn't figure out how to move forward. > > > > 4. The CLI framework needs to reuse code so i didn't want to use pure python and develop a framework from scratch. Rather use something like pyCLI/CLIFF. > > > > The problem is lack of documentation with examples on how to use the above. > > > > Any guidance would be greatly appreciated. > > > > Regards & Thanks, > > Vij From rosuav at gmail.com Tue Oct 14 09:35:58 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Oct 2014 00:35:58 +1100 Subject: Code Review for Paper, Rock, Scissors In-Reply-To: References: Message-ID: On Tue, Oct 14, 2014 at 7:04 PM, Revenant wrote: > As previously stated, I am new to Python and would also like to see if any of you programming gurus have some suggestions about how I can simplify code, and also if there are any other good starter programs to work on to improve my skills. > Hi! Happy to help out. But first, there's one meta-suggestion that I'd like to make: Use something other than Google Groups. As shown by the line above, Google Groups has some issues with line breaks and text wrapping; and it gets much worse when you reply to someone else's post. I suggest using the mailing list instead: https://mail.python.org/mailman/listinfo/python-list Also, it can be helpful to state what version of Python you're using, and on what platform. Your "press any key to quit" request suggests you're probably invoking the script using a GUI, quite possibly Windows, but that's far from certain; and as Dave's response shows, the solutions depend on platform. I'm presuming you're using some 3.x version of Python, as you use input() and print() functions, but I can't tell whether you're on 3.2, 3.3, 3.4, or even an unreleased 3.5. It's not likely to make a huge amount of difference with a script this simple, but as a general rule, more information is better than less. So, on to the code! > # Creates the main menu. > def menu(): > # Sets the scores to 0. > global playerscore > global compscore > global draws > playerscore = 0 > compscore = 0 > draws = 0 You're importing these globals into several places that don't need them. The menu shouldn't have to concern itself with these scores; you could initialize them all to zero at top-level, and then keep the different functions more self-contained. The displaying of the menu doesn't logically involve zeroing out the scores; imagine making the very slight (and quite logical) change of having the full menu redisplayed after each game, instead of just having the "Again? (Y/N)" prompt - suddenly your scores aren't getting carried over. > menuselection = input('Please enter a selection: (Play/Help/About): ') > # Checks for an invalid selection. > while menuselection != 'Play' and menuselection != 'play' and menuselection != 'Help' and menuselection != 'help' \ > and menuselection != 'About' and menuselection != 'about': > print('You have entered an invalid selection.') > menuselection = input('\nPlease type a selection: (Play/Help/About): ') > else: > if menuselection == 'Play' or menuselection == 'play': > play() > elif menuselection == 'Help' or menuselection == 'help': > instructions() > else: > about() The "else" clause on a while loop isn't necessary here, because you're not using break. All you need is to put your code outside the loop. Alternatively, you can combine the verification and iteration into one pass, which reduces redundancy and makes it easier to add more options. I'm also incorporating some suggestions already made, including Dave's dispatch dictionary. func = {"play":play, "help":instructions, "about":about} while True: menuselection = input('Please enter a selection: (Play/Help/About): ').lower() if menuselection in func: break print('You have entered an invalid selection.') func[menuselection]() Note how the loop condition is now inside the loop ("if ...: break"), with the while statement simply creating an infinite loop ("while True:"). > def play(): > # Player chooses Paper, Rock, or Scissors. > playerselect = input('\nPlease choose Paper, Rock, or Scissors: ') Try to avoid comments that simply state what the next line(s) of code do. At best, they're redundant; at worst, they're confusing, because they can get out of sync with the code. Imagine adding a fourth option (Claw Hammer) and forgetting to change the comment. (Why claw hammer? http://www.theregister.co.uk/2003/06/09/the_bastard_interviewer_from_hell/ ) > import random It's much more common to put your imports at the top of the script, rather than inside a function. > # Creates the instructions. > def instructions(): > print('\nPaper, Rock, Scissors is a simple game played against a computer opponent.') > print('The player will have a choice of selecting paper, rock, or scissors.') > print('The player\'s result will be compared with that of the computer to determine who wins the round.') > print('In the event that both the player and the computer have the same selection, the round will end in a tie.') > print('\nPaper beats rock but loses to scissors.') > print('\nRock beats scissors but loses to paper.') > print('\nScissors beats paper but loses to rock.') > print('\nGood luck, and have fun!\n') > menu() As noted elsewhere, you have mutual recursion happening here. That's not an advised technique in Python, as you can blow your stack (there's no tail call optimization here). Much more common would be to have self-contained functions that perform one job (in this case, displaying the instructions on the console), and have looping done in the places that want looping - probably inside menu(). Incidentally, this function doesn't *create* anything. Your comment (which would be better as a docstring, fwiw) is slightly confusing here. > # Creates the about section. > def about(): > print('\nPaper, Rock, Scissors\n\nVersion 1.0\n\nCreated by , 07 October 2014\n') > menu() Huh, I didn't know your name was actually :) > # Calculates score. > def score(): > print('\nCurrent Scores: ') > print('\nPlayer Score:', playerscore) > print('\nComputer Score:', compscore) > print('\nDraws:', draws) > > > # Start of program operations. > print('Welcome to Paper, Rock, Scissors!\n') > menu() Suggestion: Where possible, follow a general policy of "Define Before Use". For any given global name (like function names), the first occurrence in the file should be its definition, and all usage should be lower in the file than that. Once you clean up the mutual recursion, you'll be able to lay your code out like this; there'll be a single menu() function near the bottom, and functions like score() will be much higher up, as they have almost no dependencies. It'd look something like this (function bodies and blank lines elided for brevity): import random playerscore = compscore = draws = 0 def instructions(): def about(): def score(): def again(): # which will return True or False, as per Dave's suggestion def play(): def menu(): print("Welcome") menu() When someone comes looking at a program like this, s/he can see exactly what depends on what. There can be exceptions, of course (sometimes mutual recursion really is the right thing to do, especially with tree-walking routines), but those can then be noted with comments ("Mutually recursive with xyz()."), or in some cases may be obvious from the names. In any case, the bulk of most programs can be written in this style, and it does improve clarity. Hope that's of value. Like all advice, it's just one person's opinion, and you're most welcome to reject it; but you did ask for code review, so I'm hoping you'll at least know *why* you're rejecting any piece of advice :) All the best! ChrisA From galois271 at gmail.com Tue Oct 14 09:36:01 2014 From: galois271 at gmail.com (Chuck) Date: Tue, 14 Oct 2014 06:36:01 -0700 (PDT) Subject: Sqlite3 help Message-ID: <4a691d82-be63-4355-8898-0ecbd9cb16bd@googlegroups.com> I am building a simple podcast program where I download all the data from a feed with feedparser and store the data in sqlite3. I am spanking new to sqlite and database programming. Should I create the database in the __init__ method of my class, or is that a bad idea. I haven't done any designing that included databases. Thanks! Chuck From jhibschman at gmail.com Tue Oct 14 09:38:44 2014 From: jhibschman at gmail.com (Johann Hibschman) Date: Tue, 14 Oct 2014 09:38:44 -0400 Subject: I'm looking to start a team of developers, quants, and financial experts, to setup and manage an auto-trading-money-making-machine References: <2447a61b-57c7-4477-adf1-d5f73588b8bb@googlegroups.com> <87tx36ltrw.fsf@elektro.pacujo.net> Message-ID: Marko Rauhamaa writes: > ryguy7272 : > >> I'm looking to start a team of developers, quants, and financial >> experts, to setup and manage an auto-trading-money-making-machine > > This has already been done: http://en.wikipedia.org/wiki/Sampo And mocked by MST3K ("sampo means flavor!"): https://www.youtube.com/watch?v=cdfUkrbNvwA -Johann (whose cousins are all Mattinens and Nikkanens) From rosuav at gmail.com Tue Oct 14 09:43:16 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Oct 2014 00:43:16 +1100 Subject: CLI framework using python In-Reply-To: References: <274771d2-4a11-40fe-bc31-ccfaa7d32690@googlegroups.com> Message-ID: On Wed, Oct 15, 2014 at 12:33 AM, vijnaana bhairava wrote: > Another question i have is whether it uses argparse? > If so, what value add does PYCLI do? It depends what you mean by "CLI framework". If you simply mean something like hg, where you have subcommands and options and so on, all you really need is argument parsing. Take the simplest possible solution and run with it! ChrisA From giordani.leonardo at gmail.com Tue Oct 14 10:08:34 2014 From: giordani.leonardo at gmail.com (Leonardo Giordani) Date: Tue, 14 Oct 2014 16:08:34 +0200 Subject: Short syntax for try/pass Message-ID: Hi all, a lot of times the following pattern pops out in Python code: try: somecode except SomeException: pass A very simple example could be if you want to process a list that may be empty def process_list(lst): try: lst[0] = lst[0] + 1 except IndexError: pass or in more complex cases in which however an exception just signals that there is nothing to do there. Converting the code to a non-EAFP version, for example if len(lst) != 0: lst[0] = lst[0] + 1 is in my opinion generally against the Python nature, since it relies on a specific check on the object, instead of trusting the object as being able to either satisfy the request or raise an exception. That is, this solution is non-polymorphic. In such cases sometimes ABC may help, but generally speaking they it is not always the case of being an instance of a given ABC or not. The problem here is if the code raises an exception or not. Would it be feasible to propose a short syntax like this? pass SomeException: somecode where the above example would become: pass IndexError: lst[0] = lst[0] + 1 I could not find if such a syntax has been already discussed elsewhere, so please let me know if this is the case. Otherwise, what do you think about it? Thank you Leonardo Leonardo Giordani @tw_lgiordani - lgiordani.com My profile on About.me - My GitHub page -------------- next part -------------- An HTML attachment was scrubbed... URL: From songofacandy at gmail.com Tue Oct 14 10:15:35 2014 From: songofacandy at gmail.com (Naoki INADA) Date: Tue, 14 Oct 2014 07:15:35 -0700 (PDT) Subject: CLI framework using python In-Reply-To: References: Message-ID: <1413296134785.c39ab9ad@Nodemailer> Click_ is another CLI framework. It support multi-level nested command like git and it has some nice utilities. I love it's design. .. _click: http://click.pocoo.org/3/ ? Sent from Mailbox On Tue, Oct 14, 2014 at 10:35 PM, vijnaana bhairava wrote: > Hi Folks, > The requirement is to develop a CLI framework in python for a linux router. > The suggestions i got is to use PyCli/Cliff. Not sure which would be the right choice! Also, a few APIs are mentioned here: > https://pythonhosted.org/pyCLI/#module-cli.app > Since i couldn't find any actual implementation which uses pyCli, > i can't figure out how to make use of pyCLI. > Another question i have is whether it uses argparse? > If so, what value add does PYCLI do? > Regards, > vij > On Thursday, October 9, 2014 5:50:51 PM UTC+5:30, vijnaana bhairava wrote: >> Hi, >> >> >> >> I need to develop a python CLI framework. >> >> >> >> For example if i need to set an ip address in linux: >> >> >> >> ifconfig eth0 172.16.25.125 >> >> >> >> I should be able to use python to do the above. >> >> >> >> 1. The user will execute a python script to which i will pass the params eth0 and ip address (something like ifconf.py eth0 172.16.25.125) >> >> >> >> 2. Within the script i grab the params and do something to the effect of user executing 'ifconfig eth0 172.16.25.125' from the shell. >> >> >> >> 3. There are other such commands for which i will be using python scripts. I came across pyCLI, but it doesn't have much documentation, so couldn't figure out how to move forward. >> >> >> >> 4. The CLI framework needs to reuse code so i didn't want to use pure python and develop a framework from scratch. Rather use something like pyCLI/CLIFF. >> >> >> >> The problem is lack of documentation with examples on how to use the above. >> >> >> >> Any guidance would be greatly appreciated. >> >> >> >> Regards & Thanks, >> >> Vij > -- > https://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Tue Oct 14 10:22:03 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Oct 2014 01:22:03 +1100 Subject: Short syntax for try/pass In-Reply-To: References: Message-ID: On Wed, Oct 15, 2014 at 1:08 AM, Leonardo Giordani wrote: > a lot of times the following pattern pops out in Python code: > > try: > somecode > except SomeException: > pass > > Converting the code to a non-EAFP version, for example > > if len(lst) != 0: > lst[0] = lst[0] + 1 This could be just "if lst:", but I agree, LBYL is not Python's style (and isn't always possible anyway). You can at least squish it up onto less lines, which might look better: try: lst[0] += 1 except IndexError: pass Alternatively, you can use this style: from contextlib import suppress with suppress(IndexError): lst[0] += 1 ChrisA From ned at nedbatchelder.com Tue Oct 14 10:28:11 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Tue, 14 Oct 2014 10:28:11 -0400 Subject: Short syntax for try/pass In-Reply-To: References: Message-ID: On 10/14/14 10:08 AM, Leonardo Giordani wrote: > Would it be feasible to propose a short syntax like this? > > pass SomeException: > somecode > > where the above example would become: > > pass IndexError: > lst[0] = lst[0] + 1 > > I could not find if such a syntax has been already discussed elsewhere, > so please let me know if this is the case. > > Otherwise, what do you think about it? PEP 463 proposes a short syntax for this use case: http://legacy.python.org/dev/peps/pep-0463/ I'm not sure what became of it. -- Ned Batchelder, http://nedbatchelder.com From rosuav at gmail.com Tue Oct 14 10:39:19 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Oct 2014 01:39:19 +1100 Subject: Short syntax for try/pass In-Reply-To: References: Message-ID: On Wed, Oct 15, 2014 at 1:28 AM, Ned Batchelder wrote: > PEP 463 proposes a short syntax for this use case: > http://legacy.python.org/dev/peps/pep-0463/ > > I'm not sure what became of it. Not quite; PEP 463 is about the case where you then want a different value instead. I'm fairly sure the PEP is in a "virtually rejected" state, but I nudged about it a couple of times and didn't get any certain response on the subject. ChrisA From shivaji_tn at yahoo.com Tue Oct 14 10:42:21 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Tue, 14 Oct 2014 14:42:21 +0000 (UTC) Subject: downloading from links within a webpage Message-ID: Hi, Here is a small code that I wrote that downloads images from a webpage url specified (you can limit to how many downloads you want). However, I am looking at adding functionality and searching external links from this page and downloading the same number of images from that page as well.(And limiting the depth it can go to) Any ideas? (I am using Python 3.4 & I am a beginner) import urllib.request import re url="http://www.abc.com" pagehtml = urllib.request.urlopen(url) myfile = pagehtml.read() matches=re.findall(r'http://\S+jpg|jpeg',str(myfile)) for urltodownload in matches[0:50]: imagename=urltodownload[-12:] urllib.request.urlretrieve(urltodownload,imagename) print('Done!') Thanks, Shiva From rosuav at gmail.com Tue Oct 14 10:54:07 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Oct 2014 01:54:07 +1100 Subject: downloading from links within a webpage In-Reply-To: References: Message-ID: On Wed, Oct 15, 2014 at 1:42 AM, Shiva wrote: > Here is a small code that I wrote that downloads images from a webpage url > specified (you can limit to how many downloads you want). However, I am > looking at adding functionality and searching external links from this page > and downloading the same number of images from that page as well.(And > limiting the depth it can go to) > > Any ideas? (I am using Python 3.4 & I am a beginner) First idea: Use wget, it does all this for you :) ChrisA From joel.goldstick at gmail.com Tue Oct 14 10:57:22 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Tue, 14 Oct 2014 10:57:22 -0400 Subject: downloading from links within a webpage In-Reply-To: References: Message-ID: On Tue, Oct 14, 2014 at 10:54 AM, Chris Angelico wrote: > On Wed, Oct 15, 2014 at 1:42 AM, Shiva > wrote: >> Here is a small code that I wrote that downloads images from a webpage url >> specified (you can limit to how many downloads you want). However, I am >> looking at adding functionality and searching external links from this page >> and downloading the same number of images from that page as well.(And >> limiting the depth it can go to) >> >> Any ideas? (I am using Python 3.4 & I am a beginner) > > First idea: Use wget, it does all this for you :) You might look at Requests and BeautifulSoup python modules. Requests is easier for many things than urllib. BS is an HTML parser that may be easier, and more powerful than what you can do with regex > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From slyost at ilstu.edu Tue Oct 14 11:08:09 2014 From: slyost at ilstu.edu (slyost at ilstu.edu) Date: Tue, 14 Oct 2014 08:08:09 -0700 (PDT) Subject: scipy errors and gfortran In-Reply-To: <18d6bf8c-4265-49cc-b49c-3795b615aa44@googlegroups.com> References: <18d6bf8c-4265-49cc-b49c-3795b615aa44@googlegroups.com> Message-ID: On Monday, October 13, 2014 1:14:27 PM UTC-5, sly... at ilstu.edu wrote: > Trying to get scipy 0.14 running on python 3.4.1 on SLES 11 SP2 LINUX system. > > Scipy seemed to compile fine using the command "python setup.py install" but when I try the scipy.test("full"), I get errors regarding gfortran. I am using GCC(gfortran) version 4.9.1. > > > > The error states that /usr/lib/libgfortran.so.3: version 'gfortran_1.4' was not found (required by....). Google tells me that this is the name of the symbol node whatever that means. > > > > What do I need to do to fix these errors? Please help. Was able to fix the issue with an export of LD_LIBRARY_PATH, thank goodness. From ryanshuell at gmail.com Tue Oct 14 11:16:25 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Tue, 14 Oct 2014 08:16:25 -0700 (PDT) Subject: I'm looking to start a team of developers, quants, and financial experts, to setup and manage an auto-trading-money-making-machine In-Reply-To: References: <2447a61b-57c7-4477-adf1-d5f73588b8bb@googlegroups.com> <87tx36ltrw.fsf@elektro.pacujo.net> Message-ID: <6948a57f-52ca-4446-8193-a27c3b4a1d88@googlegroups.com> On Tuesday, October 14, 2014 9:38:55 AM UTC-4, Johann Hibschman wrote: > Marko Rauhamaa writes: > > > > > ryguy7272 : > > > > > >> I'm looking to start a team of developers, quants, and financial > > >> experts, to setup and manage an auto-trading-money-making-machine > > > > > > This has already been done: http://en.wikipedia.org/wiki/Sampo > > > > And mocked by MST3K ("sampo means flavor!"): > > > > https://www.youtube.com/watch?v=cdfUkrbNvwA > > > > -Johann (whose cousins are all Mattinens and Nikkanens) Good stuff! Very funny!! From rustompmody at gmail.com Tue Oct 14 11:31:56 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 14 Oct 2014 08:31:56 -0700 (PDT) Subject: downloading from links within a webpage In-Reply-To: References: Message-ID: <6ad706a4-7c9c-43e0-b9d9-0eedc3cec30f@googlegroups.com> On Tuesday, October 14, 2014 8:12:56 PM UTC+5:30, Shiva wrote: > Hi, > Here is a small code that I wrote that downloads images from a webpage url > specified (you can limit to how many downloads you want). However, I am > looking at adding functionality and searching external links from this page > and downloading the same number of images from that page as well.(And > limiting the depth it can go to) > Any ideas? (I am using Python 3.4 & I am a beginner) > import urllib.request > import re Read this: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 From anuragpatibandla7 at gmail.com Tue Oct 14 11:57:56 2014 From: anuragpatibandla7 at gmail.com (anuragpatibandla7 at gmail.com) Date: Tue, 14 Oct 2014 08:57:56 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects Message-ID: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> I have a dictionary that looks like this: {"1":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, "2":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, "3":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, "4":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}} Now if I have 100 objects like these and I need to split them into 3 smaller dicts in a ratio 2:3:5, how could I do that? I tried using numpy.random.choice(), but it says it needs to be a 1-d array. Can someone please help with this? Thanks From davea at davea.name Tue Oct 14 13:02:12 2014 From: davea at davea.name (Dave Angel) Date: Tue, 14 Oct 2014 13:02:12 -0400 (EDT) Subject: Parsing Python dictionary with multiple objects References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: anuragpatibandla7 at gmail.com Wrote in message: > I have a dictionary that looks like this: > {"1":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > "2":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > "3":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > "4":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}} > > Now if I have 100 objects like these and I need to split them into 3 smaller dicts in a ratio 2:3:5, how could I do that? I really have no idea what that means. You have 100 dicts of dicts? Are the keys unique? If so, you could combine them with a loop of update. > I tried using numpy.random.choice(), but it says it needs to be a 1-d array. > How about random.choice? It needs a sequence. To get anything more concrete, you need to specify Python version, and make a clearer problem statement, perhaps with example of what you expect. -- DaveA From gianniboncompagni at mail.com Tue Oct 14 13:20:20 2014 From: gianniboncompagni at mail.com (MICHELE CALZOLARI CREDIT SUISSE ASSOSIM) Date: Tue, 14 Oct 2014 10:20:20 -0700 (PDT) Subject: -- redacted -- Message-ID: -- redacted -- From davea at davea.name Tue Oct 14 13:47:20 2014 From: davea at davea.name (Dave Angel) Date: Tue, 14 Oct 2014 13:47:20 -0400 (EDT) Subject: downloading from links within a webpage References: Message-ID: Shiva Wrote in message: > Hi, > > Here is a small code that I wrote that downloads images from a webpage url > specified (you can limit to how many downloads you want). However, I am > looking at adding functionality and searching external links from this page > and downloading the same number of images from that page as well.(And > limiting the depth it can go to) > > Any ideas? (I am using Python 3.4 & I am a beginner) > > import urllib.request > import re > url="http://www.abc.com" > > pagehtml = urllib.request.urlopen(url) > myfile = pagehtml.read() > matches=re.findall(r'http://\S+jpg|jpeg',str(myfile)) > > > for urltodownload in matches[0:50]: > imagename=urltodownload[-12:] > urllib.request.urlretrieve(urltodownload,imagename) > > print('Done!') > > Thanks, > Shiva > > I'm going to make the wild assumption that you can safely do both parses using regex, and that finding the jpegs works well enough with your present one. First thing is to make most of your present code a function fetch(), starting with pagehtml and ending before the print. The function should take two arguments, url and depthlimit. Now, at the end of the function, add something like If depthlimit > 0: matches = ... some regex that finds links for link in matches [:40]: fetch (link, depthlimit - 1) Naturally, the rest of the top level code needs to be moved after the function definition, and is called by doing something like: fetch (url, 10) to have a depth limit of 10. -- DaveA From tntsugar at googlemail.com Tue Oct 14 14:13:03 2014 From: tntsugar at googlemail.com (tntsugar at googlemail.com) Date: Tue, 14 Oct 2014 20:13:03 +0200 Subject: strange thing that disturbs Message-ID: hello guys, for half an hour now i am searching for something simple... not IRC, not Fakebook, not Twitter... simply an email where i can ask a question to a problem i have in python 3.4.2 and the tkinter (it doesnt seem to be present and doesnt react to the "python -m tkinter" -module not present-)... can you please tell me where i can find help here... i would like to learn python but... ???? greetings G. p.s. i dont use twitter, irc or fakebook... -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip.montanaro at gmail.com Tue Oct 14 14:32:36 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 14 Oct 2014 13:32:36 -0500 Subject: strange thing that disturbs In-Reply-To: References: Message-ID: On Tue, Oct 14, 2014 at 1:13 PM, wrote: > it doesnt seem to be present and doesnt react to the "python -m tkinter" > -module not present > I don't know how it's spelled in 3.4.x, but in 2.7 it's spelled "Tkinter". Give that a try. (Sorry, no 3.4 install handy or I'd verify it myself.) The other alternative is that the tkinter module wasn't built when you installed Python because the build system couldn't find Tcl or Tk libraries to link to. If that's the case, let us know your computing platform (Windows, Linux/Unix, MacOSX) and how 3.4 was installed on your system. Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip.montanaro at gmail.com Tue Oct 14 15:22:58 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 14 Oct 2014 14:22:58 -0500 Subject: strange thing that disturbs In-Reply-To: References: Message-ID: Adding python-list back into the CC list. I know nothing about Windows. Perhaps someone else here can help. (Sorry about the top post all you bottom post mavens. It seemed warranted in this case...) Skip On Tue, Oct 14, 2014 at 2:10 PM, wrote: > hi, > > thank you so much for the quick reply!!!! :-D > > i run win7 home premium... > > during the installation of python 3.4.2 i have seen the tcl/tk option > activated! > > the change between the T and t i tried but still the module wasnt found... > > ... ... ... > > its strange... you know... i dealed with C, C++, and many other > programming languages and it was ALWAYS the same... never it was easy and > always there was a problem with the instalation or the editor... even > buying a book never it was like described in the book and i got stuck at a > point where the example in the book and the software didnt match... so that > happening noow isnt something new to me... > > another question that you might be able to help me is if you can recommend > me a simple editor for writing python programs... right now i took IEP... > any tips? > > be well and thank you! > > GD > > p.s. i only installed 3.4.2... thats enough right? or do i have to install > the 2.X version as well? > > 2014-10-14 20:32 GMT+02:00 Skip Montanaro : > >> >> On Tue, Oct 14, 2014 at 1:13 PM, wrote: >> >>> it doesnt seem to be present and doesnt react to the "python -m tkinter" >>> -module not present >>> >> >> I don't know how it's spelled in 3.4.x, but in 2.7 it's spelled >> "Tkinter". Give that a try. (Sorry, no 3.4 install handy or I'd verify it >> myself.) >> >> The other alternative is that the tkinter module wasn't built when you >> installed Python because the build system couldn't find Tcl or Tk libraries >> to link to. If that's the case, let us know your computing platform >> (Windows, Linux/Unix, MacOSX) and how 3.4 was installed on your system. >> >> Skip >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wolfgang.maier at biologie.uni-freiburg.de Tue Oct 14 15:52:39 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Tue, 14 Oct 2014 21:52:39 +0200 Subject: stressing problem with Python < 3.3.3 / 2.7.6 and Mac OS 10.9 Mavericks Message-ID: Hi, I'm not a regular MacPython user, but today I had to build Mac wheels for different versions of Python. To test the wheel files I set up a fresh Mac OS 10.9 Mavericks and and installed Python 3.2, 3.3, 3.4 from the python.org download page on it. Then I struggled for the rest of the afternoon to try to figure out why Python 3.2 crashed when I used my package in interactive mode until I finally realized that it's not the package but Python that's responsible. Turns out that I had run into http://bugs.python.org/issue18458 which probably every MacPython user here is so familiar with that the download page doesn't even mention it ? ;) Seriously, I think the official download page for a OS shouldn't offer me a version that will not work well with the latest version of that OS without a warning. Why not add such a warning (like: versions below will crash in interactive mode on Mac OS 10.9) in the list of downloads at https://www.python.org/downloads/mac-osx/ between Python 2.7.6 (the first version with the issue fixed) and Python 3.2.5 (the last affected version). Wolfgang From nad at acm.org Tue Oct 14 16:30:08 2014 From: nad at acm.org (Ned Deily) Date: Tue, 14 Oct 2014 13:30:08 -0700 Subject: stressing problem with Python < 3.3.3 / 2.7.6 and Mac OS 10.9 Mavericks References: Message-ID: In article , Wolfgang Maier wrote: > I'm not a regular MacPython user, but today I had to build Mac wheels > for different versions of Python. To test the wheel files I set up a > fresh Mac OS 10.9 Mavericks and and installed Python 3.2, 3.3, 3.4 from > the python.org download page on it. Then I struggled for the rest of the > afternoon to try to figure out why Python 3.2 crashed when I used my > package in interactive mode until I finally realized that it's not the > package but Python that's responsible. > > Turns out that I had run into http://bugs.python.org/issue18458 which > probably every MacPython user here is so familiar with that the download > page doesn't even mention it ? ;) > > Seriously, I think the official download page for a OS shouldn't offer > me a version that will not work well with the latest version of that OS > without a warning. Why not add such a warning (like: versions below will > crash in interactive mode on Mac OS 10.9) in the list of downloads at > https://www.python.org/downloads/mac-osx/ between Python 2.7.6 (the > first version with the issue fixed) and Python 3.2.5 (the last affected > version). Sorry you ran into that problem. Unfortunately, that's a general problem when using older versions of Python that are in security-fix-only mode, e.g. those no longer in active maintenance mode. Currently only 3.2.x and 3.3.x are in that category. "The only changes made to a security branch are those fixing issues exploitable by attackers such as crashes, privilege escalation and, optionally, other issues such as denial of service attacks. Any other changes are not considered a security risk and thus not backported to a security branch." https://docs.python.org/devguide/devcycle.html#security-branches Fixes for new operating system releases do not fall in this category. There are certainly other problems that one will run into on platform releases newer than those supported and tested at the time of the final maintenance release. However, we did add a warning about this particular issue to the release page of the final security release of 2.6.x. That warning is now copied into the 3.2.6 release page. In the future, if you encounter problems with the python.org website, follow the Help link at the bottom of each page to the website issue tracker. -- Ned Deily, nad at acm.org From wolfgang.maier at biologie.uni-freiburg.de Tue Oct 14 16:53:36 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Tue, 14 Oct 2014 22:53:36 +0200 Subject: stressing problem with Python < 3.3.3 / 2.7.6 and Mac OS 10.9 Mavericks In-Reply-To: References: Message-ID: <543D8D50.4070201@biologie.uni-freiburg.de> On 14.10.2014 22:30, Ned Deily wrote: > In article , > Wolfgang Maier wrote: >> I'm not a regular MacPython user, but today I had to build Mac wheels >> for different versions of Python. To test the wheel files I set up a >> fresh Mac OS 10.9 Mavericks and and installed Python 3.2, 3.3, 3.4 from >> the python.org download page on it. Then I struggled for the rest of the >> afternoon to try to figure out why Python 3.2 crashed when I used my >> package in interactive mode until I finally realized that it's not the >> package but Python that's responsible. >> >> Turns out that I had run into http://bugs.python.org/issue18458 which >> probably every MacPython user here is so familiar with that the download >> page doesn't even mention it ? ;) >> >> Seriously, I think the official download page for a OS shouldn't offer >> me a version that will not work well with the latest version of that OS >> without a warning. Why not add such a warning (like: versions below will >> crash in interactive mode on Mac OS 10.9) in the list of downloads at >> https://www.python.org/downloads/mac-osx/ between Python 2.7.6 (the >> first version with the issue fixed) and Python 3.2.5 (the last affected >> version). > > Sorry you ran into that problem. Unfortunately, that's a general > problem when using older versions of Python that are in > security-fix-only mode, e.g. those no longer in active maintenance mode. > Currently only 3.2.x and 3.3.x are in that category. > > "The only changes made to a security branch are those fixing issues > exploitable by attackers such as crashes, privilege escalation and, > optionally, other issues such as denial of service attacks. Any other > changes are not considered a security risk and thus not backported to a > security branch." > > https://docs.python.org/devguide/devcycle.html#security-branches > > Fixes for new operating system releases do not fall in this category. > There are certainly other problems that one will run into on platform > releases newer than those supported and tested at the time of the final > maintenance release. However, we did add a warning about this > particular issue to the release page of the final security release of > 2.6.x. That warning is now copied into the 3.2.6 release page. > Thanks for the fast response, Ned. I fully understand how the issue arose and why it hasn't been fixed. No complaints about that. I just thought that, if you cannot use the interactive interpreter on a standard version of the OS you're downloading for, that deserves a prominent mention. The added warning in the 3.2.6 release page may have saved me a bit of searching *after* I figured out what's going on, but I wouldn't have discovered it *before* downloading. > In the future, if you encounter problems with the python.org website, > follow the Help link at the bottom of each page to the website issue > tracker. > Thanks for pointing that out. I thought such a link must exist, but posting to this list seemed simpler than looking for it. I'll remember it for next time. Best, Wolfgang From anuragpatibandla7 at gmail.com Tue Oct 14 17:15:36 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Tue, 14 Oct 2014 14:15:36 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: On Tuesday, October 14, 2014 12:59:27 PM UTC-4, Dave Angel wrote: > anuragpatibandla7 at gmail.com Wrote in message: > > > I have a dictionary that looks like this: > > > {"1":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > > > "2":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > > > "3":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > > > "4":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}} > > > > > > Now if I have 100 objects like these and I need to split them into 3 smaller dicts in a ratio 2:3:5, how could I do that? > > > > I really have no idea what that means. You have 100 dicts of > > dicts? Are the keys unique? If so, you could combine them with a > > loop of update. > > > > > I tried using numpy.random.choice(), but it says it needs to be a 1-d array. > > > > > > > How about random.choice? It needs a sequence. > > > > To get anything more concrete, you need to specify Python version, > > and make a clearer problem statement, perhaps with example of > > what you expect. > > > > > > -- > > DaveA Hey DaveA, I am using Python 2.7. Yes. I have a dict of dicts with keys ranging from 1..100 And the value of each of these keys is another dict. What I need to do is make 3 smaller dicts and assign the values of keys 1..100 in the ratio 2:3:5. For example, if my original dict is d={"1":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, "2":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, "3":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, "4":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}} ... ... "100":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"} I need to have three dicts d1, d2, d3 with d1 containing the values of first 20 keys, d2 containing the values on next 30 keys and d3 containing the values of the next 50. Can you please help me with this? From skip.montanaro at gmail.com Tue Oct 14 17:32:38 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 14 Oct 2014 16:32:38 -0500 Subject: Parsing Python dictionary with multiple objects In-Reply-To: References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: Shuffle the keys, then grab the first 20 for one dictionary, the next 30 for the second, and the last 50 for the third. Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Oct 14 17:37:36 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 14 Oct 2014 17:37:36 -0400 Subject: strange thing that disturbs In-Reply-To: References: Message-ID: > i run win7 home premium. > during the installation of python 3.4.2 i have seen the tcl/tk > option activated! Then python -m tkinter in Command Prompt should bring up a tk windows with a bit a text and two buttons, one for exit. First try to find Python 3.4 on the Start menu and start Python 3.4 (command .... Then try import sys, then import tkinter. If this does not work, try re-installing. If you respond, do so to the list, not me. -- Terry Jan Reedy From anuragpatibandla7 at gmail.com Tue Oct 14 17:36:49 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Tue, 14 Oct 2014 14:36:49 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: <9eaa23e4-a38a-4318-a899-4c7369bf6e50@googlegroups.com> On Tuesday, October 14, 2014 5:33:01 PM UTC-4, Skip Montanaro wrote: > Shuffle the keys, then grab the first 20 for one dictionary, the next 30 for the second, and the last 50 for the third. > > Skip Could you please be more specific? From python at mrabarnett.plus.com Tue Oct 14 18:58:25 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 14 Oct 2014 23:58:25 +0100 Subject: Parsing Python dictionary with multiple objects In-Reply-To: References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: <543DAA91.1070808@mrabarnett.plus.com> On 2014-10-14 22:15, Anurag Patibandla wrote: > On Tuesday, October 14, 2014 12:59:27 PM UTC-4, Dave Angel wrote: >> anuragpatibandla7 at gmail.com Wrote in message: >> >> > I have a dictionary that looks like this: >> > {"1":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, >> > "2":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, >> > "3":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, >> > "4":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}} >> > >> > Now if I have 100 objects like these and I need to split them into 3 smaller dicts in a ratio 2:3:5, how could I do that? >> >> I really have no idea what that means. You have 100 dicts of >> dicts? Are the keys unique? If so, you could combine them with a >> loop of update. >> >> > I tried using numpy.random.choice(), but it says it needs to be a 1-d array. >> > >> >> How about random.choice? It needs a sequence. >> >> To get anything more concrete, you need to specify Python version, >> and make a clearer problem statement, perhaps with example of >> what you expect. >> > > Hey DaveA, > I am using Python 2.7. > Yes. I have a dict of dicts with keys ranging from 1..100 > And the value of each of these keys is another dict. What I need to do is make 3 smaller dicts and assign the values of keys 1..100 in the ratio 2:3:5. > For example, if my original dict is > > d={"1":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > "2":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > "3":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > "4":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}} > ... > ... > "100":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"} > > I need to have three dicts d1, d2, d3 with d1 containing the values of first 20 keys, d2 containing the values on next 30 keys and d3 containing the values of the next 50. > Can you please help me with this? > You can get a list of the entries using the dict's .items method. It's then a simple matter of slicing the list. Note that dicts aren't ordered, i.e. its keys aren't in a fixed order, so if you want then in a particular order, you'll need to sort the list. From pecore at pascolo.net Tue Oct 14 19:04:42 2014 From: pecore at pascolo.net (giacomo boffi) Date: Wed, 15 Oct 2014 01:04:42 +0200 Subject: while loop - multiple condition References: <878uklcd3r.fsf@elektro.pacujo.net> Message-ID: <87oatel0c5.fsf@pascolo.net> Tim Chase writes: > On 2014-10-12 22:16, Marko Rauhamaa wrote: >> is equivalent with >> >> while ans.lower()[0] != 'y': >> ans = input('Do you like python?') > > And still better improved with > > while ans[:1].lower() != 'y': > ans = input('Do you like python?') yok is Turkish for an EMPHATIC NO (or, at least, that's what I was led to think many years ago) From rosuav at gmail.com Tue Oct 14 19:16:58 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Oct 2014 10:16:58 +1100 Subject: while loop - multiple condition In-Reply-To: <87oatel0c5.fsf@pascolo.net> References: <878uklcd3r.fsf@elektro.pacujo.net> <87oatel0c5.fsf@pascolo.net> Message-ID: On Wed, Oct 15, 2014 at 10:04 AM, giacomo boffi wrote: > Tim Chase writes: > >> On 2014-10-12 22:16, Marko Rauhamaa wrote: >>> is equivalent with >>> >>> while ans.lower()[0] != 'y': >>> ans = input('Do you like python?') >> >> And still better improved with >> >> while ans[:1].lower() != 'y': >> ans = input('Do you like python?') > > yok is Turkish for an EMPHATIC NO > (or, at least, that's what I was led to think many years ago) Corrupted core, are you ready to start the procedure? What do you think? Interpreting vague answer as: Yes! If your program misinterprets a non-English response to an English question, that's not critical. It just means you haven't implemented full i18n. :) ChrisA From davea at davea.name Tue Oct 14 21:57:08 2014 From: davea at davea.name (Dave Angel) Date: Tue, 14 Oct 2014 21:57:08 -0400 (EDT) Subject: Parsing Python dictionary with multiple objects References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: anuragpatibandla7 at gmail.com Wrote in message: > I have a dictionary that looks like this: > {"1":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > "2":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > "3":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > "4":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}} > > Now if I have 100 objects like these and I need to split them into 3 smaller dicts in a ratio 2:3:5, how could I do that? > I tried using numpy.random.choice(), but it says it needs to be a 1-d array. > What have you actually tried? You haven't shown any actual code. Look up the method dict.keys, and see how you might use that. Then look up random.shuffle, and see what it would do. Also look up dict.sort, since your two messages on this thread imply two conflicting goals as to which sub dictionaries should go in which of your buckets. As for extracting 20% of the keys, slicing is your answer. If there are 100 keys, 20, 30, and 50 need to be sliced off. Then you'll need a loop to build each result dictionary from its keys. There are shortcuts, but it's best to learn the fundamentals first. Try writing the code. If it doesn?t all work show us what you've tried, and what you think is wrong. And when you get an exception, show the whole traceback, don't just paraphrase one of the lines. -- DaveA From ryanshuell at gmail.com Tue Oct 14 22:13:41 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Tue, 14 Oct 2014 19:13:41 -0700 (PDT) Subject: Is there an easy way to control indents in Python Message-ID: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> I'm just learning Python. It seems like indents are EXTREMELY important. I guess, since there are no brackets, everything is controlled by indents. Well, I'm reading a couple books on Python now, and in almost all of the examples they don't have proper indents, so when I copy/paste the code (from the PDF to the IDE) the indents are totally screwed up. I'm thinking that there should be some control, or setting, for this. I hope. :) I have PyCharm 3.4 and Python 3.4. From juan0christian at gmail.com Tue Oct 14 22:23:03 2014 From: juan0christian at gmail.com (Juan Christian) Date: Tue, 14 Oct 2014 23:23:03 -0300 Subject: Is there an easy way to control indents in Python In-Reply-To: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: Using PyCharm is easy: File > Settings > (IDE Settings) Editor > Smart Keys > Reformat on paste > choose "Reformat Block" On Tue, Oct 14, 2014 at 11:13 PM, ryguy7272 wrote: > I'm just learning Python. It seems like indents are EXTREMELY important. > I guess, since there are no brackets, everything is controlled by indents. > Well, I'm reading a couple books on Python now, and in almost all of the > examples they don't have proper indents, so when I copy/paste the code > (from the PDF to the IDE) the indents are totally screwed up. I'm thinking > that there should be some control, or setting, for this. I hope. :) > > I have PyCharm 3.4 and Python 3.4. > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Tue Oct 14 22:18:46 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Oct 2014 13:18:46 +1100 Subject: Is there an easy way to control indents in Python In-Reply-To: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On Wed, Oct 15, 2014 at 1:13 PM, ryguy7272 wrote: > I'm just learning Python. It seems like indents are EXTREMELY important. I guess, since there are no brackets, everything is controlled by indents. Well, I'm reading a couple books on Python now, and in almost all of the examples they don't have proper indents, so when I copy/paste the code (from the PDF to the IDE) the indents are totally screwed up. I'm thinking that there should be some control, or setting, for this. I hope. :) > That probably depends on the person who made the PDF. You may simply have to copy and paste one line at a time; if you're using an editor that understands Python syntax, it'll do some of your indenting for you, and you'll just have to manually mark the unindents. Alternatively, just paste it all in without indentation, then go through and select blocks of code and hit Tab; in many editors, that'll indent the selected code by one level. But ultimately, the fault is almost certainly with the PDF. ChrisA From rustompmody at gmail.com Tue Oct 14 22:32:27 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 14 Oct 2014 19:32:27 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: <97e450f8-26ec-4756-a52c-d5e1423b0769@googlegroups.com> On Wednesday, October 15, 2014 7:35:18 AM UTC+5:30, Dave Angel wrote: > anurag Wrote in message: > > I have a dictionary that looks like this: > > {"1":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > > "2":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > > "3":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}, > > "4":{"Key1":"Value1", "Key2":"Value2", "Key3":"Value3"}} > > Now if I have 100 objects like these and I need to split them into 3 smaller dicts in a ratio 2:3:5, how could I do that? > > I tried using numpy.random.choice(), but it says it needs to be a 1-d array. > What have you actually tried? You haven't shown any actual code. > Look up the method dict.keys, and see how you might use that. Then > look up random.shuffle, and see what it would do. Also look up > dict.sort, since your two messages on this thread imply two > conflicting goals as to which sub dictionaries should go in which > of your buckets. > As for extracting 20% of the keys, slicing is your answer. If > there are 100 keys, 20, 30, and 50 need to be sliced > off. > Then you'll need a loop to build each result dictionary from its keys. > There are shortcuts, but it's best to learn the fundamentals first. > Try writing the code. If it doesn't all work show us what you've > tried, and what you think is wrong. And when you get an > exception, show the whole traceback, don't just paraphrase one > of the lines. Yes that is what is in general expected out here -- code -- maybe working, maybe not, maybe incomplete, maybe 'pseudo' etc Then others here will improve it However there is one conceptual thing that perhaps should be mentioned: order. Is your data *essentially* ordered? And by 'essentially' I mean you think of it independent of python. Yeah in python dicts are unordered and lists are ordered and one can fudge one to behave a bit like the other. But before you fudge, please ponder which you really need/want. Below a bit of going from one to other # dict -> list >>> d = {"a":1,"b":2,"c":3} >>> d {'a': 1, 'c': 3, 'b': 2} >>> list(d) ['a', 'c', 'b'] # alternate >>> d.keys() ['a', 'c', 'b'] >>> d.items() [('a', 1), ('c', 3), ('b', 2)] >>> d.values() [1, 3, 2] # list -> dict >>> dict(d.items()) {'a': 1, 'c': 3, 'b': 2} # round-tripping >>> dict(d.items()) == d True From drsalists at gmail.com Tue Oct 14 22:38:15 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 14 Oct 2014 19:38:15 -0700 Subject: Is there an easy way to control indents in Python In-Reply-To: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On Tue, Oct 14, 2014 at 7:13 PM, ryguy7272 wrote: > I'm just learning Python. It seems like indents are EXTREMELY important. I guess, since there are no brackets, everything is controlled by indents. Well, I'm reading a couple books on Python now, and in almost all of the examples they don't have proper indents, so when I copy/paste the code (from the PDF to the IDE) the indents are totally screwed up. I'm thinking that there should be some control, or setting, for this. I hope. :) Perhaps if you share a screenshot of your PDF and the name of your PDF viewer, we can help you more. Here's a URL about Python and Whitespace: http://stromberg.dnsalias.org/~strombrg/significant-whitespace.html From zachary.ware+pylist at gmail.com Tue Oct 14 22:35:12 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Tue, 14 Oct 2014 21:35:12 -0500 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On Tue, Oct 14, 2014 at 9:18 PM, Chris Angelico wrote: > On Wed, Oct 15, 2014 at 1:13 PM, ryguy7272 wrote: >> I'm just learning Python. It seems like indents are EXTREMELY important. I guess, since there are no brackets, everything is controlled by indents. Well, I'm reading a couple books on Python now, and in almost all of the examples they don't have proper indents, so when I copy/paste the code (from the PDF to the IDE) the indents are totally screwed up. I'm thinking that there should be some control, or setting, for this. I hope. :) >> > > That probably depends on the person who made the PDF. You may simply > have to copy and paste one line at a time; if you're using an editor > that understands Python syntax, it'll do some of your indenting for > you, and you'll just have to manually mark the unindents. > Alternatively, just paste it all in without indentation, then go > through and select blocks of code and hit Tab; in many editors, > that'll indent the selected code by one level. But ultimately, the > fault is almost certainly with the PDF. Agreed, although I'd say the PDF viewer could also be at fault. Earlier today I tried to copy just a paragraph of mostly plain text from the Firefox built-in PDF viewer, but when pasting it elsewhere, it was pasted one character per line. Opening it in the Windows 8.1 default PDF viewer (of all things...), copying and pasting worked like a charm. -- Zach From rosuav at gmail.com Tue Oct 14 22:47:19 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Oct 2014 13:47:19 +1100 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On Wed, Oct 15, 2014 at 1:35 PM, Zachary Ware wrote: >> But ultimately, the >> fault is almost certainly with the PDF. > > Agreed, although I'd say the PDF viewer could also be at fault. Good point, there are some really terrible PDF viewers around. Either way, the workaround of grabbing one line at a time will be effective - albeit tedious for anything more than a dozen lines or so. ChrisA From anuragpatibandla7 at gmail.com Tue Oct 14 23:40:40 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Tue, 14 Oct 2014 20:40:40 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: <7582dd3f-c0e1-4d5e-a03e-20bf711d1e79@googlegroups.com> Thanks for the response. Here is the code that I have tried. from operator import itemgetter keys = json.keys() order = list(keys) q1 = int(round(len(keys)*0.2)) q2 = int(round(len(keys)*0.3)) q3 = int(round(len(keys)*0.5)) b = [q1,q2,q3] n=0 for i in b: queues = order[n:n+i] n = n+i print queues for j in range(len(queues)): q = (queues[j], json.get(queues[j])) print q By this I am able to get the 3 smaller dicts I want, but can you help me assign them to 3 variables? The dicts need not be ordered but it would be better if they are ordered. Thanks From anuragpatibandla7 at gmail.com Tue Oct 14 23:41:59 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Tue, 14 Oct 2014 20:41:59 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: <050847f8-713e-46cd-b18e-7c3fea6458f7@googlegroups.com> 'json' has my original larger dict From rustompmody at gmail.com Wed Oct 15 00:50:28 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 14 Oct 2014 21:50:28 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <7582dd3f-c0e1-4d5e-a03e-20bf711d1e79@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> <7582dd3f-c0e1-4d5e-a03e-20bf711d1e79@googlegroups.com> Message-ID: <32d89ca5-5e3f-47f4-945b-39d0ae5b40f8@googlegroups.com> On Wednesday, October 15, 2014 9:10:54 AM UTC+5:30, Anurag Patibandla wrote: > Thanks for the response. > Here is the code that I have tried. > from operator import itemgetter > keys = json.keys() > order = list(keys) > q1 = int(round(len(keys)*0.2)) > q2 = int(round(len(keys)*0.3)) > q3 = int(round(len(keys)*0.5)) > b = [q1,q2,q3] > n=0 > for i in b: > queues = order[n:n+i] > n = n+i > print queues > for j in range(len(queues)): > q = (queues[j], json.get(queues[j])) > print q Converting the end for loop (last 3 lines) into: print [(queues[j], json.get(queues[j])) for j in range(len(queues))] Does that help? General advice: 1. Instead of writing 'naked' code as you have done, if you wrap it into functions (preferably small) 2. Contents similar to the original naked code but with print's replaced by return's you make your as well as those trying to help/collaborate with you life easier Also the above is a more or mechanical translation. However something[j] ... for j in range(len(something)) is usually a sign of a C programmer writing python :-) Usually better to write x for x in something So... Better to write that comprehension as print [(q, json.get(q)) for q in queues] From venugopal.reddy at tspl.com Wed Oct 15 01:42:07 2014 From: venugopal.reddy at tspl.com (Venugopal Reddy) Date: Tue, 14 Oct 2014 22:42:07 -0700 (PDT) Subject: Jython or Pyton issue-- Kindly Help me.... In-Reply-To: References: <91eb3378-958d-45e0-8741-a800ae681260@googlegroups.com> <552277f6-fb5b-44de-a0d4-7c7fe480d265@googlegroups.com> Message-ID: <0c8200cc-5ae7-4fd9-9dd6-903802fc5bb7@googlegroups.com> Actuvally am having below XML File: 13001 2014 12 178 W78 41859 0 B 181 LIGHT TRUCK WHEELBASES P AA5 15615 AA5K8 178 /4521MM WHEELBASE false false 181 LIGHT TRUCK WHEELBASES P AA5 15615 AA5K8_second time 178 /4521MM WHEELBASE false false 13001 2014 12 190 W90 41860 0 B 181 LIGHT TRUCK WHEELBASES P AA5 15616 AA5MA 190 /4826MM WHEELBASE false false ============================ My expected Output is: WersCode AA5K8 AA5MA ============== For this I have used below Code: mport glob import xml.etree.ElementTree as ET Fatfile = open('#Var_SOE_VLIS_Response_Output\\Sales_to_Wers_Code2.txt', 'a') try: tree = ET.parse('#Var_ENG_Response_Files\\SoapResponse1.xml') Fatfile.write('1111') WersCodeList = tree.findall('./{urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0}PortInstalledOptionFeature') Fatfile.write('\n2222') # x = len(WersCodeList) # Fatfile.write(x) Fatfile.write('\n333') for WersCode in WersCodeList : Fatfile.write('\n444') WersCode = WersCode.find('.//{urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0}WersCode') Fatfile.write('\n') Fatfile.write(WersCode.text) except : Fatfile.write(' \nsorry') Fatfile.write(' \nSuccess') ==== But I could not able to get the WersCode List using Findall. Please please please help on this .. am struggling sice one week sir... On Tuesday, October 14, 2014 4:14:19 PM UTC+5:30, Peter Otten wrote: > Venugopal Reddy wrote: > > > > > Ok, I will explain my problem in details : > > > > > > I have below XML: > > > > > > > > > > > > > > > 1 > > > 2008 > > > 2009> > > > 141100 > > > > > > > > > > > > > > > 4 > > > 2011 > > > 59900 > > > > > > > > > > > > 68 > > > 2011 > > > 13600 > > > > > > > > > > > > > > > > > > > > > From I want output below format: > > > > > > Countryname Rank Year gdppc > > > Liechtenstein 1 2008 141100 > > > Singapore 4 2011 59900 > > > Panama 68 2011 13600 > > > > > > Please help how to do it.. > > > > Read up on elementtree: > > > > http://pymotw.com/2/xml/etree/ElementTree/parse.html > > > > You can load the data from the file with parse(), get the countries with > > findall(), the name with country_node.attrib["name"], and rank, year and > > gdppc with country_node.find("rank").text etc. > > > > If you run into problems come back with some code of yours. From jeffevalencia at gmail.com Wed Oct 15 01:57:31 2014 From: jeffevalencia at gmail.com (Jeffe) Date: Tue, 14 Oct 2014 22:57:31 -0700 (PDT) Subject: Python Help Message-ID: <2c8f67b6-151f-4ef0-8ea1-01e1ce60a999@googlegroups.com> Hi, I am looking for anyone who knows python (C++ is also ok) well enough to write a basic script login registration and tws ib api connected. Looking to build a asset/security trading platform and have investors interested but want to see it operational first. Looking for a something basic yet operational, fee based or we can discuss equity if succesfully funded. Have some Big people interested with a solid business framework. Just need the software to show and its on.. Similar to this...https://www.youtube.com/watch?v=Bu0kpU-ozaw We have Solid trading strategies but investors want to see the software operational first before integrating our strategies (and their funds) so we may collect trading fees while we run our patterns simultaneously Looking forward to hearing back from you, Jeff jeffevalencia at gmail.com From rosuav at gmail.com Wed Oct 15 02:11:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 15 Oct 2014 17:11:45 +1100 Subject: Python Help In-Reply-To: <2c8f67b6-151f-4ef0-8ea1-01e1ce60a999@googlegroups.com> References: <2c8f67b6-151f-4ef0-8ea1-01e1ce60a999@googlegroups.com> Message-ID: On Wed, Oct 15, 2014 at 4:57 PM, Jeffe wrote: > Looking for a something basic yet operational, fee based or we can discuss equity if succesfully funded. Have some Big people interested with a solid business framework. Just need the software to show and its on.. > Unfortunately, the Python Job Board isn't currently active, so I can't point you there. But you may find that Stack Overflow Careers will help: http://careers.stackoverflow.com/ Good luck! There's people out there who can do what you're wanting. It's just a matter of finding them! ChrisA From varun7rs at gmail.com Wed Oct 15 03:20:27 2014 From: varun7rs at gmail.com (varun7rs at gmail.com) Date: Wed, 15 Oct 2014 00:20:27 -0700 (PDT) Subject: reading output from a .sol file Message-ID: Hello everyone, I have a .sol file at my hand and I wish to make it an xml file so that its a bit more convenient to read and skim off data from an xml file. But to do that, I need to write a function to read the values in the .sol file. What I intend is when I read the line z_ something, i need to have a request tree and based on the number that follows the underscore, i will update the id of the request...but for the f_0_0(0,1)_(1,5) category, its a bit tricky. excluding the first few, when I read the contents in the brackets, the first set (0,1) means the virtual link and i update the xml with this and the second set (1,5) indicates the physical link on which the virtual link is placed. This is where I need your help. I tried writing one but I found it too hard. Hopefully you guys help me out or point me to the relevant sources for more information. Sorry for the trouble and thanks a lot z_0 1.000000 x_0_0_1 1.000000 x_0_1_5 1.000000 x_0_2_20 1.000000 x_0_3_21 1.000000 x_0_4_8 1.000000 f_0_0(0,1)_(1,5) 33.800000 f_0_1(1,2)_(5,9) 51.100000 f_0_1(1,2)_(9,20) 51.100000 f_0_2(2,3)_(2,21) 33.300000 f_0_2(3,2)_(2,22) 33.300000 f_0_2(3,2)_(18,19) 2.900000 f_0_2(2,3)_(18,25) 2.900000 f_0_2(3,2)_(19,20) 2.900000 f_0_2(2,3)_(20,22) 33.300000 f_0_2(3,2)_(21,25) 2.900000 f_0_3(3,4)_(5,8) 48.000000 f_0_3(4,3)_(5,25) 48.000000 f_0_3(3,4)_(21,25) 48.000000 From wuwei23 at gmail.com Wed Oct 15 03:27:37 2014 From: wuwei23 at gmail.com (alex23) Date: Wed, 15 Oct 2014 17:27:37 +1000 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On 15/10/2014 12:23 PM, Juan Christian wrote: > Using PyCharm is easy: > > File > Settings > (IDE Settings) Editor > Smart Keys > Reformat on paste > > choose "Reformat Block" This isn't as straight forward as you imply. Say I have misindented code like this: if True: print 'true' else: print 'false' print 'done' If I select this block in PyCharm and reformat it, I get: if True: print 'true' else: print 'false' print 'done' Which is still invalid. Even if it did work more fully, though, how would it determine the correct placement of the last line of code? From __peter__ at web.de Wed Oct 15 03:32:37 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 15 Oct 2014 09:32:37 +0200 Subject: Jython or Pyton issue-- Kindly Help me.... References: <91eb3378-958d-45e0-8741-a800ae681260@googlegroups.com> <552277f6-fb5b-44de-a0d4-7c7fe480d265@googlegroups.com> <0c8200cc-5ae7-4fd9-9dd6-903802fc5bb7@googlegroups.com> Message-ID: Venugopal Reddy wrote: > Actuvally am having below XML File: > > > xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> > xmlns:a="urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0" > xmlns:b="urn:ford/VehicleOrder/SingleOrderEdit/v1.0" > xmlns:c="urn:ford/interface/VehicleOrder/LegacyFeatureMapping/v2"> > 13001 > 2014 12 > 178 > W78 > 41859 > 0 > B > > > 181 > LIGHT TRUCK WHEELBASES > P > AA5 > > 15615 > AA5K8 > 178 /4521MM WHEELBASE > false > false > > > > 181 > LIGHT TRUCK WHEELBASES > P > AA5 > > 15615 > AA5K8_second time > 178 /4521MM WHEELBASE > false > false > > > > 13001 > 2014 > 12 > 190 > W90 > 41860 > 0 > B > > > 181 > LIGHT TRUCK WHEELBASES > P > AA5 > > 15616 > AA5MA > 190 /4826MM WHEELBASE > false > false > > > > > > ============================ > > My expected Output is: > > > WersCode > AA5K8 > AA5MA > > ============== For this I have used below Code: > > mport glob > import xml.etree.ElementTree as ET > > Fatfile = open('#Var_SOE_VLIS_Response_Output\\Sales_to_Wers_Code2.txt', > 'a') try: > tree = ET.parse('#Var_ENG_Response_Files\\SoapResponse1.xml') > Fatfile.write('1111') > WersCodeList = > tree.findall('./{urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0}PortInstalledOptionFeature') > Fatfile.write('\n2222') > # x = len(WersCodeList) > # Fatfile.write(x) > Fatfile.write('\n333') > for WersCode in WersCodeList : > Fatfile.write('\n444') > WersCode = > WersCode.find('.//{urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0}WersCode') > Fatfile.write('\n') Fatfile.write(WersCode.text) > except : > Fatfile.write(' \nsorry') > Fatfile.write(' \nSuccess') > > ==== > > But I could not able to get the WersCode List using Findall. - The namespace is not correct - "./" finds only direct children Try something like for feature in tree.findall( ".//{urn:ford/interface/VehicleOrder/LegacyFeatureMapping/v2}PortInstalledOptionFeature"): code = feature.find( ".//{urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0}WersCode") print(code.text) > Please please please help on this .. am struggling sice one week sir... ... and it's all your fault because you offered a task to do for you instead of some code we could help you fix. From orgnut at yahoo.com Wed Oct 15 03:56:49 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Wed, 15 Oct 2014 00:56:49 -0700 Subject: Code Review for Paper, Rock, Scissors In-Reply-To: References: Message-ID: On 10/14/2014 01:04 AM, Revenant wrote: > Hi all! > > I'm new to Python and programming in general, and am trying to learn as much as I can about it. > > Anyway, for a basic first program I made a simple game of Paper, Rock, Scissors. For this program, I incorporated a main menu that presented three different options, allowed the user to play a game of Paper, Rock, Scissors, allowed them to play the game again, and most importantly checked the user's input to make sure the program doesn't fail due to errors. > > One thing I want to try to add is a "Press any key to continue" function that occurs at the end of the program when the user decides to quit. I looked at some options online, but haven't quite figured it out yet. > > As previously stated, I am new to Python and would also like to see if any of you programming gurus have some suggestions about how I can simplify code, and also if there are any other good starter programs to work on to improve my skills. > > Thanks for reading! Code is below: > [snip] You've already received a lot of good advice, which I'm not going to repeat here. Rather, I'm going to show you the version that I wrote some time ago. Whether this version is good/bad/indifferent is up to someone else to say, but I'm showing it here just as an example of a different approach that you might find interesting to study. Although, being new to Python, some of the things here will probably be unfamiliar to you, particularly the new-style string formatting which I use a lot. The key to this approach is to recognize that there are only nine possible combinations. I handle these in the get_result() function by stitching together pieces of strings in a dictionary. This function is interesting because, although it has a total of 34 lines, 17 are comments or blanks, 16 are data definitions, and only 1 line is actual code. The get_rps() function is used to get the player's rock/paper/scissor choice. It also allows 'quit' as a fourth choice. This makes your proposed "Press any key..." unnecessary, because this version will continue automatically until you specifically tell it to stop. Also it accepts an empty input as the same as a 'quit' choice. Whether this is good or bad is debatable, but it can easily be written either way. It returns the choice as a single lower-case character, 'r', 'p', 's' or 'q'. This version also makes heavy use of the constants WIN/LOSE/DRAW, which are defined as globals at the top of the program. They help the clarity of the source. Normal convention is to make the names of constants all upper-case. This is a convention only, not a requirement. The scores are tracked in a three-element list, which use the WIN/LOSE/DRAW constants as the indexes. The instruction display in my version is very short, but it could easily be replaced with a longer version like yours. FWIW, here is my code... Note the first line is Linux-specific -- Windows will ignore it, or you can remove it. #------------ Code starts here ------------ #!/usr/bin/env python3 # rps.py -- Rock, Paper, Scissors game from random import choice # Global constants WIN = 0 LOSE = 1 DRAW = 2 def get_result(h, c): """Determine who wins this round Parameters: h: Human's selection (r, p or s) c: Computer's selection (r, p or s) Returns a tuple of the WIN/LOSE/DRAW value and the string describing the results """ # Strings used in results pr = 'Paper covers Rock. {}' rs = 'Rock smashes Scissors. {}' sp = 'Scissors cuts Paper. {}' ti = 'We both have {}. {}' # Win/lose/draw strings wins = ('You win', 'I win', "It's a draw") # Dictionary defining the results res = { 'rr' : (DRAW, ti.format('rocks', wins[DRAW])), 'rp' : (LOSE, pr.format(wins[LOSE])), 'rs' : (WIN, rs.format(wins[WIN])), 'pr' : (WIN, pr.format(wins[WIN])), 'pp' : (DRAW, ti.format('paper', wins[DRAW])), 'ps' : (LOSE, sp.format(wins[LOSE])), 'sr' : (LOSE, rs.format(wins[LOSE])), 'sp' : (WIN, sp.format(wins[WIN])), 'ss' : (DRAW, ti.format('scissors', wins[DRAW])) } # Return the result tuple return res[h + c] def get_rps(): """Get Rock/Paper/Scissor choice.""" while True: select = input('\nDo you choose Rock, Paper or Scissors ').lower() # Check for empty input or quit command if not select or select in ['q', 'quit']: return 'q' # return quit code # Check for valid input if select in ['r', 'rock', 'p', 'paper', 's', 'scissors']: return select[0] # return first character print('What did you say?? Try again please') #================= Main Program starts here ============== # Keep track of results: # scores[0] = number of human wins # scores[1] = number of computer wins # scores[2] = number of draws scores = [0] * 3 things = {'r':'a rock', 'p':'paper', 's':'scissors'} print("Let's play a game or Rock, Paper, Scissors.\n") print('Enter "r", "p", "s", "rock", "paper", or "scissors" for your choice.') print('Use empty input, "q" or "quit" to end the game.') while True: computer = choice('rps') # Computer selects human = get_rps() # Human selects if human == 'q': break print('You have {}, I have {}. '.format( things[human], things[computer]), end='') scr, res = get_result(human, computer) scores[scr] += 1 # Count win/loss/draw print(res) # And show results # Show final scores print('\nTotal scores:') print('\tYou won {} games'.format(scores[WIN])) print('\tComputer won {} games'.format(scores[LOSE])) print('\tThere were {} tie games'.format(scores[DRAW])) print('\nThanks for playing with me. Bye now.') #------------ End of code -------------- -=- Larry -=- From nickolas.ellson at gmail.com Tue Oct 14 16:21:14 2014 From: nickolas.ellson at gmail.com (Nick Ellson) Date: Tue, 14 Oct 2014 13:21:14 -0700 Subject: Help with parsing a dict from Vendor's API? Message-ID: Hello! I have a very specific question related to the output of a Vendors API (Palo Alto Networks "pan.xapi" and how I might farm data from this output. I am new to python, doing well in the tutorials, but this is an automation task at work and I know the rest will be much easier once i get past the ability to read this dict. The code reaches in to the central Palo Alto firewall manager (Panorama) and executes a simple command to return all of the information for each of the managed firewalls in the field. It captured this output in XML I believe, but has the ability to return it in python dict format too, which looked like probably the best format to use. Here is the test I tried xapi.op(cmd='show devices connected', cmd_xml=True ) MyDict=xapi.xml_python() print (type(MyDict)) print (MyDict) and I get: (This displays only 2 firewalls of the 180, so you can see the structure, and that python does say it is a "dict") bertha bin # ./test.py {'response': {'result': {'devices': {'entry': [{'av-version': '1391-1863', 'unsupported-version': False, 'ip-address': '1.8.2.8', 'sw-version': '4.1.9', 'vsys': {'entry': [{'name': 'vsys1', 'shared-policy-md5sum': '8a8dcd146e24bd750ae571059bc09210', 'shared-policy-status': None, 'display-name': 'vsys1'}]}, 'uptime': '350 days, 14:29:49', 'threat-version': '460-2394', 'operational-mode': 'normal', 'multi-vsys': False, 'global-protect-client-package-version': '0.0.0', 'app-version': '460-2394', 'model': 'PA-200', 'connected': True, 'name': '001606000002', 'family': '200', 'url-filtering-version': '4390', 'vpn-disable-mode': False, 'logdb-version': '4.1.2', 'serial': '001606000002', 'hostname': 'bob-int-fw'}, {'av-version': '1391-1863', 'unsupported-version': False, 'ip-address': '1.9.8.8', 'sw-version': '4.1.9', 'vsys': {'entry': [{'name': 'vsys1', 'shared-policy-md5sum': '8a8dcd146e24bd750ae571059bc09210', 'shared-policy-status': None, 'display-name': 'vsys1'}]}, 'uptime': '358 days, 0:03:20', 'threat-version': '460-2394', 'operational-mode': 'normal', 'multi-vsys': False, 'global-protect-client-package-version': '0.0.0', 'app-version': '460-2394', 'model': 'PA-200', 'connected': True, 'name': '001606000009', 'family': '200', 'url-filtering-version': '4390', 'vpn-disable-mode': False, 'logdb-version': '4.1.2', 'serial': '001606008639', 'hostname': 'bib-int-fw'}, <****repeats for 180 firewalls****> ]}}, 'status': 'success'}} What I want is to parse through each firewall grabbing the "ip-address" value so that I can dump it to a list: For use in another network management tool so I don't rely on outsourced help to remember to place teh firewalls into the correct tools. But dang if every dict tutorial seems to deal with slightly simpler looking structures than what this puts out. I would be very appreciative with help stepping out of the 6 line "address book/grocery list" example world for a taste of something useful :-) Maybe to a Python coder, it maybe a simple even be able to randomly reference a firewall index number and teh value in this structure so one can easily just pluck any A/V pair at will.. just not for me yet :-D Nick -------------- next part -------------- An HTML attachment was scrubbed... URL: From venugopal.reddy at tspl.com Wed Oct 15 04:35:45 2014 From: venugopal.reddy at tspl.com (Venugopal Reddy) Date: Wed, 15 Oct 2014 01:35:45 -0700 (PDT) Subject: Jython or Pyton issue-- Kindly Help me.... In-Reply-To: References: <91eb3378-958d-45e0-8741-a800ae681260@googlegroups.com> <552277f6-fb5b-44de-a0d4-7c7fe480d265@googlegroups.com> <0c8200cc-5ae7-4fd9-9dd6-903802fc5bb7@googlegroups.com> Message-ID: <9266b258-3ee0-4f98-88ee-9849ac9abb2b@googlegroups.com> Thanks for Help Sir, Am using " for feature in tree.findall( ".//{urn:ford/interface/VehicleOrder/LegacyFeatureMapping/v2}PortInstalledOptionFeature"): ) " Please sir help me Here also this findall Method is not return any list values. On Wednesday, October 15, 2014 1:03:00 PM UTC+5:30, Peter Otten wrote: > Venugopal Reddy wrote: > > > > > Actuvally am having below XML File: > > > > > > > > > > > xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> > > > > > xmlns:a="urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0" > > > xmlns:b="urn:ford/VehicleOrder/SingleOrderEdit/v1.0" > > > xmlns:c="urn:ford/interface/VehicleOrder/LegacyFeatureMapping/v2"> > > > 13001 > > > 2014 12 > > > 178 > > > W78 > > > 41859 > > > 0 > > > B > > > > > > > > > 181 > > > LIGHT TRUCK WHEELBASES > > > P > > > AA5 > > > > > > 15615 > > > AA5K8 > > > 178 /4521MM WHEELBASE > > > false > > > false > > > > > > > > > > > > 181 > > > LIGHT TRUCK WHEELBASES > > > P > > > AA5 > > > > > > 15615 > > > AA5K8_second time > > > 178 /4521MM WHEELBASE > > > false > > > false > > > > > > > > > > > > 13001 > > > 2014 > > > 12 > > > 190 > > > W90 > > > 41860 > > > 0 > > > B > > > > > > > > > 181 > > > LIGHT TRUCK WHEELBASES > > > P > > > AA5 > > > > > > 15616 > > > AA5MA > > > 190 /4826MM WHEELBASE > > > false > > > false > > > > > > > > > > > > > > > > > > ============================ > > > > > > My expected Output is: > > > > > > > > > WersCode > > > AA5K8 > > > AA5MA > > > > > > ============== For this I have used below Code: > > > > > > mport glob > > > import xml.etree.ElementTree as ET > > > > > > Fatfile = open('#Var_SOE_VLIS_Response_Output\\Sales_to_Wers_Code2.txt', > > > 'a') try: > > > tree = ET.parse('#Var_ENG_Response_Files\\SoapResponse1.xml') > > > Fatfile.write('1111') > > > WersCodeList = > > > > > tree.findall('./{urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0}PortInstalledOptionFeature') > > > Fatfile.write('\n2222') > > > # x = len(WersCodeList) > > > # Fatfile.write(x) > > > Fatfile.write('\n333') > > > for WersCode in WersCodeList : > > > Fatfile.write('\n444') > > > WersCode = > > > > > WersCode.find('.//{urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0}WersCode') > > > Fatfile.write('\n') Fatfile.write(WersCode.text) > > > except : > > > Fatfile.write(' \nsorry') > > > Fatfile.write(' \nSuccess') > > > > > > ==== > > > > > > But I could not able to get the WersCode List using Findall. > > > > - The namespace is not correct > > - "./" finds only direct children > > > > Try something like > > > > for feature in tree.findall( > > ".//{urn:ford/interface/VehicleOrder/LegacyFeatureMapping/v2}PortInstalledOptionFeature"): > > code = feature.find( > > ".//{urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0}WersCode") > > print(code.text) > > > > > > > Please please please help on this .. am struggling sice one week sir... > > > > ... and it's all your fault because you offered a task to do for you instead > > of some code we could help you fix. From __peter__ at web.de Wed Oct 15 05:04:12 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 15 Oct 2014 11:04:12 +0200 Subject: Jython or Pyton issue-- Kindly Help me.... References: <91eb3378-958d-45e0-8741-a800ae681260@googlegroups.com> <552277f6-fb5b-44de-a0d4-7c7fe480d265@googlegroups.com> <0c8200cc-5ae7-4fd9-9dd6-903802fc5bb7@googlegroups.com> <9266b258-3ee0-4f98-88ee-9849ac9abb2b@googlegroups.com> Message-ID: Venugopal Reddy wrote: > Thanks for Help Sir, > > Am using " for feature in tree.findall( > ".//{urn:ford/interface/VehicleOrder/LegacyFeatureMapping/v2}PortInstalledOptionFeature"): > ) " > > Please sir help me > > Here also this findall Method is not return any list values. OK, I tried it: $ cat xml_werscode.py from xml.etree import ElementTree as ET data = """ 13001 2014 12 178 W78 41859 0 B 181 LIGHT TRUCK WHEELBASES P AA5 15615 AA5K8 178 /4521MM WHEELBASE false false 181 LIGHT TRUCK WHEELBASES P AA5 15615 AA5K8_second time 178 /4521MM WHEELBASE false false 13001 2014 12 190 W90 41860 0 B 181 LIGHT TRUCK WHEELBASES P AA5 15616 AA5MA 190 /4826MM WHEELBASE false false """ tree = ET.fromstring(data) for feature in tree.findall( ".//{urn:ford/interface/VehicleOrder/LegacyFeatureMapping/v2}PortInstalledOptionFeature"): code = feature.find(".//{urn:ford/VehicleOrder/LegacyFeatureMapping/v2.0}WersCode") print(code.text) $ python xml_werscode.py AA5K8 AA5MA As you can see I do get the expected output. I am sorry I have no idea what you might be doing wrong. From __peter__ at web.de Wed Oct 15 05:22:26 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 15 Oct 2014 11:22:26 +0200 Subject: Help with parsing a dict from Vendor's API? References: Message-ID: Nick Ellson wrote: > Hello! > > I have a very specific question related to the output of a Vendors API > (Palo Alto Networks "pan.xapi" and how I might farm data from this output. > I am new to python, doing well in the tutorials, but this is an automation > task at work and I know the rest will be much easier once i get past the > ability to read this dict. > > The code reaches in to the central Palo Alto firewall manager (Panorama) > and executes a simple command to return all of the information for each of > the managed firewalls in the field. It captured this output in XML I > believe, but has the ability to return it in python dict format too, which > looked like probably the best format to use. Here is the test I tried > > > xapi.op(cmd='show devices connected', cmd_xml=True ) > MyDict=xapi.xml_python() > print (type(MyDict)) > print (MyDict) > > > and I get: (This displays only 2 firewalls of the 180, so you can see the > structure, and that python does say it is a "dict") > > bertha bin # ./test.py > > {'response': {'result': {'devices': {'entry': [{'av-version': '1391-1863', > 'unsupported-version': False, 'ip-address': '1.8.2.8', 'sw-version': > '4.1.9', 'vsys': {'entry': [{'name': 'vsys1', 'shared-policy-md5sum': > '8a8dcd146e24bd750ae571059bc09210', 'shared-policy-status': None, > 'display-name': 'vsys1'}]}, 'uptime': '350 days, 14:29:49', > 'threat-version': '460-2394', 'operational-mode': 'normal', 'multi-vsys': > False, 'global-protect-client-package-version': '0.0.0', 'app-version': > '460-2394', 'model': 'PA-200', 'connected': True, 'name': '001606000002', > 'family': '200', 'url-filtering-version': '4390', 'vpn-disable-mode': > False, 'logdb-version': '4.1.2', 'serial': '001606000002', 'hostname': > 'bob-int-fw'}, {'av-version': '1391-1863', 'unsupported-version': False, > 'ip-address': '1.9.8.8', 'sw-version': '4.1.9', 'vsys': {'entry': > [{'name': 'vsys1', 'shared-policy-md5sum': > '8a8dcd146e24bd750ae571059bc09210', 'shared-policy-status': None, > 'display-name': 'vsys1'}]}, 'uptime': '358 days, 0:03:20', > 'threat-version': '460-2394', 'operational-mode': 'normal', 'multi-vsys': > False, 'global-protect-client-package-version': '0.0.0', 'app-version': > '460-2394', 'model': 'PA-200', 'connected': True, 'name': '001606000009', > 'family': '200', 'url-filtering-version': '4390', 'vpn-disable-mode': > False, 'logdb-version': '4.1.2', 'serial': '001606008639', 'hostname': > 'bib-int-fw'}, <****repeats for 180 firewalls****> ]}}, 'status': > 'success'}} > > > What I want is to parse through each firewall grabbing the "ip-address" > value so that I can dump it to a list: > > > > > > For use in another network management tool so I don't rely on outsourced > help to remember to place teh firewalls into the correct tools. > > But dang if every dict tutorial seems to deal with slightly simpler > looking structures than what this puts out. I would be very appreciative > with help stepping out of the 6 line "address book/grocery list" example > world for a taste of something useful :-) > > Maybe to a Python coder, it maybe a simple even be able to randomly > reference a firewall index number and teh value in this structure so one > can easily just pluck any A/V pair at will.. just not for me yet :-D Look at your dict (I use the name 'd' instead of 'MyDict'): d = {"response": {"result": ...} So d["response"] will give you {"result": {"devices": ...} A good tool to explore a data structure like this is the interactive interpreter. If you invoke the script with python -i test.py you have all its global variables available, i. e. >>> MyDict { ... } # you should see the dictionary contents On we go: d["response"]["result"] will give {"devices": {"entry": ...} Next step: d["response"]["result"]["devices"] --> {"entry": [...] That's a list for change, so you loop over it: entries = d["response"]["result"]["devices"]["entry"] for entry in entries: print(entry) # --> {..., 'ip-address': '1.8.2.8', ... } So the final code is: for entry in d["response"]["result"]["devices"]["entry"]: print(entry["ip-address"]) From xdegaye at gmail.com Wed Oct 15 07:23:50 2014 From: xdegaye at gmail.com (Xavier de Gaye) Date: Wed, 15 Oct 2014 13:23:50 +0200 Subject: [ANN] pdb-clone 1.9 - a fast clone of pdb with the remote debugging and attach features Message-ID: <543E5946.1010802@gmail.com> pdb-clone 1.9 has been released at Pypi: https://pypi.python.org/pypi/pdb-clone Features: * Improve significantly pdb performance. With breakpoints, pdb-clone runs just above the speed of the interpreter while pdb runs at 10 to 100 times the speed of the interpreter. * Extend pdb with remote debugging. A remote debugging session may be started when the program stops at a `pdb.set_trace_remote()` hard-coded breakpoint, or at any time and multiple times by attaching to the process main thread. This feature is implemented in the py3 and py2.7 versions of pdb-clone. * Fix pdb long standing bugs entered in the python issue tracker. * Add a bdb comprehensive test suite (more than 70 tests) and run both the Python pdb and pdb-clone bdb test suites. * Three versions of pdb-clone are supported: * The py3 version of pdb-clone runs on python3 from python 3.2 onward. * The py2.7 vesion runs on python 2.7. * The py2.4 version runs on all python versions from 2.4 to 2.7 included. The pdb command line interface remains unchanged except for the new `detach` and `thread` pdb commands. All the versions of pdb-clone implement the most recent python3 features of pdb, as defined in Python documentation. From nickolas.ellson at gmail.com Wed Oct 15 09:35:57 2014 From: nickolas.ellson at gmail.com (Nick Ellson) Date: Wed, 15 Oct 2014 06:35:57 -0700 Subject: Help with parsing a dict from Vendor's API? In-Reply-To: References: Message-ID: <5CCD60B7-99B4-4D4E-9DA6-9E8B6D0087A6@gmail.com> Thank you Peter! That makes sense, and I did find "pprint" that dumped it out aligned so I could actually see the nested layers you are referring to. That got me my IP's. :-) I'll play with this now and see if I can harvest something targeted.. Like list all device host names running code 4.1.9, or display the serial number of the device with hostname 'foo' That should get me on my way to productive fun :-) Nick Nick Ellson - from iPhone (forgive typos) CCIE #20018 Network Hobbyist "Educating Layer 8, one user at a time." > On Oct 15, 2014, at 2:22 AM, Peter Otten <__peter__ at web.de> wrote: > > Nick Ellson wrote: > >> Hello! >> >> I have a very specific question related to the output of a Vendors API >> (Palo Alto Networks "pan.xapi" and how I might farm data from this output. >> I am new to python, doing well in the tutorials, but this is an automation >> task at work and I know the rest will be much easier once i get past the >> ability to read this dict. >> >> The code reaches in to the central Palo Alto firewall manager (Panorama) >> and executes a simple command to return all of the information for each of >> the managed firewalls in the field. It captured this output in XML I >> believe, but has the ability to return it in python dict format too, which >> looked like probably the best format to use. Here is the test I tried >> >> >> xapi.op(cmd='show devices connected', cmd_xml=True ) >> MyDict=xapi.xml_python() >> print (type(MyDict)) >> print (MyDict) >> >> >> and I get: (This displays only 2 firewalls of the 180, so you can see the >> structure, and that python does say it is a "dict") >> >> bertha bin # ./test.py >> >> {'response': {'result': {'devices': {'entry': [{'av-version': '1391-1863', >> 'unsupported-version': False, 'ip-address': '1.8.2.8', 'sw-version': >> '4.1.9', 'vsys': {'entry': [{'name': 'vsys1', 'shared-policy-md5sum': >> '8a8dcd146e24bd750ae571059bc09210', 'shared-policy-status': None, >> 'display-name': 'vsys1'}]}, 'uptime': '350 days, 14:29:49', >> 'threat-version': '460-2394', 'operational-mode': 'normal', 'multi-vsys': >> False, 'global-protect-client-package-version': '0.0.0', 'app-version': >> '460-2394', 'model': 'PA-200', 'connected': True, 'name': '001606000002', >> 'family': '200', 'url-filtering-version': '4390', 'vpn-disable-mode': >> False, 'logdb-version': '4.1.2', 'serial': '001606000002', 'hostname': >> 'bob-int-fw'}, {'av-version': '1391-1863', 'unsupported-version': False, >> 'ip-address': '1.9.8.8', 'sw-version': '4.1.9', 'vsys': {'entry': >> [{'name': 'vsys1', 'shared-policy-md5sum': >> '8a8dcd146e24bd750ae571059bc09210', 'shared-policy-status': None, >> 'display-name': 'vsys1'}]}, 'uptime': '358 days, 0:03:20', >> 'threat-version': '460-2394', 'operational-mode': 'normal', 'multi-vsys': >> False, 'global-protect-client-package-version': '0.0.0', 'app-version': >> '460-2394', 'model': 'PA-200', 'connected': True, 'name': '001606000009', >> 'family': '200', 'url-filtering-version': '4390', 'vpn-disable-mode': >> False, 'logdb-version': '4.1.2', 'serial': '001606008639', 'hostname': >> 'bib-int-fw'}, <****repeats for 180 firewalls****> ]}}, 'status': >> 'success'}} >> >> >> What I want is to parse through each firewall grabbing the "ip-address" >> value so that I can dump it to a list: >> >> >> >> >> >> For use in another network management tool so I don't rely on outsourced >> help to remember to place teh firewalls into the correct tools. >> >> But dang if every dict tutorial seems to deal with slightly simpler >> looking structures than what this puts out. I would be very appreciative >> with help stepping out of the 6 line "address book/grocery list" example >> world for a taste of something useful :-) >> >> Maybe to a Python coder, it maybe a simple even be able to randomly >> reference a firewall index number and teh value in this structure so one >> can easily just pluck any A/V pair at will.. just not for me yet :-D > > Look at your dict (I use the name 'd' instead of 'MyDict'): > > d = {"response": {"result": ...} > > So > > d["response"] > > will give you > > {"result": {"devices": ...} > > A good tool to explore a data structure like this is the interactive > interpreter. If you invoke the script with > > python -i test.py > > you have all its global variables available, i. e. > >>>> MyDict > { ... } # you should see the dictionary contents > > > On we go: > > d["response"]["result"] > > will give > > {"devices": {"entry": ...} > > Next step: > > d["response"]["result"]["devices"] > > --> > > {"entry": [...] > > That's a list for change, so you loop over it: > > entries = d["response"]["result"]["devices"]["entry"] > for entry in entries: > print(entry) # --> {..., 'ip-address': '1.8.2.8', ... } > > So the final code is: > > for entry in d["response"]["result"]["devices"]["entry"]: > print(entry["ip-address"]) > > > -- > https://mail.python.org/mailman/listinfo/python-list From kwpolska at gmail.com Wed Oct 15 10:32:28 2014 From: kwpolska at gmail.com (=?UTF-8?B?Q2hyaXMg4oCcS3dwb2xza2HigJ0gV2Fycmljaw==?=) Date: Wed, 15 Oct 2014 16:32:28 +0200 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On Wed, Oct 15, 2014 at 9:27 AM, alex23 wrote: > On 15/10/2014 12:23 PM, Juan Christian wrote: >> >> Using PyCharm is easy: >> >> File > Settings > (IDE Settings) Editor > Smart Keys > Reformat on paste >> > choose "Reformat Block" > > > > This isn't as straight forward as you imply. Say I have misindented code > like this: > > if True: > print 'true' > else: > print 'false' > print 'done' > > If I select this block in PyCharm and reformat it, I get: > > if True: > print 'true' > else: > print 'false' > print 'done' > > Which is still invalid. Even if it did work more fully, though, how would it > determine the correct placement of the last line of code? > -- > https://mail.python.org/mailman/listinfo/python-list It should parse this as else: print 'false' print 'done' Why? Because things like `print 'done'` usually have an empty line before it: if True: print 'true' else: print 'false' print 'done' That should be parsed the way you want it done. Makes perfect sense when you look at it. -- Chris ?Kwpolska? Warrick PGP: 5EAAEA16 stop html mail | always bottom-post | only UTF-8 makes sense From anuragpatibandla7 at gmail.com Wed Oct 15 11:52:30 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Wed, 15 Oct 2014 08:52:30 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: <6004f171-689a-4a69-9b3d-2800fc4216d5@googlegroups.com> Thanks Rustom for the advice. I am new to Python and getting struck at some basic things. How do I assign the values that I am printing to 3 variables say dict1, dict2, dict3? When I try to assign them before the print statement like this: d1, d2, d3 =[(queues[j], json.get(queues[j])) for j in range(len(queues))] I get an error saying 'need more than one value to unpack' From vijnaana at gmail.com Wed Oct 15 12:05:14 2014 From: vijnaana at gmail.com (vijnaana bhairava) Date: Wed, 15 Oct 2014 09:05:14 -0700 (PDT) Subject: CLI framework using python In-Reply-To: References: Message-ID: Hi Naoki, I am new to python programming. Getting used to writing basic scripts to understand python. To understand 'Click' i may need some more guidance. For e.g if i were to do 'ifconfig -a' from Click, how would the program look like. That will help me get started. What i am looking for is a class based approach. For e.g all interface related commands could come under class Interface and 'ifconfig' would probably be a method. I would like to see one working program to get a feel for 'Click' Thank You! vij On Tuesday, October 14, 2014 7:46:44 PM UTC+5:30, INADA Naoki wrote: > Click_ is another CLI framework. > > It support multi-level nested command like git and it has some nice utilities. > > I love it's design. > > > > > > > > .. _click: http://click.pocoo.org/3/ > > > > -- > Sent from Mailbox > > > > > > On Tue, Oct 14, 2014 at 10:35 PM, vijnaana bhairava wrote: > > Hi Folks, > > > The requirement is to develop a CLI framework in python for a linux router. > > The suggestions i got is to use PyCli/Cliff. Not sure which would be the right choice! Also, a few APIs are mentioned here: > > > https://pythonhosted.org/pyCLI/#module-cli.app > > > Since i couldn't find any actual implementation which uses pyCli, > > i can't figure out how to make use of pyCLI. > > > Another question i have is whether it uses argparse? > > If so, what value add does PYCLI do? > > > Regards, > > vij > > > On Thursday, October 9, 2014 5:50:51 PM UTC+5:30, vijnaana bhairava wrote: > > > Hi, > > > > > > > > > > > > I need to develop a python CLI framework. > > > > > > > > > > > > For example if i need to set an ip address in linux: > > > > > > > > > > > > ifconfig eth0 172.16.25.125 > > > > > > > > > > > > I should be able to use python to do the above. > > > > > > > > > > > > 1. The user will execute a python script to which i will pass the params eth0 and ip address (something like ifconf.py eth0 172.16.25.125) > > > > > > > > > > > > 2. Within the script i grab the params and do something to the effect of user executing 'ifconfig eth0 172.16.25.125' from the shell. > > > > > > > > > > > > 3. There are other such commands for which i will be using python scripts. I came across pyCLI, but it doesn't have much documentation, so couldn't figure out how to move forward. > > > > > > > > > > > > 4. The CLI framework needs to reuse code so i didn't want to use pure python and develop a framework from scratch. Rather use something like pyCLI/CLIFF. > > > > > > > > > > > > The problem is lack of documentation with examples on how to use the above. > > > > > > > > > > > > Any guidance would be greatly appreciated. > > > > > > > > > > > > Regards & Thanks, > > > > > > Vij > > -- > > https://mail.python.org/mailman/listinfo/python-list From rustompmody at gmail.com Wed Oct 15 12:06:25 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 15 Oct 2014 09:06:25 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <6004f171-689a-4a69-9b3d-2800fc4216d5@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> <6004f171-689a-4a69-9b3d-2800fc4216d5@googlegroups.com> Message-ID: <07fd3d66-6343-4fe4-bb38-5d98eff4062d@googlegroups.com> On Wednesday, October 15, 2014 9:22:48 PM UTC+5:30, Anurag Patibandla wrote: > Thanks Rustom for the advice. > I am new to Python and getting struck at some basic things. How do I assign the values that I am printing to 3 variables say dict1, dict2, dict3? > When I try to assign them before the print statement like this: > d1, d2, d3 =[(queues[j], json.get(queues[j])) for j in range(len(queues))] > I get an error saying 'need more than one value to unpack' Probably means your comprehension [(queues[j], json.get(queues[j])) for j in range(len(queues))] is having less than 3 values >>> lst = [1,2,3] >>> x,y,z = lst >>> (x,y,z) # note no need to print (1, 2, 3) >>> lst=[1] >>> x,y,z=lst Traceback (most recent call last): File "", line 1, in ValueError: need more than 1 value to unpack >>> lst=[1,2,3,4] >>> x,y,z=lst Traceback (most recent call last): File "", line 1, in ValueError: too many values to unpack ================ I suggest youdont directly start with multiple assignment Instead do it in two steps dicts = [(queues[j], json.get(queues[j])) for j in range(len(queues))] d0 = dicts[0] d1 = dicts[1] d2 = dicts[2] When that works go to the more compact form Also please get rid of the range(len(queues)) Its unpythonic! From anuragpatibandla7 at gmail.com Wed Oct 15 12:28:38 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Wed, 15 Oct 2014 09:28:38 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: <26e61c1f-807c-4504-89b6-46771e0d51be@googlegroups.com> First the values printed by '[(queues[j], json.get(queues[j])) for j in range(len(queues))] ' is a list, so I tried to convert it into a dict using dict(). And then I tried doing dict[0] but there is an error which says: 'type' object has no attribute '__getitem__' From rustompmody at gmail.com Wed Oct 15 12:43:06 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 15 Oct 2014 09:43:06 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <26e61c1f-807c-4504-89b6-46771e0d51be@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> <26e61c1f-807c-4504-89b6-46771e0d51be@googlegroups.com> Message-ID: On Wednesday, October 15, 2014 9:58:49 PM UTC+5:30, Anurag Patibandla wrote: > First the values printed by > '[(queues[j], json.get(queues[j])) for j in range(len(queues))] ' > is a list, so I tried to convert it into a dict using dict(). > And then I tried doing dict[0] but there is an error which says: > 'type' object has no attribute '__getitem__' print each step in the process until the error step Also assuming [(queues[j], json.get(queues[j])) for j in range(len(queues))] is the same as [(q, json.get(q) for q in queues] do a = [(q, json.get(q) for q in queues] print a b = dict(a) print b c = b[0] print c or whatever it is you are doing and PASTE (not NARRATE) the results From anuragpatibandla7 at gmail.com Wed Oct 15 12:57:28 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Wed, 15 Oct 2014 09:57:28 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: keys = json.keys() order = list(keys) q1 = int(round(len(keys)*0.2)) q2 = int(round(len(keys)*0.3)) q3 = int(round(len(keys)*0.5)) b = [q1,q2,q3] n=0 for i in b: queues = order[n:n+i] n = n+i #print queues #print [(queues[j], json.get(queues[j])) for j in range(len(queues))] lists = [(queues[j], json.get(queues[j])) for j in range(len(queues))] #print lists dicts = dict(lists) print dicts print dict[0] Print dicts works as expected giving me the combine dictionary values. But when I say dict[0]. I see the error: TypeError: 'type' object has no attribute '__getitem__' From rustompmody at gmail.com Wed Oct 15 12:59:12 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 15 Oct 2014 09:59:12 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> <26e61c1f-807c-4504-89b6-46771e0d51be@googlegroups.com> Message-ID: <5c41697f-cb94-4803-b56e-d8d3909216cf@googlegroups.com> On Wednesday, October 15, 2014 10:13:18 PM UTC+5:30, Rustom Mody wrote: > On Wednesday, October 15, 2014 9:58:49 PM UTC+5:30, Anurag Patibandla wrote: > > First the values printed by > > '[(queues[j], json.get(queues[j])) for j in range(len(queues))] ' > > is a list, so I tried to convert it into a dict using dict(). > > And then I tried doing dict[0] but there is an error which says: > > 'type' object has no attribute '__getitem__' Also there are dictionary comprehensions recently added to python: http://legacy.python.org/dev/peps/pep-0274/ Can generally be used if you are doing dict(a list comprehension) To start with though, I suggest you stay with the longer older form until you understand how it works From anuragpatibandla7 at gmail.com Wed Oct 15 13:00:38 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Wed, 15 Oct 2014 10:00:38 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: keys = json.keys() order = list(keys) q1 = int(round(len(keys)*0.2)) q2 = int(round(len(keys)*0.3)) q3 = int(round(len(keys)*0.5)) b = [q1,q2,q3] n=0 for i in b: queues = order[n:n+i] n = n+i lists = [(queues[j], json.get(queues[j])) for j in range(len(queues))] dicts = dict(lists) print dicts print dict[0] print dicts works as expected. It gives me the entire dictionary. But when I do dicts[0], there is the following error: 'type' object has no attribute '__getitem__' From tjreedy at udel.edu Wed Oct 15 13:12:51 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Oct 2014 13:12:51 -0400 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On 10/15/2014 10:32 AM, Chris ?Kwpolska? Warrick wrote: > On Wed, Oct 15, 2014 at 9:27 AM, alex23 wrote: >> On 15/10/2014 12:23 PM, Juan Christian wrote: >>> >>> Using PyCharm is easy: >>> >>> File > Settings > (IDE Settings) Editor > Smart Keys > Reformat on paste >>> > choose "Reformat Block" >> >> >> >> This isn't as straight forward as you imply. Say I have misindented code >> like this: >> >> if True: >> print 'true' >> else: >> print 'false' >> print 'done' >> >> If I select this block in PyCharm and reformat it, I get: >> >> if True: >> print 'true' >> else: >> print 'false' >> print 'done' >> >> Which is still invalid. Even if it did work more fully, though, how would it >> determine the correct placement of the last line of code? >> -- >> https://mail.python.org/mailman/listinfo/python-list > > It should parse this as > > else: > print 'false' > print 'done' > > Why? Because things like `print 'done'` usually have an empty line before it: There is no such rule in Python so it hardly dependable for auto indenting. > if True: > print 'true' > else: > print 'false' > > print 'done' > > That should be parsed the way you want it done. Makes perfect sense > when you look at it. > -- Terry Jan Reedy From rustompmody at gmail.com Wed Oct 15 13:10:26 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 15 Oct 2014 10:10:26 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: <7056aefb-600a-4bcf-a4f2-2b0f45824c88@googlegroups.com> On Wednesday, October 15, 2014 10:30:49 PM UTC+5:30, Anurag Patibandla wrote: > keys = json.keys() > order = list(keys) > q1 = int(round(len(keys)*0.2)) > q2 = int(round(len(keys)*0.3)) > q3 = int(round(len(keys)*0.5)) > b = [q1,q2,q3] > n=0 > for i in b: > queues = order[n:n+i] > n = n+i > lists = [(queues[j], json.get(queues[j])) for j in range(len(queues))] > dicts = dict(lists) > print dicts > print dict[0] > print dicts works as expected. It gives me the entire dictionary. But when I do dicts[0], there is the following error: > 'type' object has no attribute '__getitem__' Do you want dict[0] ?? I think you want dicts[0] From anuragpatibandla7 at gmail.com Wed Oct 15 13:20:20 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Wed, 15 Oct 2014 10:20:20 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <7056aefb-600a-4bcf-a4f2-2b0f45824c88@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> <7056aefb-600a-4bcf-a4f2-2b0f45824c88@googlegroups.com> Message-ID: <5f3989af-31bf-4896-9770-a7703b8b9a58@googlegroups.com> On Wednesday, October 15, 2014 1:10:41 PM UTC-4, Rustom Mody wrote: > On Wednesday, October 15, 2014 10:30:49 PM UTC+5:30, Anurag Patibandla wrote: > > > keys = json.keys() > > > order = list(keys) > > > q1 = int(round(len(keys)*0.2)) > > > q2 = int(round(len(keys)*0.3)) > > > q3 = int(round(len(keys)*0.5)) > > > b = [q1,q2,q3] > > > n=0 > > > for i in b: > > > queues = order[n:n+i] > > > > > n = n+i > > > lists = [(queues[j], json.get(queues[j])) for j in range(len(queues))] > > > > > dicts = dict(lists) > > > print dicts > > > print dict[0] > > > > > > > print dicts works as expected. It gives me the entire dictionary. But when I do dicts[0], there is the following error: > > > 'type' object has no attribute '__getitem__' > > > > Do you want dict[0] ?? > > I think you want dicts[0] Sorry about that. dicts[0] gives me a KeyError: 0 From anuragpatibandla7 at gmail.com Wed Oct 15 13:20:57 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Wed, 15 Oct 2014 10:20:57 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: Here is my sample dict if that helps: json = {"1": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 1, "m_Quantile": "80", "m_Controller": "Python", "m_Method": "Distributed", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "3": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 3, "m_Quantile": "90", "m_Controller": "Python", "m_Method": "Distributed", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "2": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 2, "m_Quantile": "80", "m_Controller": "Python", "m_Method": "GARCH", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "4": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 4, "m_Quantile": "90", "m_Controller": "Python", "m_Method": "GARCH", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}} From rustompmody at gmail.com Wed Oct 15 13:35:30 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 15 Oct 2014 10:35:30 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: <4b844872-b21e-4286-97a7-a76076f25809@googlegroups.com> On Wednesday, October 15, 2014 10:51:11 PM UTC+5:30, Anurag Patibandla wrote: > Here is my sample dict if that helps: > > > > json = {"1": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 1, "m_Quantile": "80", "m_Controller": "Python", "m_Method": "Distributed", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "3": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 3, "m_Quantile": "90", "m_Controller": "Python", "m_Method": "Distributed", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "2": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 2, "m_Quantile": "80", "m_Controller": "Python", "m_Method": "GARCH", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "4": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 4, "m_Quantile": "90", "m_Controller": "Python", "m_Method": "GARCH", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}} Right So your dict (which is dicts !) we have >>> json.keys() ['1', '3', '2', '4'] And so >>> json[0] Traceback (most recent call last): File "", line 1, in KeyError: 0 >>> json['0'] Traceback (most recent call last): File "", line 1, in KeyError: '0' >>> json['1'] {'Status': 'Submitted', 'Startdate': ['01/01/2011'], 'Enddate': ['02/02/2012'], 'Job_ID': 1, 'm_Quantile': '80', 'Allocation_3': ['50'], 'm_Method': 'Distributed', 'm_Controller': 'Python', 'Allocation_2': ['30'], 'Allocation_1': ['20'], 'Asset_2': ['YHOO'], 'Note': '', 'VaR': '', 'submit': ['Submit'], 'm_Iterations': '1000', 'Asset_3': ['CAT'], 'Asset_1': ['AAPL']} IOW 0 is not a key Neither is '0' (the string containing the char 0) But the string '1' is a valid key From davea at davea.name Wed Oct 15 13:43:58 2014 From: davea at davea.name (Dave Angel) Date: Wed, 15 Oct 2014 13:43:58 -0400 (EDT) Subject: Parsing Python dictionary with multiple objects References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> <7582dd3f-c0e1-4d5e-a03e-20bf711d1e79@googlegroups.com> Message-ID: Anurag Patibandla Wrote in message: > Thanks for the response. > Here is the code that I have tried. > > from operator import itemgetter > keys = json.keys() > order = list(keys) > q1 = int(round(len(keys)*0.2)) > q2 = int(round(len(keys)*0.3)) > q3 = int(round(len(keys)*0.5)) > b = [q1,q2,q3] > n=0 threedicts = [] > for i in b: > queues = order[n:n+i] > > n = n+i > print queues > > for j in range(len(queues)): > q = (queues[j], json.get(queues[j])) > print q > onedict = {} for q in queues: onedict[q] = json[q] threedicts.append (onedict) dict1, dictw, dict3 = threedicts > By this I am able to get the 3 smaller dicts I want, but can you help me assign them to 3 variables? > The dicts need not be ordered but it would be better if they are ordered. > dicts are not ordered. If you want the items in a particular order, you have to do that after extraction from the dict. There is a related type called collections.OrderedDict, which 'remembers' the order things were added. -- DaveA From davea at davea.name Wed Oct 15 13:50:54 2014 From: davea at davea.name (Dave Angel) Date: Wed, 15 Oct 2014 13:50:54 -0400 (EDT) Subject: Parsing Python dictionary with multiple objects References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> <7056aefb-600a-4bcf-a4f2-2b0f45824c88@googlegroups.com> <5f3989af-31bf-4896-9770-a7703b8b9a58@googlegroups.com> Message-ID: Anurag Patibandla Wrote in message: > On Wednesday, October 15, 2014 1:10:41 PM UTC-4, Rustom Mody wrote: >> On Wednesday, October 15, 2014 10:30:49 PM UTC+5:30, Anurag Patibandla wrote: >> >> > keys = json.keys() >> >> > order = list(keys) >> >> > q1 = int(round(len(keys)*0.2)) >> >> > q2 = int(round(len(keys)*0.3)) >> >> > q3 = int(round(len(keys)*0.5)) >> >> > b = [q1,q2,q3] >> >> > n=0 >> >> > for i in b: >> >> > queues = order[n:n+i] >> >> >> >> > n = n+i >> >> > lists = [(queues[j], json.get(queues[j])) for j in range(len(queues))] >> >> >> >> > dicts = dict(lists) >> >> > print dicts >> >> > print dict[0] >> >> >> >> >> >> > print dicts works as expected. It gives me the entire dictionary. But when I do dicts[0], there is the following error: >> >> > 'type' object has no attribute '__getitem__' >> >> >> >> Do you want dict[0] ?? >> >> I think you want dicts[0] > > Sorry about that. > dicts[0] gives me a KeyError: 0 > If the keys are all strings, why would you expect to find any items with an int key? -- DaveA From davea at davea.name Wed Oct 15 13:48:22 2014 From: davea at davea.name (Dave Angel) Date: Wed, 15 Oct 2014 13:48:22 -0400 (EDT) Subject: Parsing Python dictionary with multiple objects References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> Message-ID: Anurag Patibandla Wrote in message: > dicts = dict(lists) > print dicts > print dict[0] > > Print dicts works as expected giving me the combine dictionary values. But when I say dict[0]. I see the error: > TypeError: 'type' object has no attribute '__getitem__' > Of course. You forgot the s in the name dicts. So you were referring to the dict class, not your variable. -- DaveA From davea at davea.name Wed Oct 15 13:58:33 2014 From: davea at davea.name (Dave Angel) Date: Wed, 15 Oct 2014 13:58:33 -0400 (EDT) Subject: [ANN] pdb-clone 1.9 - a fast clone of pdb with the remote debugging and attach features References: <543E5946.1010802@gmail.com> Message-ID: Xavier de Gaye Wrote in message: > pdb-clone 1.9 has been released at Pypi: https://pypi.python.org/pypi/pdb-clone > > Features: > * Improve significantly pdb performance. With breakpoints, pdb-clone runs just above the speed of the interpreter while pdb runs at 10 to 100 times the speed of the interpreter. You probably mean below, and .1 to .01 times the speed. I've never seen a debugger that substantially improves the code's performance. > > * Extend pdb with remote debugging. A remote debugging session may be started when the program stops at a `pdb.set_trace_remote()` hard-coded breakpoint, or at any time and multiple times by > attaching to the process main thread. This feature is implemented in the py3 and py2.7 versions of pdb-clone. > > * Fix pdb long standing bugs entered in the python issue tracker. > > * Add a bdb comprehensive test suite (more than 70 tests) and run both the Python pdb and pdb-clone bdb test suites. > > * Three versions of pdb-clone are supported: > * The py3 version of pdb-clone runs on python3 from python 3.2 onward. > * The py2.7 vesion runs on python 2.7. > * The py2.4 version runs on all python versions from 2.4 to 2.7 included. > > The pdb command line interface remains unchanged except for the new `detach` and `thread` pdb commands. All the versions of pdb-clone implement the most recent python3 features of pdb, as defined in > Python documentation. > -- DaveA From anuragpatibandla7 at gmail.com Wed Oct 15 14:27:18 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Wed, 15 Oct 2014 11:27:18 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: <4b844872-b21e-4286-97a7-a76076f25809@googlegroups.com> References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> <4b844872-b21e-4286-97a7-a76076f25809@googlegroups.com> Message-ID: <1000bb60-54bc-4aad-a3cb-77fd481af93c@googlegroups.com> On Wednesday, October 15, 2014 1:35:43 PM UTC-4, Rustom Mody wrote: > On Wednesday, October 15, 2014 10:51:11 PM UTC+5:30, Anurag Patibandla wrote: > > > Here is my sample dict if that helps: > > > > > > > > > > > > json = {"1": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 1, "m_Quantile": "80", "m_Controller": "Python", "m_Method": "Distributed", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "3": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 3, "m_Quantile": "90", "m_Controller": "Python", "m_Method": "Distributed", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "2": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 2, "m_Quantile": "80", "m_Controller": "Python", "m_Method": "GARCH", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "4": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 4, "m_Quantile": "90", "m_Controller": "Python", "m_Method": "GARCH", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}} > > > > Right > > So your dict (which is dicts !) we have > > >>> json.keys() > > ['1', '3', '2', '4'] > > > > And so > > > > >>> json[0] > > Traceback (most recent call last): > > File "", line 1, in > > KeyError: 0 > > > > >>> json['0'] > > Traceback (most recent call last): > > File "", line 1, in > > KeyError: '0' > > > > >>> json['1'] > > {'Status': 'Submitted', 'Startdate': ['01/01/2011'], 'Enddate': ['02/02/2012'], 'Job_ID': 1, 'm_Quantile': '80', 'Allocation_3': ['50'], 'm_Method': 'Distributed', 'm_Controller': 'Python', 'Allocation_2': ['30'], 'Allocation_1': ['20'], 'Asset_2': ['YHOO'], 'Note': '', 'VaR': '', 'submit': ['Submit'], 'm_Iterations': '1000', 'Asset_3': ['CAT'], 'Asset_1': ['AAPL']} > > > > IOW 0 is not a key > > Neither is '0' (the string containing the char 0) > > But the string '1' is a valid key Yes, but I can't just do 'json['1']', at the end of the code I need to do a 'dicts['1']', or 'dicts['2']', to get the smaller dicts which still gives me a 'KeyError: 1' From shivaji_tn at yahoo.com Wed Oct 15 14:39:09 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Wed, 15 Oct 2014 18:39:09 +0000 (UTC) Subject: Creating a counter Message-ID: Hi, I am trying to search a string through files in a directory - however while Python script works on it and writes a log - I want to present the user with count of number of strings found. So it should increment for each string found. How do I implement it? If I use a print() within a if condition statement - and execute the script in terminal - for each find, the print() prints in new line instead of a constantly incrementing counter. Thanks, Shiva From anuragpatibandla7 at gmail.com Wed Oct 15 14:35:53 2014 From: anuragpatibandla7 at gmail.com (Anurag Patibandla) Date: Wed, 15 Oct 2014 11:35:53 -0700 (PDT) Subject: Parsing Python dictionary with multiple objects In-Reply-To: References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> <7582dd3f-c0e1-4d5e-a03e-20bf711d1e79@googlegroups.com> Message-ID: <7779f647-b676-47b6-82b4-d3024299cf7c@googlegroups.com> On Wednesday, October 15, 2014 1:41:13 PM UTC-4, Dave Angel wrote: > Anurag Patibandla Wrote in message: > > > Thanks for the response. > > > Here is the code that I have tried. > > > > > > from operator import itemgetter > > > keys = json.keys() > > > order = list(keys) > > > q1 = int(round(len(keys)*0.2)) > > > q2 = int(round(len(keys)*0.3)) > > > q3 = int(round(len(keys)*0.5)) > > > b = [q1,q2,q3] > > > n=0 > > > > threedicts = [] > > > > > for i in b: > > > queues = order[n:n+i] > > > > > > n = n+i > > > print queues > > > > > > for j in range(len(queues)): > > > q = (queues[j], json.get(queues[j])) > > > print q > > > > > > > onedict = {} > > for q in queues: > > onedict[q] = json[q] > > threedicts.append (onedict) > > dict1, dictw, dict3 = threedicts > > > > > By this I am able to get the 3 smaller dicts I want, but can you help me assign them to 3 variables? > > > The dicts need not be ordered but it would be better if they are ordered. > > > > > > > dicts are not ordered. If you want the items in a particular > > order, you have to do that after extraction from the dict. There > > is a related type called collections.OrderedDict, which > > 'remembers' the order things were added. > > > > -- > > DaveA Thanks DaveA! This works perfectly! From ryanshuell at gmail.com Wed Oct 15 15:09:50 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Wed, 15 Oct 2014 12:09:50 -0700 (PDT) Subject: How to debug Python IDLE? Message-ID: I'm wondering how to debug code in IDLE Python 3.4. I found this. http://www.cs.uky.edu/~paulp/CS115F11/notes/debug/debug.html That looks pretty helpful, but mine is nothing like that. All my controls are greyed out. The debugger does basically...nothing. All I get is messages like this. [DEBUG ON] >>> [DEBUG OFF] >>> [DEBUG ON] >>> It doesn't debug anything at all. Any idea what's wrong? Thanks. From tntsugar at googlemail.com Wed Oct 15 15:12:28 2014 From: tntsugar at googlemail.com (tntsugar at googlemail.com) Date: Wed, 15 Oct 2014 21:12:28 +0200 Subject: tkinter (Tkinter ;-) ) Message-ID: hi guys, can you help me please... i installed python 3.4.2 and the IEP editor... now i want to program a little thingy with a window, a button and some entry fields that are connected to a simple calculation... the IEP shows me "3.4.2 without GUI"... strange... in the instalation i see the package being installed but when i check in the command box i get a message that tkinter is not installed (yes i tried both ways T and t...)... any ideas on what i can do to start programming GUI with tkinter? be well and greetings from the desert, GD -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Wed Oct 15 15:17:11 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 15 Oct 2014 13:17:11 -0600 Subject: Creating a counter In-Reply-To: References: Message-ID: On Wed, Oct 15, 2014 at 12:39 PM, Shiva wrote: > Hi, > > I am trying to search a string through files in a directory - however while > Python script works on it and writes a log - I want to present the user with > count of number of strings found. So it should increment for each string found. > > How do I implement it? > > If I use a print() within a if condition statement - and execute the script > in terminal - for each find, the print() prints in new line instead of a > constantly incrementing counter. Before the loop, initialize the counter to 0: counter = 0 Inside the loop, increment the counter: counter = counter + 1 # can be shortened to: counter += 1 Alternatively, if you have all the strings you want to count in a list, you can just check the length of the list: print(len(os.listdir("/some/directory"))) From tjreedy at udel.edu Wed Oct 15 15:22:46 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Oct 2014 15:22:46 -0400 Subject: How to debug Python IDLE? In-Reply-To: References: Message-ID: On 10/15/2014 3:09 PM, ryguy7272 wrote: > I'm wondering how to debug code in IDLE Python 3.4. I found this. Use 3.4.2, which has an important bugfix for debugger. > http://www.cs.uky.edu/~paulp/CS115F11/notes/debug/debug.html > > That looks pretty helpful, > but mine is nothing like that. All my controls are greyed out. That is normal when you first turn debugger on. You have to load a file in the editor and then run it (F5). On the site above, the file is volume.py. The the debugger is 'activated'. -- Terry Jan Reedy From tjreedy at udel.edu Wed Oct 15 15:25:33 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Oct 2014 15:25:33 -0400 Subject: tkinter (Tkinter ;-) ) In-Reply-To: References: Message-ID: On 10/15/2014 3:12 PM, tntsugar at googlemail.com wrote: > hi guys, > > can you help me please... > > i installed python 3.4.2 What system? > and the IEP editor... I have no idea what that is. > now i want to program a little thingy with a window, a button and some > entry fields that are connected to a simple calculation... > > the IEP shows me "3.4.2 without GUI"... > > strange... in the instalation i see the package being installed Which package. > but when > i check in the command box i get a message that tkinter is not installed > (yes i tried both ways T and t...)... tkinter needs tcl/tk. The Windows installer installs this automtically. The installer on other systems may not. -- Terry Jan Reedy From ian.g.kelly at gmail.com Wed Oct 15 15:30:17 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 15 Oct 2014 13:30:17 -0600 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On Wed, Oct 15, 2014 at 11:12 AM, Terry Reedy wrote: > On 10/15/2014 10:32 AM, Chris ?Kwpolska? Warrick wrote: >> It should parse this as >> >> else: >> print 'false' >> print 'done' >> >> Why? Because things like `print 'done'` usually have an empty line before >> it: > > > There is no such rule in Python so it hardly dependable for auto indenting. I agree. I very rarely use blank lines inside functions. As I see it, if you feel you need a blank line for separation within a function, that's an indication your function is overly complex and should be broken up. Keeping blank lines out of functions also makes it easy to copy/paste those functions into the interactive interpreter, which can be handy e.g. when sharing snippets of code by email. From tjreedy at udel.edu Wed Oct 15 15:26:52 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Oct 2014 15:26:52 -0400 Subject: Creating a counter In-Reply-To: References: Message-ID: On 10/15/2014 2:39 PM, Shiva wrote: > Hi, > > I am trying to search a string through files in a directory - however while > Python script works on it and writes a log - I want to present the user with > count of number of strings found. So it should increment for each string found. > > How do I implement it? n=0 before the look and n += 1 withing the loop -- Terry Jan Reedy From vincent.vande.vyvre at telenet.be Wed Oct 15 15:24:27 2014 From: vincent.vande.vyvre at telenet.be (Vincent Vande Vyvre) Date: Wed, 15 Oct 2014 21:24:27 +0200 Subject: Creating a counter In-Reply-To: References: Message-ID: <543EC9EB.8010202@telenet.be> Le 15/10/2014 20:39, Shiva a ?crit : > Hi, > > I am trying to search a string through files in a directory - however while > Python script works on it and writes a log - I want to present the user with > count of number of strings found. So it should increment for each string found. > > How do I implement it? > > If I use a print() within a if condition statement - and execute the script > in terminal - for each find, the print() prints in new line instead of a > constantly incrementing counter. > > Thanks, > Shiva > Try this: >>> def counter(x): ... for i in range(x): ... print "\rProgress .............. %s" % i, ... sys.stdout.flush() ... time.sleep(1) ... >>> counter(5) Vincent. From ryanshuell at gmail.com Wed Oct 15 15:36:25 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Wed, 15 Oct 2014 12:36:25 -0700 (PDT) Subject: How to debug Python IDLE? In-Reply-To: References: Message-ID: On Wednesday, October 15, 2014 3:23:22 PM UTC-4, Terry Reedy wrote: > On 10/15/2014 3:09 PM, ryguy7272 wrote: > > > I'm wondering how to debug code in IDLE Python 3.4. I found this. > > > > Use 3.4.2, which has an important bugfix for debugger. > > > > > http://www.cs.uky.edu/~paulp/CS115F11/notes/debug/debug.html > > > > > > That looks pretty helpful, > > > > > but mine is nothing like that. All my controls are greyed out. > > > > That is normal when you first turn debugger on. You have to load a file > > in the editor and then run it (F5). On the site above, the file is > > volume.py. The the debugger is 'activated'. > > > > -- > > Terry Jan Reedy Oh, I didn't know that's how it works. ok. Makes sense. Something is still wrong though. I have a file named 'test_script.py'. Here's the code: def showMaxFactor(num): count = num / 2 while count > 1: if num % count == 0: print 'largest factor of %d is %d' % \ (num, count) break count -= 1 else: print num, "is prime" for eachNum in range(10, 21): showMaxFactor(eachNum) With the debugger ON, I hit F5 and get this. 'Expected an indent block' I wouldn't say that's debugging anything. I can't tell what line is throwing the error, or how to fix it. Any thoughts? From python at mrabarnett.plus.com Wed Oct 15 15:48:30 2014 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 15 Oct 2014 20:48:30 +0100 Subject: Creating a counter In-Reply-To: <543EC9EB.8010202@telenet.be> References: <543EC9EB.8010202@telenet.be> Message-ID: <543ECF8E.90804@mrabarnett.plus.com> On 2014-10-15 20:24, Vincent Vande Vyvre wrote: > Le 15/10/2014 20:39, Shiva a ?crit : >> Hi, >> >> I am trying to search a string through files in a directory - >> however while Python script works on it and writes a log - I want >> to present the user with count of number of strings found. So it >> should increment for each string found. >> >> How do I implement it? >> >> If I use a print() within a if condition statement - and execute >> the script in terminal - for each find, the print() prints in new >> line instead of a constantly incrementing counter. >> > Try this: > > >>> def counter(x): > ... for i in range(x): > ... print "\rProgress .............. %s" % i, > ... sys.stdout.flush() > ... time.sleep(1) > ... > >>> counter(5) > In Python 3, you can specify what to do at the end of the print. Normally it prints a newline, but you can make it print nothing at the end, leaving the cursor just after the last thing printed: >>> def counter(x): ... for i in range(x): ... print("\rProgress .............. %s" % i, end="") ... sys.stdout.flush() ... time.sleep(1) ... >>> counter(5) The "\r" moves the cursor back to the start of the line so that it overwrites what was printed last time. From python at mrabarnett.plus.com Wed Oct 15 15:52:17 2014 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 15 Oct 2014 20:52:17 +0100 Subject: How to debug Python IDLE? In-Reply-To: References: Message-ID: <543ED071.6040209@mrabarnett.plus.com> On 2014-10-15 20:36, ryguy7272 wrote: > On Wednesday, October 15, 2014 3:23:22 PM UTC-4, Terry Reedy wrote: >> On 10/15/2014 3:09 PM, ryguy7272 wrote: >> >> > I'm wondering how to debug code in IDLE Python 3.4. I found this. >> >> >> >> Use 3.4.2, which has an important bugfix for debugger. >> >> >> >> > http://www.cs.uky.edu/~paulp/CS115F11/notes/debug/debug.html >> >> > >> >> > That looks pretty helpful, >> >> >> >> > but mine is nothing like that. All my controls are greyed out. >> >> >> >> That is normal when you first turn debugger on. You have to load a file >> >> in the editor and then run it (F5). On the site above, the file is >> >> volume.py. The the debugger is 'activated'. >> >> >> >> -- >> >> Terry Jan Reedy > > > Oh, I didn't know that's how it works. ok. Makes sense. Something is still wrong though. I have a file named 'test_script.py'. > > Here's the code: > > def showMaxFactor(num): > count = num / 2 > while count > 1: > if num % count == 0: > print 'largest factor of %d is %d' % \ > (num, count) > break > count -= 1 > else: > print num, "is prime" > for eachNum in range(10, 21): > showMaxFactor(eachNum) > > With the debugger ON, I hit F5 and get this. > 'Expected an indent block' > > I wouldn't say that's debugging anything. I can't tell what line is throwing the error, or how to fix it. > > Any thoughts? > The 'print' line is indented the same as the 'if' line. From gary.herron at islandtraining.com Wed Oct 15 16:04:03 2014 From: gary.herron at islandtraining.com (Gary Herron) Date: Wed, 15 Oct 2014 13:04:03 -0700 Subject: Creating a counter In-Reply-To: References: Message-ID: <543ED333.6060102@islandtraining.com> On 10/15/2014 11:39 AM, Shiva wrote: > Hi, > > I am trying to search a string through files in a directory - however while > Python script works on it and writes a log - I want to present the user with > count of number of strings found. So it should increment for each string found. > > How do I implement it? > > If I use a print() within a if condition statement - and execute the script > in terminal - for each find, the print() prints in new line instead of a > constantly incrementing counter. > > Thanks, > Shiva > The question seems confuse the word "increment". If you are asking how to count, plenty of responders have answered count = count+1 and similar. However, the second paragraphs seems to use the word "increment" to mean displaying the counter on a single line overwriting itself instead of a scrolling list of values one-per-line. The solution may depend on what is displaying the value as you write it out, but if it's a terminal/command-prompt /console-window, then you want the write to finish with a carriage-return alone instead of a carriage-return/new-line combination. In Python that is represented with a \r instead of a \n. Python2: print counter, '\r', # The ending comma means do NOT output the usual \n Python3: print(counter, end='\r') Gary Herron From ryanshuell at gmail.com Wed Oct 15 16:45:59 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Wed, 15 Oct 2014 13:45:59 -0700 (PDT) Subject: How to debug Python IDLE? In-Reply-To: References: Message-ID: <68679eed-b778-4341-a4c2-9b2ff8b422bb@googlegroups.com> On Wednesday, October 15, 2014 3:10:05 PM UTC-4, ryguy7272 wrote: > I'm wondering how to debug code in IDLE Python 3.4. I found this. > > http://www.cs.uky.edu/~paulp/CS115F11/notes/debug/debug.html > > > > That looks pretty helpful, but mine is nothing like that. All my controls are greyed out. The debugger does basically...nothing. All I get is messages like this. > > > > [DEBUG ON] > > >>> > > [DEBUG OFF] > > >>> > > [DEBUG ON] > > >>> > > > > It doesn't debug anything at all. > > > > Any idea what's wrong? > > Thanks. Yes. exactly. So why is it throwing an error and how can I truly debug it? Normally, you can step through code line by line, but I don't see any way to do this using Python. Man, I've been in all kinds of development roles, for over 10 years, using all kinds of languages, and I've never worked with anything as difficult as Python. It seems so simple, but actually nothing works for me. I've read 4 books on Python and I've been working on small snippets of code, for 2 months now. Almost nothing at all has worked for me. From breamoreboy at yahoo.co.uk Wed Oct 15 17:19:47 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 15 Oct 2014 22:19:47 +0100 Subject: How to debug Python IDLE? In-Reply-To: <68679eed-b778-4341-a4c2-9b2ff8b422bb@googlegroups.com> References: <68679eed-b778-4341-a4c2-9b2ff8b422bb@googlegroups.com> Message-ID: On 15/10/2014 21:45, ryguy7272 wrote: > On Wednesday, October 15, 2014 3:10:05 PM UTC-4, ryguy7272 wrote: >> I'm wondering how to debug code in IDLE Python 3.4. I found this. >> >> http://www.cs.uky.edu/~paulp/CS115F11/notes/debug/debug.html >> >> >> >> That looks pretty helpful, but mine is nothing like that. All my controls are greyed out. The debugger does basically...nothing. All I get is messages like this. >> >> >> >> [DEBUG ON] >> >>>>> >> >> [DEBUG OFF] >> >>>>> >> >> [DEBUG ON] >> >>>>> >> >> >> >> It doesn't debug anything at all. >> >> >> >> Any idea what's wrong? >> >> Thanks. > > > Yes. exactly. So why is it throwing an error and how can I truly debug it? Normally, you can step through code line by line, but I don't see any way to do this using Python. > > Man, I've been in all kinds of development roles, for over 10 years, using all kinds of languages, and I've never worked with anything as difficult as Python. It seems so simple, but actually nothing works for me. I've read 4 books on Python and I've been working on small snippets of code, for 2 months now. Almost nothing at all has worked for me. > What did you not understand about the answers given by Terry Reedy and MRAB? Why are you using a debugger, I can't remember the last time I needed one with Python? Please don't try to fight the language, use the 1000s of man years experience here to make life easier for yourself. Even if you've no Java experience try reading this http://dirtsimple.org/2004/12/python-is-not-java.html and this http://dirtsimple.org/2004/12/java-is-not-python-either.html to get a feel for Python. If you haven't read the Zen of Python do that as well. I'll let you look that one up :) Further would you please access this list via https://mail.python.org/mailman/listinfo/python-list or read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing and single line paragraphs, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From davea at davea.name Wed Oct 15 18:25:19 2014 From: davea at davea.name (Dave Angel) Date: Wed, 15 Oct 2014 18:25:19 -0400 (EDT) Subject: Parsing Python dictionary with multiple objects References: <64f7e57a-4be3-44f4-b11c-0d270fc91809@googlegroups.com> <4b844872-b21e-4286-97a7-a76076f25809@googlegroups.com> <1000bb60-54bc-4aad-a3cb-77fd481af93c@googlegroups.com> Message-ID: Anurag Patibandla Wrote in message: > On Wednesday, October 15, 2014 1:35:43 PM UTC-4, Rustom Mody wrote: >> On Wednesday, October 15, 2014 10:51:11 PM UTC+5:30, Anurag Patibandla wrote: >> >> > Here is my sample dict if that helps: >> >> > >> >> > >> >> > >> >> > json = {"1": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 1, "m_Quantile": "80", "m_Controller": "Python", "m_Method": "Distributed", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "3": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 3, "m_Quantile": "90", "m_Controller": "Python", "m_Method": "Distributed", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "2": {"Status": "Submitted", "Startdat > e": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 2, "m_Quantile": "80", "m_Controller": "Python", "m_Method": "GARCH", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], > "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}, "4": {"Status": "Submitted", "Startdate": ["01/01/2011"], "Enddate": ["02/02/2012"], "Job_ID": 4, "m_Quantile": "90", "m_Controller": "Python", "m_Method": "GARCH", "Allocation_3": ["50"], "Allocation_2": ["30"], "Allocation_1": ["20"], "Note": "", "m_Iterations": "1000", "submit": ["Submit"], "VaR": "", "Asset_2": ["YHOO"], "Asset_3": ["CAT"], "Asset_1": ["AAPL"]}} >> >> >> >> Right >> >> So your dict (which is dicts !) we have >> >> >>> json.keys() >> >> ['1', '3', '2', '4'] >> >> >> >> And so >> >> >> >> >>> json[0] >> >> Traceback (most recent call last): >> >> File "", line 1, in >> >> KeyError: 0 >> >> >> >> >>> json['0'] >> >> Traceback (most recent call last): >> >> File "", line 1, in >> >> KeyError: '0' >> >> >> >> >>> json['1'] >> >> {'Status': 'Submitted', 'Startdate': ['01/01/2011'], 'Enddate': ['02/02/2012'], 'Job_ID': 1, 'm_Quantile': '80', 'Allocation_3': ['50'], 'm_Method': 'Distributed', 'm_Controller': 'Python', 'Allocation_2': ['30'], 'Allocation_1': ['20'], 'Asset_2': ['YHOO'], 'Note': '', 'VaR': '', 'submit': ['Submit'], 'm_Iterations': '1000', 'Asset_3': ['CAT'], 'Asset_1': ['AAPL']} >> >> >> >> IOW 0 is not a key >> >> Neither is '0' (the string containing the char 0) >> >> But the string '1' is a valid key > > Yes, but I can't just do 'json['1']', at the end of the code I need to do a 'dicts['1']', or 'dicts['2']', to get the smaller dicts which still gives me a 'KeyError: 1' > Did you read the code I supplied, where you would wind up with three variables, dict1, ict2, and dict3? Just before assigning those, I had a LIST of dicts. Such a list can be accessed by threedicts [0] to get the first dictionary, threedicts [1] to get the next, etc. -- DaveA From ryanshuell at gmail.com Wed Oct 15 18:50:23 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Wed, 15 Oct 2014 15:50:23 -0700 (PDT) Subject: Question About Running Python code Message-ID: I'm trying to run this script (using IDLE 3.4) #!/usr/bin/env python import urllib2 import pytz import pandas as pd from bs4 import BeautifulSoup from datetime import datetime from pandas.io.data import DataReader SITE = "http://en.wikipedia.org/wiki/List_of_S%26P_500_companies" START = datetime(1900, 1, 1, 0, 0, 0, 0, pytz.utc) END = datetime.today().utcnow() def scrape_list(site): hdr = {'User-Agent': 'Mozilla/5.0'} req = urllib2.Request(site, headers=hdr) page = urllib2.urlopen(req) soup = BeautifulSoup(page) table = soup.find('table', {'class': 'wikitable sortable'}) sector_tickers = dict() for row in table.findAll('tr'): col = row.findAll('td') if len(col) > 0: sector = str(col[3].string.strip()).lower().replace(' ', '_') ticker = str(col[0].string.strip()) if sector not in sector_tickers: sector_tickers[sector] = list() sector_tickers[sector].append(ticker) return sector_tickers def download_ohlc(sector_tickers, start, end): sector_ohlc = {} for sector, tickers in sector_tickers.iteritems(): print 'Downloading data from Yahoo for %s sector' % sector data = DataReader(tickers, 'yahoo', start, end) for item in ['Open', 'High', 'Low']: data[item] = data[item] * data['Adj Close'] / data['Close'] data.rename(items={'Open': 'open', 'High': 'high', 'Low': 'low', 'Adj Close': 'close', 'Volume': 'volume'}, inplace=True) data.drop(['Close'], inplace=True) sector_ohlc[sector] = data print 'Finished downloading data' return sector_ohlc def store_HDF5(sector_ohlc, path): with pd.get_store(path) as store: for sector, ohlc in sector_ohlc.iteritems(): store[sector] = ohlc def get_snp500(): sector_tickers = scrape_list(SITE) sector_ohlc = download_ohlc(sector_tickers, START, END) store_HDF5(sector_ohlc, 'snp500.h5') if __name__ == '__main__': get_snp500() I got it from this link. http://www.thealgoengineer.com/2014/download_sp500_data/ I'm just about going insane here. I've been doing all kinds of computer programming for 11 years, and I know 10 languages. I'm trying to learn Python now, but this makes no sense to me. I would be most appreciative if someone could respond to a few questions. The error that I get is this. 'invalid syntax' The second single quote in this line is highlighted pink. print 'Downloading data from Yahoo for %s sector' % sector #1) That's very bizarre to mix single quotes and double quotes in a single language. Does Python actually mix single quotes and double quotes? #2) In the Python 3.4 Shell window, I turn the debugger on by clicking 'Debugger'. Then I run the file I just created; it's called 'stock.py'. I get the error immediately, and I can't debug anything so I can't tell what's going on. This is very frustrating. All the controls in the debugger are greyed out. What's up with the debugger? #3) My final question is this? How do I get this code running? It seems like there is a problem with a single quote, which is just silly. I can't get the debugger working, so I can't tell what's going on. The only thins I know, or I think I know, is that the proper libraries seem to be installed, so that's one thing that's working. I'd really appreciate it if someone could please answer my questions and help me get this straightened out, so I can have some fun with Python. So far, I've spent 2 months reading 4 books, and trying all kinds of sample code...and almost every single thing fails and I have no idea why. From drsalists at gmail.com Wed Oct 15 19:09:21 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Wed, 15 Oct 2014 16:09:21 -0700 Subject: Question About Running Python code In-Reply-To: References: Message-ID: On Wed, Oct 15, 2014 at 3:50 PM, ryguy7272 wrote: > I'm trying to run this script (using IDLE 3.4) > I would be most appreciative if someone could respond to a few questions. > > The error that I get is this. > 'invalid syntax' You may get better help if you give the context of this message. > The second single quote in this line is highlighted pink. > print 'Downloading data from Yahoo for %s sector' % sector > > #1) That's very bizarre to mix single quotes and double quotes in a single language. Does Python actually mix single quotes and double quotes? I'm not sure what you mean by "mix". C uses single quotes and double quotes, right? Python treats single quotes and double quotes pretty much interchangeably, except if you start a string with a single quote (for example), you can easily put a double quote inside it, and you must terminate the string with another single quote. And vice versa. > #2) In the Python 3.4 Shell window, I turn the debugger on by clicking 'Debugger'. Then I run the file I just created; it's called 'stock.py'. I get the error immediately, and I can't debug anything so I can't tell what's going on. This is very frustrating. All the controls in the debugger are greyed out. What's up with the debugger? You have Python 2.x code there. The differences between 2.x and 3.x are far from insurmountable, but it does require a little code adjustment. If you're a python novice, you might be better off running this under 2.x. I believe your debugger won't help until your code compiles. > #3) My final question is this? How do I get this code running? It seems like there is a problem with a single quote, which is just silly. I can't get the debugger working, so I can't tell what's going on. The only thins I know, or I think I know, is that the proper libraries seem to be installed, so that's one thing that's working. The print statement in 2.x has been made a print function in 3.x; that's likely necessary to fix, though not necessarily sufficient. EG in 2.x: print 'hello word', 6 while in 3.x that would be: print('hello world', 6) Interestingly, you can write a single command that works in both with: print('hello world {}'.format(6)) To 2.x, it's printing the result of a parenthesized expression. To 3.x, it's a function call with one argument. > I'd really appreciate it if someone could please answer my questions and help me get this straightened out, so I can have some fun with Python. So far, I've spent 2 months reading 4 books, and trying all kinds of sample code...and almost every single thing fails and I have no idea why. You may also need to install pytz, pandas and BeautifulSoup. I favor pip or pip3 for such things. From wuwei23 at gmail.com Wed Oct 15 19:51:16 2014 From: wuwei23 at gmail.com (alex23) Date: Thu, 16 Oct 2014 09:51:16 +1000 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On 16/10/2014 12:32 AM, Chris ?Kwpolska? Warrick wrote: > It should parse this as > > else: > print 'false' > print 'done' > > Why? Because things like `print 'done'` usually have an empty line before it: > > if True: > print 'true' > else: > print 'false' > > print 'done' > > That should be parsed the way you want it done. Makes perfect sense > when you look at it. I don't think it makes any sense at all, for two reasons: 1) Empty lines have no such semantic meaning in Python. 2) Anything that strips tabs is just as likely to strip EOLs. From ryanshuell at gmail.com Wed Oct 15 20:40:25 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Wed, 15 Oct 2014 17:40:25 -0700 (PDT) Subject: Import Doesn't Import Message-ID: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> So sorry everyone. I've posted here several times today. This is VERY frustrating. So, I'm reading this link. https://docs.python.org/2/howto/urllib2.html Fetching URLs The simplest way to use urllib2 is as follows: import urllib2 response = urllib2.urlopen('http://python.org/') html = response.read() So, I fire up Python, and create a new file and name it and hit F5. All I have is thins in the file: import urllib2 response = urllib2.urlopen('http://python.org/') html = response.read() It immediately produces this error: Traceback (most recent call last): File "C:/Python34/import_web_data.py", line 1, in import urllib2 ImportError: No module named 'urllib2' ImportError: No module named 'urllib2' I'm telling Python to import because it doesn't exist and it throws an error. I don't get it; I just don't get it. If I'm working with R, I can import thousands of libraries with no errors whatsoever. With Python, I just get thousands of errors with nothing working whatsoever. I totally don't understand this language. Import means import. Right. WTF!!!!! From ryanshuell at gmail.com Wed Oct 15 20:44:00 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Wed, 15 Oct 2014 17:44:00 -0700 (PDT) Subject: Import Doesn't Import In-Reply-To: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> Message-ID: <20f25f12-d376-4b78-9fb4-e877e2fcde15@googlegroups.com> On Wednesday, October 15, 2014 8:40:40 PM UTC-4, ryguy7272 wrote: > So sorry everyone. I've posted here several times today. This is VERY frustrating. > > > > So, I'm reading this link. > > https://docs.python.org/2/howto/urllib2.html > > > > > > Fetching URLs > > The simplest way to use urllib2 is as follows: > > import urllib2 > > response = urllib2.urlopen('http://python.org/') > > html = response.read() > > > > > > So, I fire up Python, and create a new file and name it and hit F5. > > > > All I have is thins in the file: > > import urllib2 > > response = urllib2.urlopen('http://python.org/') > > html = response.read() > > > > It immediately produces this error: > > Traceback (most recent call last): > > File "C:/Python34/import_web_data.py", line 1, in > > import urllib2 > > ImportError: No module named 'urllib2' > > > > > > ImportError: No module named 'urllib2' > > I'm telling Python to import because it doesn't exist and it throws an error. I don't get it; I just don't get it. If I'm working with R, I can import thousands of libraries with no errors whatsoever. With Python, I just get thousands of errors with nothing working whatsoever. I totally don't understand this language. Import means import. Right. WTF!!!!! Either this is the most brilliant thing ever invented, or it's the biggest piece of shit ever invented. I just can't tell. All I know for sure, is that it doesn't do ANYTHING that I tell it to do. If there is another way of running Python code, like using Visual Studio, or a text file, or some such thing, let me know, and I'll do it. It seems like you should use Python to run Python, but my Python doesn't do anything at all. Yesterday I uninstalled Python 2.7, because that wouldn't do anything either. I'm just about ready to uninstall 3.4. From rosuav at gmail.com Wed Oct 15 20:54:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 16 Oct 2014 11:54:01 +1100 Subject: Import Doesn't Import In-Reply-To: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> Message-ID: On Thu, Oct 16, 2014 at 11:40 AM, ryguy7272 wrote: > I totally don't understand this language. Import means import. Right. WTF!!!!! Yes, but import from where? If you ask Python - or any other language - to "import asfadgt4tfihavzcxvzxcvaerg", do you expect it to succeed? It doesn't exist. In this case, you simply want "urllib", not "urllib2". You should be able to "import urllib" with no problems. ChrisA From cs at zip.com.au Wed Oct 15 20:42:54 2014 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 16 Oct 2014 11:42:54 +1100 Subject: Question About Running Python code In-Reply-To: References: Message-ID: <20141016004254.GA74782@cskk.homeip.net> On 15Oct2014 16:09, Dan Stromberg wrote: >On Wed, Oct 15, 2014 at 3:50 PM, ryguy7272 wrote: >> #1) That's very bizarre to mix single quotes and double quotes in a single >> language. Does Python actually mix single quotes and double quotes? > >I'm not sure what you mean by "mix". C uses single quotes and double >quotes, right? Yes, but it uses single quotes for characters (a single byte integer type) and double quotes for strings. Python doesn't really have a single character type, and lets the user use either quote mark as they see fit. Ryan finds this unfamiliar. Cheers, Cameron Simpson BTW, don't bother flaming me. I can't read. - afdenis at lims03.lerc.nasa.gov (Stephen Dennison) From drsalists at gmail.com Wed Oct 15 21:12:15 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Wed, 15 Oct 2014 18:12:15 -0700 Subject: Import Doesn't Import In-Reply-To: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> Message-ID: On Wed, Oct 15, 2014 at 5:40 PM, ryguy7272 wrote: > > ImportError: No module named 'urllib2' http://stackoverflow.com/questions/2792650/python3-error-import-error-no-module-name-urllib From python at mrabarnett.plus.com Wed Oct 15 21:13:43 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 16 Oct 2014 02:13:43 +0100 Subject: Import Doesn't Import In-Reply-To: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> Message-ID: <543F1BC7.1000205@mrabarnett.plus.com> On 2014-10-16 01:40, ryguy7272 wrote: > So sorry everyone. I've posted here several times today. This is > VERY frustrating. > > So, I'm reading this link. > https://docs.python.org/2/howto/urllib2.html > > > Fetching URLs > The simplest way to use urllib2 is as follows: > import urllib2 > response = urllib2.urlopen('http://python.org/') > html = response.read() > > > So, I fire up Python, and create a new file and name it and hit F5. > > All I have is thins in the file: > import urllib2 > response = urllib2.urlopen('http://python.org/') > html = response.read() > > It immediately produces this error: > Traceback (most recent call last): > File "C:/Python34/import_web_data.py", line 1, in > import urllib2 > ImportError: No module named 'urllib2' > > > ImportError: No module named 'urllib2' > I'm telling Python to import because it doesn't exist and it throws > an error. I don't get it; I just don't get it. If I'm working with > R, I can import thousands of libraries with no errors whatsoever. > With Python, I just get thousands of errors with nothing working > whatsoever. I totally don't understand this language. Import means > import. Right. WTF!!!!! > It raises an exception because there's no such module as 'urllib2' in Python 3. You're reading the docs here: https://docs.python.org/2/howto/urllib2.html which are for Python 2, but the path you have here: C:/Python34/import_web_data.py says that you're using Python 3.4. There's an explanation of Python 2 vs Python 3 here: https://wiki.python.org/moin/Python2orPython3 From drsalists at gmail.com Wed Oct 15 21:19:37 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Wed, 15 Oct 2014 18:19:37 -0700 Subject: Import Doesn't Import In-Reply-To: <20f25f12-d376-4b78-9fb4-e877e2fcde15@googlegroups.com> References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> <20f25f12-d376-4b78-9fb4-e877e2fcde15@googlegroups.com> Message-ID: On Wed, Oct 15, 2014 at 5:44 PM, ryguy7272 wrote: > Either this is the most brilliant thing ever invented, or it's the biggest piece of shit ever invented. I just can't tell. All I know for sure, is that it doesn't do ANYTHING that I tell it to do. Maybe you should decide whether you want to run your 2.x code on 2.7, or adapt it to 3.x. Doing both won't work well, unless you go with a version of the code carefully constructed to work on both. I believe I heard there's a way of doing Python in Visual Studio, but personally, I use Python on Linux without an IDE - mostly via a vim macro. BTW, I got your code to run, but it got stuck in a socket.recv(); I suspect Wikipedia is blocking some forms of access, so this labor may be irrelevant. Perhaps check out https://pypi.python.org/pypi?%3Aaction=search&term=stock&submit=search , and use the most relevant-looking one with a matching version of Python? From ian.g.kelly at gmail.com Wed Oct 15 21:31:31 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 15 Oct 2014 19:31:31 -0600 Subject: Question About Running Python code In-Reply-To: <20141016004254.GA74782@cskk.homeip.net> References: <20141016004254.GA74782@cskk.homeip.net> Message-ID: On Oct 15, 2014 7:04 PM, "Cameron Simpson" wrote: > > On 15Oct2014 16:09, Dan Stromberg wrote: >> >> On Wed, Oct 15, 2014 at 3:50 PM, ryguy7272 wrote: >>> >>> #1) That's very bizarre to mix single quotes and double quotes in a single language. Does Python actually mix single quotes and double quotes? >> >> >> I'm not sure what you mean by "mix". C uses single quotes and double >> quotes, right? > > > Yes, but it uses single quotes for characters (a single byte integer type) and double quotes for strings. Python doesn't really have a single character type, and lets the user use either quote mark as they see fit. Ryan finds this unfamiliar. In any case, it's hardly bizarre; it's common among interpreted languages. Other languages that allow both single- and double-quote strings include ECMAScript and Lua. Perl, PHP and Ruby also have both variants but distinguish between them for interpolation. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Wed Oct 15 21:35:29 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 16 Oct 2014 12:35:29 +1100 Subject: Python 3 is the active language, recommended for newcomers (was: Import Doesn't Import) References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> Message-ID: <85iojkyexq.fsf@benfinney.id.au> ryguy7272 writes: > So, I'm reading this link. > https://docs.python.org/2/howto/urllib2.html Note that this is the documentation for Python 2, which is obsolescent. It has had a long life, so references to Python on the web are still dominantly about that legacy version. Your confusion is quite normal. Instead, use Python 3 only (which it seems you are doing), and read the Python 3 documentation. You'll find that the ?urllib? modules are what you want. > I don't get it; I just don't get it. It's unfortunate that a lot of new Python users will be confused by this long transition. But the situation is a lot better now; more and more Python articles on the web are referring to Python 3 which is the actively-developed version, recommended for new users. -- \ ?You don't need a book of any description to help you have some | `\ kind of moral awareness.? ?Dr. Francesca Stavrakoloulou, bible | _o__) scholar, 2011-05-08 | Ben Finney From clp2 at rebertia.com Wed Oct 15 21:21:25 2014 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 15 Oct 2014 18:21:25 -0700 Subject: Import Doesn't Import In-Reply-To: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> Message-ID: On Wednesday, October 15, 2014, ryguy7272 wrote: > So sorry everyone. I've posted here several times today. This is VERY > frustrating. > > So, I'm reading this link. > https://docs.python.org/2/howto/urllib2.html > > Important note!: The "/2/" in the URL means those docs are for Python 2.x When using Python 3, ensure that the docs you're consulting have a "/3/" in them instead. > Fetching URLs > The simplest way to use urllib2 is as follows: > import urllib2 > response = urllib2.urlopen('http://python.org/') > html = response.read() > > > So, I fire up Python, and create a new file and name it and hit F5. > > All I have is thins in the file: > import urllib2 > response = urllib2.urlopen('http://python.org/') > html = response.read() > > It immediately produces this error: > Traceback (most recent call last): > File "C:/Python34/import_web_data.py", line 1, in > import urllib2 > ImportError: No module named 'urllib2' > > You're using Python 3, and the urllib2 module no longer exists in Python 3. The URL/HTTP modules got refactored on Python 3. You want the `urllib.request` module instead. Although most folks nowadays use http://docs.python-requests.org/ instead, though it's third-party and outside the std lib. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Wed Oct 15 22:21:34 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Oct 2014 22:21:34 -0400 Subject: How to debug Python IDLE? In-Reply-To: References: Message-ID: On 10/15/2014 3:36 PM, ryguy7272 wrote: Please pay attention to Mark's comment about how to avoid blank line doubling. > def showMaxFactor(num): > count = num / 2 > while count > 1: > if num % count == 0: > print 'largest factor of %d is %d' % \ > (num, count) > break > count -= 1 > else: > print num, "is prime" > for eachNum in range(10, 21): > showMaxFactor(eachNum) > > With the debugger ON, I hit F5 and get this. > 'Expected an indent block' You saw that in a Syntax Error box. > I wouldn't say that's debugging anything. Quite the opposite. Idle checks syntax before running the code since running the code would produce the same error anyway. > I can't tell what line is throwing the error, or how to fix it. When you click OK on the box, the editor window is display with the error marked in red background. In this case, that should be 'print' with red background. If you indent print and run again, you should, if running 3.x, see 'Missing parenthesis...' and another red marking. -- Terry Jan Reedy From tjreedy at udel.edu Wed Oct 15 22:43:10 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 15 Oct 2014 22:43:10 -0400 Subject: Import Doesn't Import In-Reply-To: <20f25f12-d376-4b78-9fb4-e877e2fcde15@googlegroups.com> References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> <20f25f12-d376-4b78-9fb4-e877e2fcde15@googlegroups.com> Message-ID: Perhaps you are trying too hard too fast. When I started Python, after 20 years of on and off experience with multiple languages, I went through the tutorial (on Dos, no Idle). It took about 2 hours. Then I quickly wrote the code I needed for a paid project. Do stick with 3.4.2, but use the 3.4.2 manual. On 10/15/2014 8:44 PM, ryguy7272 wrote: > Either this is the most brilliant thing ever invented, This, I think. > or it's the biggest piece of shit ever invented. Definitely not. It is possible that Python will never fit your brain. But give it a bit more of a chance. > All I know for sure, is that it doesn't do ANYTHING > that I tell it to do. Because you have told it to do things like run a program with syntax error, or import something that does not exist. I don't know of any language than does that ;-). -- Terry Jan Reedy From breamoreboy at yahoo.co.uk Thu Oct 16 04:01:49 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 16 Oct 2014 09:01:49 +0100 Subject: Import Doesn't Import In-Reply-To: <20f25f12-d376-4b78-9fb4-e877e2fcde15@googlegroups.com> References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> <20f25f12-d376-4b78-9fb4-e877e2fcde15@googlegroups.com> Message-ID: On 16/10/2014 01:44, ryguy7272 wrote: If you carry on using this approach and you continue using the buggy google groups interface you're unlikely to make many friends. May I suggest that before posting you spend a few minutes doing some research as Python has been in use for 22 years so your questions have been answered many times before. > > Either this is the most brilliant thing ever invented, or it's the biggest piece of shit ever invented. I just can't tell. All I know for sure, is that it doesn't do ANYTHING that I tell it to do. A bad workman always blames his tools. > > If there is another way of running Python code, like using Visual Studio, or a text file, or some such thing, let me know, and I'll do it. It seems like you should use Python to run Python, but my Python doesn't do anything at all. Yesterday I uninstalled Python 2.7, because that wouldn't do anything either. I'm just about ready to uninstall 3.4. > https://docs.python.org/3/using/windows.html https://docs.python.org/3/using/windows.html#launcher -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From a.h.jaffe at gmail.com Thu Oct 16 04:11:06 2014 From: a.h.jaffe at gmail.com (Andrew Jaffe) Date: Thu, 16 Oct 2014 09:11:06 +0100 Subject: Question About Running Python code In-Reply-To: References: Message-ID: On 15/10/2014 23:50, ryguy7272 wrote: > The error that I get is this. > 'invalid syntax' > > The second single quote in this line is highlighted pink. > print 'Downloading data from Yahoo for %s sector' % sector This is a script written for Python 2.*, but you say you are using Python 3.4. In Python 3, "print" is a function, not a statement, so you need to translate this to print('Downloading data from Yahoo for %s sector' % sector) From fomcl at yahoo.com Thu Oct 16 04:32:22 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 16 Oct 2014 08:32:22 +0000 (UTC) Subject: what is the easiest way to install multiple Python versions? In-Reply-To: <75b69c05-a245-48c2-a910-a3e34ac5792b@googlegroups.com> References: <75b69c05-a245-48c2-a910-a3e34ac5792b@googlegroups.com> Message-ID: <1288688676.68404.1413448342251.JavaMail.yahoo@jws10703.mail.gq1.yahoo.com> ----- Original Message ----- > From: Rustom Mody > To: python-list at python.org > Cc: > Sent: Monday, October 13, 2014 10:00 AM > Subject: Re: what is the easiest way to install multiple Python versions? > > On Monday, October 13, 2014 1:24:27 PM UTC+5:30, Chris Angelico wrote: >> On Mon, Oct 13, 2014 at 1:31 PM, Rustom Mody wrote: >> > Hearing a bit about docker nowadays. >> > Here's why its supposedly better than a VM: >> > https://www.docker.com/whatisdocker/ >> > Downsides?? No idea! > >> One obvious downside is that it doesn't allow guests to modify the OS >> at all. A VM gives you an entire OS, so you can use and manipulate >> anything. If you don't *need* all that flexibility, then a VM is >> paying an unnecessary cost, ergo Docker will have no downside. > > Was talking of more pragmatic downsides eg "Does it really work?" :-) > [Docker is still quite new] I have not used Docker before but I did look into it. Reason why I chose I full VM (Virtualbox in conjunction with Jenkins CI) is that I also needed to test Windows platforms. AFAIK, the Docker guest systems *must* be unix, possibly only Linux. A big plus of Docker is that the guest systems share resources, so it is a lot lighter to run multiple guest machines. I did hear that nowadays it is possible to use a Windows *host* system. From fomcl at yahoo.com Thu Oct 16 04:42:31 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 16 Oct 2014 08:42:31 +0000 (UTC) Subject: what is the easiest way to install multiple Python versions? In-Reply-To: References: Message-ID: <885910787.61165.1413448951311.JavaMail.yahoo@jws10777.mail.gq1.yahoo.com> ----- Original Message ----- > From: Chris Angelico > To: > Cc: Python > Sent: Sunday, October 12, 2014 4:20 PM > Subject: Re: what is the easiest way to install multiple Python versions? > > On Mon, Oct 13, 2014 at 12:33 AM, Albert-Jan Roskam > > wrote: >> *) Make altinstall >> sudo apt-get install libsqlite3-dev libbz2-dev libgdbm-dev libncurses5-dev > tk-dev zlib1g-dev >> wget https://www.python.org/ftp/python/2.6.8/Python-2.6.8.tgz >> tar -zxvf Python-2.6.8.tgz >> cd Python-2.6.8/ >> ./configure --prefix=/usr/local >> make # see 'failed stuff' below >> sudo make altinstall >> mkvirtualenv -p /usr/local/bin/python2.6 python26 # ImportError: No module > named zlib >> >> >> # Failed stuff >> Failed to find the necessary bits to build these modules: >> _bsddb _curses _curses_panel >> _hashlib _sqlite3 _ssl >> bsddb185 bz2 dbm >> dl gdbm imageop >> linuxaudiodev ossaudiodev readline >> sunaudiodev zlib > > Generally, this is the method I would recommend. For a start, run this: > > sudo apt-get build-dep python Aha, useful tip. But won't this (re)build the dependencies of the default python version? Or should I do sudo apt-get build-dep python-2.6? > This is in place of your explicit "apt-get install" command; Debian > keeps track of the dev packages needed to rebuild a given program, and > will go fetch them for you. > > After that, just look at exactly what packages you're still lacking. > You may well find that you don't have all the dependencies for all > Python modules, as some of them might not be included in a basic > "apt-get install python" installation; the solution is a bit more > "apt-get build-dep" work, or some manual hunting down of dev packages > (which may well be easier in some situations). > > But what version of Debian are you after, and why are you trying to > build a 2.6.8 from source? On Debian Wheezy, getting hold of Python > 2.6 should be as easy as: > > $ sudo apt-get install python2.6 > > I believe Squeeze ships 2.6 as its standard system Python, so it's > even easier. Are you on the unreleased Jessie? And why do you even > need 2.6 as opposed to 2.7? I am on Debian 7.6, Wheezy (Linux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.60-1+deb7u3 x86_64 GNU/Linux). Wow, so it is really this simple? This was actually the first option I considered, but I was sooooo paranoid to ruin my default Python version. Reason why I need Python 2.6? The script needs to run on a server that turned out to have Python 2.6. It is beyond my power to upgrade the Python version. Thanks all! From fomcl at yahoo.com Thu Oct 16 04:45:12 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 16 Oct 2014 08:45:12 +0000 (UTC) Subject: what is the easiest way to install multiple Python versions? In-Reply-To: References: Message-ID: <1137235905.71123.1413449112658.JavaMail.yahoo@jws10709.mail.gq1.yahoo.com> ----- Original Message ----- > From: Gayathri J > To: Albert-Jan Roskam > Cc: Python > Sent: Sunday, October 12, 2014 6:15 PM > Subject: Re: what is the easiest way to install multiple Python versions? > > I have been using Anaconda's (Continnum) conda installation for system > installation (python 2.7) and for python 3 > > conda lets us maintain diferent environments with different python and > different combinations of other packages like numpy etc... > > sure not to disappoint! Thanks! Yeah, Anaconda seams very promising. I am also curious about numba, which is part of conda IIRC. Curious how it compares to Cython. Awesome that it's possible to add a numba decorator to speed up an arbitrary function. From rosuav at gmail.com Thu Oct 16 04:48:31 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 16 Oct 2014 19:48:31 +1100 Subject: what is the easiest way to install multiple Python versions? In-Reply-To: <885910787.61165.1413448951311.JavaMail.yahoo@jws10777.mail.gq1.yahoo.com> References: <885910787.61165.1413448951311.JavaMail.yahoo@jws10777.mail.gq1.yahoo.com> Message-ID: On Thu, Oct 16, 2014 at 7:42 PM, Albert-Jan Roskam wrote: > >> From: Chris Angelico >> Generally, this is the method I would recommend. For a start, run this: >> >> sudo apt-get build-dep python > > Aha, useful tip. But won't this (re)build the dependencies of the default python version? > Or should I do sudo apt-get build-dep python-2.6? It would install (not usually build) all the dependencies of the default Python, yes; but if you're compiling from source, that's usually going to be fairly close. For instance, if you want to build Python 3.5 from Mercurial, the easiest way to get started would be "apt-get build-dep python3"; that might not get absolutely everything, but it's sure going to be close. Python's dependencies don't change hugely between minor versions. >> But what version of Debian are you after, and why are you trying to >> build a 2.6.8 from source? On Debian Wheezy, getting hold of Python >> 2.6 should be as easy as: >> >> $ sudo apt-get install python2.6 > > I am on Debian 7.6, Wheezy (Linux debian 3.2.0-4-amd64 #1 SMP Debian 3.2.60-1+deb7u3 x86_64 GNU/Linux). Wow, so it is really this simple? This was actually the first option I considered, but I was sooooo paranoid to ruin my default Python version. > I'm fairly sure - though you could easily confirm - that installing the python2.6 package won't fiddle with the name "python", nor the name "python2", but will simply add another name "python2.6". I have it installed on my main Wheezy system, and that's how it is. Not sure if there's a way to tweak that with update-alternatives or anything. > Reason why I need Python 2.6? The script needs to run on a server that turned out to have Python 2.6. It is beyond my power to upgrade the Python version. > > Thanks all! Fair enough. The differences between 2.6 and 2.7 aren't great, though, so you may well be able to port it trivially. But in any case, so long as you have Wheezy, you should be able to run 2.6 the easy way. ChrisA From fomcl at yahoo.com Thu Oct 16 04:47:43 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 16 Oct 2014 08:47:43 +0000 (UTC) Subject: what is the easiest way to install multiple Python versions? In-Reply-To: References: Message-ID: <1767818742.65804.1413449263512.JavaMail.yahoo@jws10735.mail.gq1.yahoo.com> ----- Original Message ----- > From: Terry Reedy > To: python-list at python.org > Cc: > Sent: Monday, October 13, 2014 2:54 AM > Subject: Re: what is the easiest way to install multiple Python versions? > > On 10/12/2014 9:33 AM, Albert-Jan Roskam wrote: > > >> A few days ago I needed to check whether some Python code ran with >> Python 2.6. What is the easiest way to install another Python version >> along side the default Python version? My own computer is Debian >> Linux 64 bit, but a platform-independent solution would be best. > > Installation is platform dependent. On Windows, the answer would simply > be 'get the PSF x.y installer and run it'. Thank you. Yes, for Windows it is easy. I was just scared that I would accidentally replace my default Python version 2.7 with 2.6 --and ruin my system. From shivaji_tn at yahoo.com Thu Oct 16 06:20:59 2014 From: shivaji_tn at yahoo.com (Shiva) Date: Thu, 16 Oct 2014 10:20:59 +0000 (UTC) Subject: Creating a counter References: <543ED333.6060102@islandtraining.com> Message-ID: > > Python3: > print(counter, end='\r') > > Gary Herron > > Thanks, that is what I was looking up - \r carriage return without linefeed. Thanks again! Shiva From fomcl at yahoo.com Thu Oct 16 08:31:29 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 16 Oct 2014 12:31:29 +0000 (UTC) Subject: what is the easiest way to install multiple Python versions? In-Reply-To: References: Message-ID: <219536496.81828.1413462689661.JavaMail.yahoo@jws10745.mail.gq1.yahoo.com> ----- Original Message ----- > From: Chris Angelico > To: > Cc: Python > Sent: Thursday, October 16, 2014 10:48 AM > Subject: Re: what is the easiest way to install multiple Python versions? > > On Thu, Oct 16, 2014 at 7:42 PM, Albert-Jan Roskam > The differences between 2.6 and 2.7 aren't great, though, > so you may well be able to port it trivially. But in any case, so long > as you have Wheezy, you should be able to run 2.6 the easy way. Most things were indeed easy to solve. But this one surprised me. With Python 2.6, I need to outcomment the 'lambda' line. The error is what I get in Python 2.6. It does not matter if I do u"\n".join(het_logboek[i:]). I don't use latin-1 anywhere in my program. I need to convert unicode to bytes in Python 2.6, or else it chokes in the smart quote. import codecs import os import time def print_log_van_vandaag(logbestand): """Print today's log. The Cron Daemon will mail this""" vandaag = time.strftime("%Y-%m-%d") with codecs.open(logbestand, encoding="utf-8") as logboek: het_logboek = logboek.readlines() #het_logboek = map(lambda x: x.encode("utf-8"), het_logboek) # bug in Python 2.6? for i, regel in enumerate(het_logboek): if regel.startswith(vandaag): print os.linesep.join(het_logboek[i:]) break Traceback (most recent call last): File "mailer.py", line 410, in print_log_van_vandaag("mailer.log") File "mailer.py", line 399, in print_log_van_vandaag print os.linesep.join(het_logboek[i:]) UnicodeEncodeError: 'latin-1' codec can't encode character u'\u2018' in position 10214: ordinal not in range(256) From rustompmody at gmail.com Thu Oct 16 09:29:03 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 16 Oct 2014 06:29:03 -0700 (PDT) Subject: python3 on mac-mavericks (was trying idle) In-Reply-To: References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Message-ID: On Thursday, October 9, 2014 2:56:56 PM UTC+5:30, Terry Reedy wrote: > One may have to install activestate tkc/tk on mac, depending on osx > version. This page has details: > https://www.python.org/download/mac/tcltk Ok Ive some more information: The people in the audience using macs are using mavericks Whats the best way to setup python3 for that? I remember seeing some two different repos (if that what they are called in mac-land) for python. With some different tradeoffs which I dont understand. Another related question for mac-python usage: I asked one of the mac-users: Please start your default python in a shell and tell me what version it is. Answer: Mac has no shell. I find this hard to believe. Is a shell called something else in mac-maverick?? Where/how to find it? From sffjunkie at gmail.com Thu Oct 16 09:44:09 2014 From: sffjunkie at gmail.com (Simon Kennedy) Date: Thu, 16 Oct 2014 06:44:09 -0700 (PDT) Subject: Creating a counter In-Reply-To: References: Message-ID: <7490ed54-3116-45da-85d1-f9ce4bf29c5e@googlegroups.com> On Wednesday, 15 October 2014 19:39:43 UTC+1, Shiva wrote: > I am trying to search a string through files in a directory - however while > Python script works on it and writes a log - I want to present the user with > count of number of strings found. So it should increment for each string found. You may ignore the following if you are just starting out on your Python learning odyssey but if you're past the early stages and looking to try something different then read on. When you looked through the other answers and found a solution you're happy with that does not use the standard library you can look through the documentation and find a stdlib (https://docs.python.org/2.7/library/index.html) provided way that may be slightly more elegant for counting strings. Something like the following :: >>> from collections import defaultdict >>> counter = defaultdict(int) >>> counter['string1'] += 1 >>> counter['string2'] += 1 >>> counter['string1'] += 1 >>> print('Count string1={string1}, string2={string2}'.format(**counter), end='\r') Count string1=2, string2=1 https://docs.python.org/3/library/collections.html#collections.defaultdict In the above code defaultdict is like a dictionary but if a key is not found then it uses the `int` factory parameter to add a value that is an integer with a value of 0 (which is what executing ``int()`` returns if you do it in the interactive Python prompt) for the dictionary key you're trying to access. or :: >>> from collections import Counter >>> counter = Counter() >>> s = 'string1 string2 string1' >>> s.split() ['string1', 'string2', 'string1'] >>> counter.update(s.split()) >>> print('Count string1={string1}, string2={string2}'.format(**counter), end='\r') Count string1=2, string2=1 https://docs.python.org/2.7/library/collections.html#collections.Counter From python at mrabarnett.plus.com Thu Oct 16 10:04:43 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 16 Oct 2014 15:04:43 +0100 Subject: python3 on mac-mavericks (was trying idle) In-Reply-To: References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> Message-ID: <543FD07B.3050204@mrabarnett.plus.com> On 2014-10-16 14:29, Rustom Mody wrote: > On Thursday, October 9, 2014 2:56:56 PM UTC+5:30, Terry Reedy wrote: > >> One may have to install activestate tkc/tk on mac, depending on osx >> version. This page has details: >> https://www.python.org/download/mac/tcltk > > Ok Ive some more information: > The people in the audience using macs are using mavericks > > Whats the best way to setup python3 for that? > > I remember seeing some two different repos (if that what they are called > in mac-land) for python. With some different tradeoffs which I dont understand. > > Another related question for mac-python usage: > > I asked one of the mac-users: > Please start your default python in a shell and tell me what version it is. > > Answer: Mac has no shell. > > I find this hard to believe. Is a shell called something else > in mac-maverick?? Where/how to find it? > In Macland it's called the terminal emulator: http://en.wikipedia.org/wiki/Terminal_%28OS_X%29 From ian.g.kelly at gmail.com Thu Oct 16 10:04:25 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 16 Oct 2014 08:04:25 -0600 Subject: Creating a counter In-Reply-To: <7490ed54-3116-45da-85d1-f9ce4bf29c5e@googlegroups.com> References: <7490ed54-3116-45da-85d1-f9ce4bf29c5e@googlegroups.com> Message-ID: On Thu, Oct 16, 2014 at 7:44 AM, Simon Kennedy wrote: > When you looked through the other answers and found a solution you're happy with that does not use the standard library you can look through the documentation and find a stdlib (https://docs.python.org/2.7/library/index.html) provided way that may be slightly more elegant for counting strings. I would have suggested a Counter if I thought it fit the OP's use case. If you're listing directory contents, you're not going to have any repeated strings, so all the counts will be 1, and your Counter might as well be a list, which is what you got from calling os.listdir() in the first place. So I was more inclined to think that the OP was only trying to count one thing. In any case, the question turned out to actually be about printing, not counting. From sffjunkie at gmail.com Thu Oct 16 10:08:51 2014 From: sffjunkie at gmail.com (Simon Kennedy) Date: Thu, 16 Oct 2014 07:08:51 -0700 (PDT) Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On Wednesday, 15 October 2014 20:31:15 UTC+1, Ian wrote: > I agree. I very rarely use blank lines inside functions. As I see it, > if you feel you need a blank line for separation within a function, > that's an indication your function is overly complex and should be > broken up. Whereas I feel that if I wanted to write code which looked like that I'd have learnt/learned Perl ;-) Each to their own. From sffjunkie at gmail.com Thu Oct 16 10:12:07 2014 From: sffjunkie at gmail.com (Simon Kennedy) Date: Thu, 16 Oct 2014 07:12:07 -0700 (PDT) Subject: Creating a counter In-Reply-To: References: <7490ed54-3116-45da-85d1-f9ce4bf29c5e@googlegroups.com> Message-ID: <6bb7675c-e821-4a10-84c2-582197afd237@googlegroups.com> On Thursday, 16 October 2014 15:05:47 UTC+1, Ian wrote: > I would have suggested a Counter if I thought it fit the OP's use > case. If you're listing directory contents, you're not going to have > any repeated strings, so all the counts will be 1, and your Counter > might as well be a list, which is what you got from calling > os.listdir() in the first place. So I was more inclined to think that > the OP was only trying to count one thing. I read the OP's question as he was looking for the string in the contents of each file in the directory not in the file names themselves but as you say... > In any case, the question turned out to actually be about printing, > not counting. From rosuav at gmail.com Thu Oct 16 10:59:32 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 17 Oct 2014 01:59:32 +1100 Subject: what is the easiest way to install multiple Python versions? In-Reply-To: <219536496.81828.1413462689661.JavaMail.yahoo@jws10745.mail.gq1.yahoo.com> References: <219536496.81828.1413462689661.JavaMail.yahoo@jws10745.mail.gq1.yahoo.com> Message-ID: On Thu, Oct 16, 2014 at 11:31 PM, Albert-Jan Roskam wrote: > Most things were indeed easy to solve. But this one surprised me. With Python 2.6, I need to outcomment the 'lambda' line. The error is what I get in Python 2.6. It does not matter if I do u"\n".join(het_logboek[i:]). I don't use latin-1 anywhere in my program. I need to convert unicode to bytes in Python 2.6, or else it chokes in the smart quote. > Hmm, that looks like a configuration difference between the two, rather than a major breaking difference. It'll depend on the console settings; if you're running 2.6 from cron, but 2.7 from the console (or the other way around), you'll see stuff like this break. It's also possible that a bug was discovered, of course, but what exactly the bug is, I can't say. The error you're seeing is perfectly correct: you have Unicode character U+2018 (a curly quote) in your stream, and the print statement is trying to send that to a Latin-1 output, and that's not going to work. The question is, why is your console believed to be set to Latin-1? And if encoding UTF-8 works, then there's something very VERY wrong. (Unless by "works" you just mean "doesn't throw an error", and the UTF-8 bytes are being interpreted as Latin-1 bytes.) ChrisA From rosuav at gmail.com Thu Oct 16 11:02:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 17 Oct 2014 02:02:18 +1100 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: On Fri, Oct 17, 2014 at 1:08 AM, Simon Kennedy wrote: > On Wednesday, 15 October 2014 20:31:15 UTC+1, Ian wrote: >> I agree. I very rarely use blank lines inside functions. As I see it, >> if you feel you need a blank line for separation within a function, >> that's an indication your function is overly complex and should be >> broken up. > > Whereas I feel that if I wanted to write code which looked like that I'd have learnt/learned Perl ;-) I did learn Perl. That's why I now code in Python. ChrisA From rosuav at gmail.com Thu Oct 16 11:23:34 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 17 Oct 2014 02:23:34 +1100 Subject: python3 on mac-mavericks (was trying idle) In-Reply-To: <543FD07B.3050204@mrabarnett.plus.com> References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> <543FD07B.3050204@mrabarnett.plus.com> Message-ID: On Fri, Oct 17, 2014 at 1:04 AM, MRAB wrote: > In Macland it's called the terminal emulator: > > http://en.wikipedia.org/wiki/Terminal_%28OS_X%29 To be strictly correct, the "shell" would be the thing you run that gives you a prompt, and the "terminal emulator" would be the thing you run that gives you a black box on your GUI. On my Linux box here (Debian Wheezy with Xfce), I use xfce4-terminal as my terminal emulator, and bash as my shell. You could alternatively use gnome-terminal, or you could use csh for your shell, or whatever strikes your fancy. Macs are no different here; they have a terminal emulator (which is usually just called "Terminal" aiui), and a shell (usually bash, though not quite the bash I know from my systems - maybe a different version). It's Windows that is the oddball. You can't easily find the terminal emulator, though it does have one. People think of "running cmd.exe" to get a "shell", which in reality is both a terminal and a shell inside that terminal. But ultimately, it's still the same. ChrisA From invalid at invalid.invalid Thu Oct 16 12:23:55 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Thu, 16 Oct 2014 16:23:55 +0000 (UTC) Subject: python3 on mac-mavericks (was trying idle) References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> <543FD07B.3050204@mrabarnett.plus.com> Message-ID: On 2014-10-16, Chris Angelico wrote: > On Fri, Oct 17, 2014 at 1:04 AM, MRAB wrote: >> In Macland it's called the terminal emulator: >> >> http://en.wikipedia.org/wiki/Terminal_%28OS_X%29 > > To be strictly correct, the "shell" would be the thing you run that > gives you a prompt, and the "terminal emulator" would be the thing > you run that gives you a black box on your GUI. Infidel! The correct color for an empty terminal box is _white_. You probably eat your soft-boiled eggs from the wrong end too. ;) -- Grant Edwards grant.b.edwards Yow! Everybody is going at somewhere!! It's probably gmail.com a garage sale or a disaster Movie!! From rosuav at gmail.com Thu Oct 16 12:33:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 17 Oct 2014 03:33:36 +1100 Subject: python3 on mac-mavericks (was trying idle) In-Reply-To: References: <86ae9246-1b3f-427b-921f-10b8b416e507@googlegroups.com> <543FD07B.3050204@mrabarnett.plus.com> Message-ID: On Fri, Oct 17, 2014 at 3:23 AM, Grant Edwards wrote: > On 2014-10-16, Chris Angelico wrote: >> On Fri, Oct 17, 2014 at 1:04 AM, MRAB wrote: >>> In Macland it's called the terminal emulator: >>> >>> http://en.wikipedia.org/wiki/Terminal_%28OS_X%29 >> >> To be strictly correct, the "shell" would be the thing you run that >> gives you a prompt, and the "terminal emulator" would be the thing >> you run that gives you a black box on your GUI. > > Infidel! The correct color for an empty terminal box is _white_. > > You probably eat your soft-boiled eggs from the wrong end too. > I probably do! Though I haven't yet figured out how to eat them from the inside. ChrisA From dyoo at hashcollision.org Thu Oct 16 14:14:22 2014 From: dyoo at hashcollision.org (Danny Yoo) Date: Thu, 16 Oct 2014 11:14:22 -0700 Subject: [Tutor] Convert Qstring to string in windows In-Reply-To: <969535236.13984943.1413472898089.JavaMail.zimbra@estudiantes.uci.cu> References: <1549164247.13980291.1413472329833.JavaMail.zimbra@estudiantes.uci.cu> <969535236.13984943.1413472898089.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On Thu, Oct 16, 2014 at 8:21 AM, C at rlos wrote: > > I have been tryed to convert a Qstring text to string on python, in linux > that work fine but in windows when qstring contine ?,?,?,?,? the converted > text is not correct, contine extranger characters, > this qstring text is an url from qdialogtext. > > in linux i do for this way: > pythonstringtext=qstringtext.text().toUtf8.data() > and it return a python string correctly. Hi Carlos, This seems like a question that's very specific to Qt: you may want to ask on a Qt-Python mailing list. Tutor is intended for beginner programmers, and the question you're asking seems a bit specialized for the intended audience. In absence of this information, I have to make a few guesses. My best guesses so far are that you're working with Qt, which provides its own Unicode string class: http://qt-project.org/doc/qt-4.8/qstring.html Are you using PyQt 4 or PyQt 5, or something else entirely? Are you using Python 2 or Python 3? According to the PyQt5 documentation, it automatically handles the string conversion: http://pyqt.sourceforge.net/Docs/PyQt5/gotchas.html#python-strings-qt-strings-and-unicode and according to the PyQt 4 documentation, it also handles the conversion automatically for you: http://pyqt.sourceforge.net/Docs/PyQt4/python_v3.html#qstring and because the mapping is done by the library, you should not have to be doing anything on your own end to convert Qstrings to Python strings. Yeah, I am not sure what you are doing yet, because the documentation says that it handles conversions for you. The fact that you're doing this manually suggests that you might be doing something unusual. We need more information. But I think you may get better help on a Qt-specific mailing list; I suspect very few of us here have Qt experience. From a24061 at ducksburg.com Thu Oct 16 15:29:46 2014 From: a24061 at ducksburg.com (Adam Funk) Date: Thu, 16 Oct 2014 20:29:46 +0100 Subject: Permissions on files installed by pip? Message-ID: I've been using the python-nltk package on Ubuntu, but I need ntlk 3.0 now. I used 'sudo aptitude purge python-nltk' to get rid of my existing installation, & followed instructions on the nltk website [1] starting at step 4 (since I already have python-pip & python-numpy packages installed). $ sudo pip install -U I couldn't get it to work, until I realized that the permissions & ownership on /usr/local/lib/python2.7/dist-packages were 'drwx--S--- root staff'. A 'chmod -R a+rX' on that directory seems to have fixed it. Is it normal for sudo pip install to set the permissions that way, or did I do something wrong? [1] http://www.nltk.org/install.html -- Master Foo once said to a visiting programmer: "There is more Unix-nature in one line of shell script than there is in ten thousand lines of C." --- Eric Raymond From alan.gauld at btinternet.com Thu Oct 16 16:59:06 2014 From: alan.gauld at btinternet.com (Alan Gauld) Date: Thu, 16 Oct 2014 21:59:06 +0100 Subject: [Tutor] Convert Qstring to string in windows In-Reply-To: References: <1549164247.13980291.1413472329833.JavaMail.zimbra@estudiantes.uci.cu> <969535236.13984943.1413472898089.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On 16/10/14 19:14, Danny Yoo wrote: > need more information. But I think you may get better help on a > Qt-specific mailing list; I suspect very few of us here have Qt > experience. There are at least 2 Python Qt mailing lists and also two for Side which is Nokia's public domain fork of Qt. That's probably worth a look too. Definitely in the minority interest camp on the tutor list. hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.flickr.com/photos/alangauldphotos From fomcl at yahoo.com Thu Oct 16 17:08:45 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Thu, 16 Oct 2014 14:08:45 -0700 Subject: [Tutor] Convert Qstring to string in windows Message-ID: <1413493725.22928.BPMail_high_carrier@web163805.mail.gq1.yahoo.com> ----------------------------- On Thu, Oct 16, 2014 10:59 PM CEST Alan Gauld wrote: >On 16/10/14 19:14, Danny Yoo wrote: > >> need more information. But I think you may get better help on a >> Qt-specific mailing list; I suspect very few of us here have Qt >> experience. > >There are at least 2 Python Qt mailing lists and also two for >Side which is Nokia's public domain fork of Qt. That's probably >worth a look too. > >Definitely in the minority interest camp on the tutor list. > I am not 100 % sure but I think you can use str() on a qstring. In other words, it has its own __str__ method. From emile at fenx.com Thu Oct 16 17:29:14 2014 From: emile at fenx.com (Emile van Sebille) Date: Thu, 16 Oct 2014 14:29:14 -0700 Subject: Import Doesn't Import In-Reply-To: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> Message-ID: On 10/15/2014 5:40 PM, ryguy7272 wrote: > ImportError: No module named 'urllib2' > I'm telling Python to import because it doesn't exist and it throws an error. I don't get it; I just don't get it. If I'm working with R, I can import thousands of libraries with no errors whatsoever. With Python, I just get thousands of errors with nothing working whatsoever. I totally don't understand this language. Import means import. Right. WTF!!!!! So, maybe Import doesn't mean import -- perhaps you expect import to retrieve content from the web and make it importable(1). That's not what python's import does. Python's version looks for a local module to import. I'd suggest starting with the tutorial. Emile (1) which would imply execution of arbitrary code. From noblebell at gmail.com Thu Oct 16 17:54:07 2014 From: noblebell at gmail.com (Noble Bell) Date: Thu, 16 Oct 2014 14:54:07 -0700 (PDT) Subject: Detecting user's installed Python/Tkinter packages during install of app Message-ID: I am thinking of writing a new mac and/or windows application using python 3.x and the tkinter gui toolkit. A question that I have is this.. If my application uses a version of python/tkinter that is not on the users computer will I be able to detect that during an install and automatically install the proper files silently? Thanks in advance.. Noble From skip.montanaro at gmail.com Thu Oct 16 18:14:23 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Thu, 16 Oct 2014 17:14:23 -0500 Subject: Detecting user's installed Python/Tkinter packages during install of app In-Reply-To: References: Message-ID: On Thu, Oct 16, 2014 at 4:54 PM, Noble Bell wrote: > If my application uses a version of python/tkinter that is not on the users computer will I be able to detect that during an install and automatically install the proper files silently? You mean, like this? % python -c 'import _tkinter ; print _tkinter.TCL_VERSION' 8.5 Skip From cs at zip.com.au Thu Oct 16 17:48:27 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 17 Oct 2014 08:48:27 +1100 Subject: python3 on mac-mavericks (was trying idle) In-Reply-To: References: Message-ID: <20141016214827.GA14237@cskk.homeip.net> On 16Oct2014 06:29, rusi wrote: >On Thursday, October 9, 2014 2:56:56 PM UTC+5:30, Terry Reedy wrote: >> One may have to install activestate tkc/tk on mac, depending on osx >> version. This page has details: >> https://www.python.org/download/mac/tcltk > >Ok Ive some more information: >The people in the audience using macs are using mavericks > >Whats the best way to setup python3 for that? > >I remember seeing some two different repos (if that what they are called >in mac-land) for python. With some different tradeoffs which I dont understand. I use MacPorts. Also popular are Brew and Fink. You can even use them all at once; they install to separate trees. My Python 3 comes from MacPorts. >Another related question for mac-python usage: >I asked one of the mac-users: >Please start your default python in a shell and tell me what version it is. >Answer: Mac has no shell. > >I find this hard to believe. Is a shell called something else >in mac-maverick?? Where/how to find it? As pointed out elsewhere, OSX ships with "Terminal" as a terminal emutator. Another popular terminal emulator is iTerm2, which is what I prefer. You can run X11 also, and use any of the many terminal emulators that run in it, though the experience is clunkier. As far as shells go, OSX ships with /bin/sh, /bin/bash and /bin/zsh. Or for the perverse, /bin/csh and /bin/tcsh (it is, after all, a BSD derived OS). I use zsh, getting my copy from MacPorts instead of OSX's native one. So it is a perfectly normal UNIX system in this regard. Cheers, Cameron Simpson No electrons were harmed in the production of this message. - Dr. P. Gensheimer From joel.goldstick at gmail.com Thu Oct 16 18:28:26 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 16 Oct 2014 18:28:26 -0400 Subject: Import Doesn't Import In-Reply-To: References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> Message-ID: On Thu, Oct 16, 2014 at 5:29 PM, Emile van Sebille wrote: > On 10/15/2014 5:40 PM, ryguy7272 wrote: >> >> ImportError: No module named 'urllib2' >> I'm telling Python to import because it doesn't exist and it throws an >> error. I don't get it; I just don't get it. If I'm working with R, I can >> import thousands of libraries with no errors whatsoever. With Python, I >> just get thousands of errors with nothing working whatsoever. I totally >> don't understand this language. Import means import. Right. WTF!!!!! > > > So, maybe Import doesn't mean import -- perhaps you expect import to > retrieve content from the web and make it importable(1). That's not what > python's import does. Python's version looks for a local module to import. > > I'd suggest starting with the tutorial. > > Emile > > > (1) which would imply execution of arbitrary code. > > -- > https://mail.python.org/mailman/listinfo/python-list requests is a better choice than urllib -- Joel Goldstick http://joelgoldstick.com From breamoreboy at yahoo.co.uk Thu Oct 16 18:56:03 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 16 Oct 2014 23:56:03 +0100 Subject: Import Doesn't Import In-Reply-To: References: <1a3844da-b467-43ba-b34f-3aaa6442d799@googlegroups.com> Message-ID: On 16/10/2014 23:28, Joel Goldstick wrote: > On Thu, Oct 16, 2014 at 5:29 PM, Emile van Sebille wrote: >> On 10/15/2014 5:40 PM, ryguy7272 wrote: >>> >>> ImportError: No module named 'urllib2' >>> I'm telling Python to import because it doesn't exist and it throws an >>> error. I don't get it; I just don't get it. If I'm working with R, I can >>> import thousands of libraries with no errors whatsoever. With Python, I >>> just get thousands of errors with nothing working whatsoever. I totally >>> don't understand this language. Import means import. Right. WTF!!!!! >> >> >> So, maybe Import doesn't mean import -- perhaps you expect import to >> retrieve content from the web and make it importable(1). That's not what >> python's import does. Python's version looks for a local module to import. >> >> I'd suggest starting with the tutorial. >> >> Emile >> >> >> (1) which would imply execution of arbitrary code. >> >> -- >> https://mail.python.org/mailman/listinfo/python-list > > requests is a better choice than urllib > To an experienced user yes, to an inexperienced OP who can't even run a Python program without help a very emphatic no. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rustompmody at gmail.com Thu Oct 16 21:08:36 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 16 Oct 2014 18:08:36 -0700 (PDT) Subject: python3 on mac-mavericks (was trying idle) In-Reply-To: References: Message-ID: <7de9a2e4-9655-494d-8cd8-1c9d5517c4b7@googlegroups.com> On Friday, October 17, 2014 3:48:20 AM UTC+5:30, Cameron Simpson wrote: > On 16Oct2014 06:29, rusi wrote: > >On Thursday, October 9, 2014 2:56:56 PM UTC+5:30, Terry Reedy wrote: > >> One may have to install activestate tkc/tk on mac, depending on osx > >> version. This page has details: > >> https://www.python.org/download/mac/tcltk > >Ok Ive some more information: > >The people in the audience using macs are using mavericks > >Whats the best way to setup python3 for that? > >I remember seeing some two different repos (if that what they are called > >in mac-land) for python. With some different tradeoffs which I dont understand. > I use MacPorts. Also popular are Brew and Fink. You can even use them all at > once; they install to separate trees. Ok and is the MacPorts python3 one monolithic package or a bunch of separate ones (like debian/ubuntu) for core-python, tkinter, idle etc? From rustompmody at gmail.com Thu Oct 16 21:24:19 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 16 Oct 2014 18:24:19 -0700 (PDT) Subject: Keepin constants, configuration values, etc. in Python - dedicated module or what? In-Reply-To: References: <54hqfb-nan.ln1@chris.zbmc.eu> <36d7ddca-29f4-403c-a64d-611e187afc3a@googlegroups.com> Message-ID: <58b174c7-276f-40a5-9628-2402c859dff4@googlegroups.com> On Tuesday, September 30, 2014 10:09:52 PM UTC+5:30, Rustom Mody wrote: > On Tuesday, September 30, 2014 8:48:15 PM UTC+5:30, c... at isbd.net wrote: > > Rustom Mody wrote: > > > On Tuesday, September 30, 2014 5:18:31 PM UTC+5:30, Chris wrote: > > > > I would actually > > > > quite like to keep the configuration data separate from the code as it > > > > would simplify using the data at the 'home' end of things as I'd just > > > > need to copy the configuration file across. This was why the database > > > > approach appealed at first as all I need to do is copy the database > > > > and everything is in there. > > > Of course > > > > Are there any better ways of doing this? E.g. some sort of standard > > > > configuration file format that Python knows about? > > > Umm this is getting to be a FAQ... > > > Maybe it should go up somewhere? > > > Yes there are dozens: > > > - ini > > > - csv > > > - json > > > - yml > > > - xml > > > - pickle > > > - And any DBMS of your choice > > > I guess Ive forgotten as many as Ive listed!! > > Yes, I know, I've found most of those. I'm really asking for help in > > choosing which to use. I think I can reject some quite quickly:- > > xml - horrible, nasty to edit, etc. I don't like XML! :-) > Heh! Youve proved yourself a pythonista! > > ini - doesn't work so well with lists/dictionaries (though possible) > > csv - rather difficult to edit > Have you tried with comma=tab? > > yml - front runner if I go for configuration files > Yeah my favorite as well > > json - one of the most likely possibilities, but prefer yml > Seems to be most popular nowadays -- maybe related to being almost yaml > and in the standard lib > > pickle - not user editable as I understand it > Well not in any reasonably pleasant way! > > What I'm really asking for is how to choose between:- > > python - just keep config in the modules/classes, not easy to use > > at 'both ends' (home and remote), otherwise quite simple > Can work at a trivial level. > As soon as things get a bit larger data and code mixed up is a recipe for mess up. Just came across this https://github.com/henriquebastos/python-decouple/ From noblebell at gmail.com Thu Oct 16 21:38:07 2014 From: noblebell at gmail.com (Noble Bell) Date: Thu, 16 Oct 2014 18:38:07 -0700 (PDT) Subject: Detecting user's installed Python/Tkinter packages during install of app In-Reply-To: References: Message-ID: <0634a3e6-b6c4-4be2-95e7-5e1418ac8997@googlegroups.com> On Thursday, October 16, 2014 5:14:44 PM UTC-5, Skip Montanaro wrote: > On Thu, Oct 16, 2014 at 4:54 PM, Noble Bell wrote: > > > If my application uses a version of python/tkinter that is not on the users computer will I be able to detect that during an install and automatically install the proper files silently? > > > > You mean, like this? > > > > % python -c 'import _tkinter ; print _tkinter.TCL_VERSION' > > 8.5 > > > > Skip Not exactly. I mean when a end user is installing my application can the installer detect the presence of the correct version of python and tkinter and if they are not present have the installer silently install them to the users machine. NB From greg.ewing at canterbury.ac.nz Fri Oct 17 01:22:29 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Fri, 17 Oct 2014 18:22:29 +1300 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: > On 16/10/2014 12:32 AM, Chris ?Kwpolska? Warrick wrote: >> Why? Because things like `print 'done'` usually have an empty line >> before it: Not in my code, they don't. I never put blank lines inside functions. -- Greg From cs at zip.com.au Fri Oct 17 01:03:11 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 17 Oct 2014 16:03:11 +1100 Subject: python3 on mac-mavericks (was trying idle) In-Reply-To: <7de9a2e4-9655-494d-8cd8-1c9d5517c4b7@googlegroups.com> References: <7de9a2e4-9655-494d-8cd8-1c9d5517c4b7@googlegroups.com> Message-ID: <20141017050311.GA35127@cskk.homeip.net> On 16Oct2014 18:08, rusi wrote: >On Friday, October 17, 2014 3:48:20 AM UTC+5:30, Cameron Simpson wrote: >> On 16Oct2014 06:29, rusi wrote: >> >On Thursday, October 9, 2014 2:56:56 PM UTC+5:30, Terry Reedy wrote: >> >> One may have to install activestate tkc/tk on mac, depending on osx >> >> version. This page has details: >> >> https://www.python.org/download/mac/tcltk >> >Ok Ive some more information: >> >The people in the audience using macs are using mavericks >> >Whats the best way to setup python3 for that? >> >I remember seeing some two different repos (if that what they are called >> >in mac-land) for python. With some different tradeoffs which I dont understand. > >> I use MacPorts. Also popular are Brew and Fink. You can even use them all at >> once; they install to separate trees. > >Ok and is the MacPorts python3 one monolithic package or a bunch of separate >ones (like debian/ubuntu) for core-python, tkinter, idle etc? It is one package. (You can install distinct packages for python 3.2, 3.3, 3.4 ... and select which one is default.) That gets you Python and the stdlib. There's a whole suite of extra packages for various third party libraries. And of course the user can use pip and/or virtualenv to arrange things on their own, also. Cheers, Cameron Simpson People are paid for coming in the morning and leaving at night, and for saying "Good morning" in the morning and "Good afternoon" in the afternoon and never confusing the two. - Albert Shanker, president of the American Federation of Teachers From dhananjay.c.joshi at gmail.com Fri Oct 17 02:28:13 2014 From: dhananjay.c.joshi at gmail.com (Dhananjay) Date: Fri, 17 Oct 2014 14:28:13 +0800 Subject: 2d color-bar map plot Message-ID: Dear all, I am bit new to the python/pyplot. This might be simple, but I guess I am missing something here. I have data file as follows: 2.1576318858 -1.8651195165 4.2333428278 2.1681875208 -1.9229968780 4.1989176884 2.3387636157 -2.0376253255 2.4460899122 2.1696565965 -2.6186941271 4.4172007912 2.0848862071 -2.1708981985 3.3404520962 2.0824347942 -1.9142798955 3.3629290206 2.0281685821 -1.8103363482 2.5446721669 2.3309993378 -1.8721153619 2.7006893016 2.0957461483 -1.5379071451 4.5228264441 2.2761376261 -2.5935979811 3.9231744717 . . . (total of 200 lines) Columns 1,2,3 corresponds to x,y,z axis data points. This is not a continuous data. I wish to make a plot as a 2D with 3rd dimension (i.e z-axis data) as a color map with color bar on right hand side. As a beginner, I tried to follow tutorial with some modification as follows: http://matplotlib.org/examples/pylab_examples/tricontour_vs_griddata.html # Read data from file: fl1 = open('flooding-psiphi.dat','r').readlines() xs = ys = zs = [] for line in fl1: line = line.split() xs.append(float(line[0])) ys.append(float(line[1])) zs.append(float(line[2])) print xs[0], ys[0], zs[0] xi = np.mgrid[-5.0:5.0:200j] yi = np.mgrid[-5.0:5.0:200j] zi = griddata((x, y), z, (xi, yi), method='cubic') plt.subplot(221) plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k') plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow, norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) plt.colorbar() # draw colorbar plt.plot(x, y, 'ko', ms=3) plt.xlim(-5, 5) plt.ylim(-5, 5) plt.title('griddata and contour (%d points, %d grid points)' % (npts, ngridx*ngridy)) #print ('griddata and contour seconds: %f' % (time.clock() - start)) plt.gcf().set_size_inches(6, 6) plt.show() However, I failed and getting long error as follows: QH6154 qhull precision error: initial facet 1 is coplanar with the interior point ERRONEOUS FACET: - f1 - flags: bottom simplicial upperDelaunay flipped - normal: 0.7071 -0.7071 0 - offset: -0 - vertices: p600(v2) p452(v1) p304(v0) - neighboring facets: f2 f3 f4 While executing: | qhull d Qz Qbb Qt Options selected for Qhull 2010.1 2010/01/14: run-id 1531309415 delaunay Qz-infinity-point Qbbound-last Qtriangulate _pre-merge _zero-centrum Pgood _max-width 8.8 Error-roundoff 1.2e-14 _one-merge 8.6e-14 _near-inside 4.3e-13 Visible-distance 2.5e-14 U-coplanar-distance 2.5e-14 Width-outside 4.9e-14 _wide-facet 1.5e-13 precision problems (corrected unless 'Q0' or an error) 2 flipped facets The input to qhull appears to be less than 3 dimensional, or a computation has overflowed. Qhull could not construct a clearly convex simplex from points: - p228(v3): 2.4 2.4 1.4 - p600(v2): 1.4 1.4 8.8 - p452(v1): 5.7 5.7 8 - p304(v0): -3.1 -3.1 2.4 The center point is coplanar with a facet, or a vertex is coplanar with a neighboring facet. The maximum round off error for computing distances is 1.2e-14. The center point, facets and distances to the center point are as follows: center point 1.595 1.595 5.173 facet p600 p452 p304 distance= 0 facet p228 p452 p304 distance= 0 facet p228 p600 p304 distance= 0 facet p228 p600 p452 distance= 0 These points either have a maximum or minimum x-coordinate, or they maximize the determinant for k coordinates. Trial points are first selected from points that maximize a coordinate. The min and max coordinates for each dimension are: 0: -3.134 5.701 difference= 8.835 1: -3.134 5.701 difference= 8.835 2: -2.118e-22 8.835 difference= 8.835 If the input should be full dimensional, you have several options that may determine an initial simplex: - use 'QJ' to joggle the input and make it full dimensional - use 'QbB' to scale the points to the unit cube - use 'QR0' to randomly rotate the input for different maximum points - use 'Qs' to search all points for the initial simplex - use 'En' to specify a maximum roundoff error less than 1.2e-14. - trace execution with 'T3' to see the determinant for each point. If the input is lower dimensional: - use 'QJ' to joggle the input and make it full dimensional - use 'Qbk:0Bk:0' to delete coordinate k from the input. You should pick the coordinate with the least range. The hull will have the correct topology. - determine the flat containing the points, rotate the points into a coordinate plane, and delete the other coordinates. - add one or more points to make the input full dimensional. Traceback (most recent call last): File "./scatter.py", line 43, in zi = griddata((x, y), z, (xi, yi), method='linear') File "/usr/lib/python2.7/dist-packages/scipy/interpolate/ndgriddata.py", line 183, in griddata ip = LinearNDInterpolator(points, values, fill_value=fill_value) File "interpnd.pyx", line 192, in scipy.interpolate.interpnd.LinearNDInterpolator.__init__ (scipy/interpolate/interpnd.c:2598) File "qhull.pyx", line 948, in scipy.spatial.qhull.Delaunay.__init__ (scipy/spatial/qhull.c:4121) File "qhull.pyx", line 172, in scipy.spatial.qhull._construct_delaunay (scipy/spatial/qhull.c:1314) RuntimeError: Qhull error Could anyone help me to point out what exactly I am missing here. I just wish to plot 2D map with color bar for Z-axis. Thank you in advance. -- DJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From cmferras at estudiantes.uci.cu Thu Oct 16 11:21:38 2014 From: cmferras at estudiantes.uci.cu (C@rlos) Date: Thu, 16 Oct 2014 11:21:38 -0400 (CDT) Subject: Convert Qstring to string in windows In-Reply-To: <1549164247.13980291.1413472329833.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: <969535236.13984943.1413472898089.JavaMail.zimbra@estudiantes.uci.cu> I have been tryed to convert a Qstring text to string on python, in linux that work fine but in windows when qstring contine ?,?,?,?,? the converted text is not correct, contine extranger characters, this qstring text is an url from qdialogtext. in linux i do for this way: pythonstringtext=qstringtext.text().toUtf8.data() and it return a python string correctly. i need some help plese... .....C at rlos III Escuela Internacional de Invierno en la UCI del 17 al 28 de febrero del 2014. Ver www.uci.cu -------------- next part -------------- An HTML attachment was scrubbed... URL: From dhananjay.c.joshi at gmail.com Thu Oct 16 23:45:20 2014 From: dhananjay.c.joshi at gmail.com (Dhananjay) Date: Fri, 17 Oct 2014 11:45:20 +0800 Subject: No subject Message-ID: Hello, This might be simple, but I guess I am missing something here. I have data file as follows: 2.1576318858 -1.8651195165 4.2333428278 2.1681875208 -1.9229968780 4.1989176884 2.3387636157 -2.0376253255 2.4460899122 2.1696565965 -2.6186941271 4.4172007912 2.0848862071 -2.1708981985 3.3404520962 2.0824347942 -1.9142798955 3.3629290206 2.0281685821 -1.8103363482 2.5446721669 2.3309993378 -1.8721153619 2.7006893016 2.0957461483 -1.5379071451 4.5228264441 2.2761376261 -2.5935979811 3.9231744717 . . . (total of 200 lines) Columns 1,2,3 corresponds to x,y,z axis data points. This is not a continuous data. I wish to make a plot as a 2D with 3rd dimension (i.e z-axis data) as a color map with color bar on right hand side. As a beginner, I tried to follow tutorial with some modification as follows: http://matplotlib.org/examples/pylab_examples/tricontour_vs_griddata.html # Read data from file: fl1 = open('flooding-psiphi.dat','r').readlines() xs = ys = zs = [] for line in fl1: line = line.split() xs.append(float(line[0])) ys.append(float(line[1])) zs.append(float(line[2])) print xs[0], ys[0], zs[0] xi = np.mgrid[-5.0:5.0:200j] yi = np.mgrid[-5.0:5.0:200j] zi = griddata((x, y), z, (xi, yi), method='cubic') plt.subplot(221) plt.contour(xi, yi, zi, 15, linewidths=0.5, colors='k') plt.contourf(xi, yi, zi, 15, cmap=plt.cm.rainbow, norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) plt.colorbar() # draw colorbar plt.plot(x, y, 'ko', ms=3) plt.xlim(-5, 5) plt.ylim(-5, 5) plt.title('griddata and contour (%d points, %d grid points)' % (npts, ngridx*ngridy)) #print ('griddata and contour seconds: %f' % (time.clock() - start)) plt.gcf().set_size_inches(6, 6) plt.show() However, I failed and getting long error as follows: QH6154 qhull precision error: initial facet 1 is coplanar with the interior point ERRONEOUS FACET: - f1 - flags: bottom simplicial upperDelaunay flipped - normal: 0.7071 -0.7071 0 - offset: -0 - vertices: p600(v2) p452(v1) p304(v0) - neighboring facets: f2 f3 f4 While executing: | qhull d Qz Qbb Qt Options selected for Qhull 2010.1 2010/01/14: run-id 1531309415 delaunay Qz-infinity-point Qbbound-last Qtriangulate _pre-merge _zero-centrum Pgood _max-width 8.8 Error-roundoff 1.2e-14 _one-merge 8.6e-14 _near-inside 4.3e-13 Visible-distance 2.5e-14 U-coplanar-distance 2.5e-14 Width-outside 4.9e-14 _wide-facet 1.5e-13 precision problems (corrected unless 'Q0' or an error) 2 flipped facets The input to qhull appears to be less than 3 dimensional, or a computation has overflowed. Qhull could not construct a clearly convex simplex from points: - p228(v3): 2.4 2.4 1.4 - p600(v2): 1.4 1.4 8.8 - p452(v1): 5.7 5.7 8 - p304(v0): -3.1 -3.1 2.4 The center point is coplanar with a facet, or a vertex is coplanar with a neighboring facet. The maximum round off error for computing distances is 1.2e-14. The center point, facets and distances to the center point are as follows: center point 1.595 1.595 5.173 facet p600 p452 p304 distance= 0 facet p228 p452 p304 distance= 0 facet p228 p600 p304 distance= 0 facet p228 p600 p452 distance= 0 These points either have a maximum or minimum x-coordinate, or they maximize the determinant for k coordinates. Trial points are first selected from points that maximize a coordinate. The min and max coordinates for each dimension are: 0: -3.134 5.701 difference= 8.835 1: -3.134 5.701 difference= 8.835 2: -2.118e-22 8.835 difference= 8.835 If the input should be full dimensional, you have several options that may determine an initial simplex: - use 'QJ' to joggle the input and make it full dimensional - use 'QbB' to scale the points to the unit cube - use 'QR0' to randomly rotate the input for different maximum points - use 'Qs' to search all points for the initial simplex - use 'En' to specify a maximum roundoff error less than 1.2e-14. - trace execution with 'T3' to see the determinant for each point. If the input is lower dimensional: - use 'QJ' to joggle the input and make it full dimensional - use 'Qbk:0Bk:0' to delete coordinate k from the input. You should pick the coordinate with the least range. The hull will have the correct topology. - determine the flat containing the points, rotate the points into a coordinate plane, and delete the other coordinates. - add one or more points to make the input full dimensional. Traceback (most recent call last): File "./scatter.py", line 43, in zi = griddata((x, y), z, (xi, yi), method='linear') File "/usr/lib/python2.7/dist-packages/scipy/interpolate/ndgriddata.py", line 183, in griddata ip = LinearNDInterpolator(points, values, fill_value=fill_value) File "interpnd.pyx", line 192, in scipy.interpolate.interpnd.LinearNDInterpolator.__init__ (scipy/interpolate/interpnd.c:2598) File "qhull.pyx", line 948, in scipy.spatial.qhull.Delaunay.__init__ (scipy/spatial/qhull.c:4121) File "qhull.pyx", line 172, in scipy.spatial.qhull._construct_delaunay (scipy/spatial/qhull.c:1314) RuntimeError: Qhull error Could anyone help me to point out what exactly I am missing here. I just wish to plot 2D map with color bar for Z-axis. Thank you in advance. -- DJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From varun7rs at gmail.com Fri Oct 17 04:33:53 2014 From: varun7rs at gmail.com (varun7rs at gmail.com) Date: Fri, 17 Oct 2014 01:33:53 -0700 (PDT) Subject: Help in using grako for parsing Message-ID: <7228e528-c597-4fd3-8620-508361aa0f6b@googlegroups.com> Hello, I am trying to parse a file which ahs the below content. I tried using the split function but that wasn't a good programming practice. I had to use it repeatedly to split the line and then read my data. I thought of doing it in a better way which is when I came across grako. But I have no idea whatsoever about the usage of grako in a script. It would be nice if any of you could help me understand the usage of grako. I need to extract the values beside the variables z, f and x. The numbers represent the request ID, virtualNode ID and physical nodeID for x and it varies a bit for f, Thanks a lot z_0 1.000000 x_0_0_1 1.000000 x_0_1_5 1.000000 x_0_2_20 1.000000 x_0_3_21 1.000000 x_0_4_8 1.000000 f_0_0(0,1)_(1,5) 1.000000 f_0_1(1,2)_(5,9) 1.000000 f_0_1(1,2)_(9,20) 1.000000 f_0_2(2,3)_(2,21) 1.000000 f_0_2(3,2)_(2,22) 1.000000 f_0_2(2,3)_(20,22) 1.000000 f_0_3(4,3)_(8,10) 1.000000 f_0_3(3,4)_(0,10) 1.000000 f_0_3(4,3)_(0,14) 1.000000 f_0_3(4,3)_(14,21) 1.000000 z_1 1.000000 x_1_0_16 1.000000 x_1_1_6 1.000000 x_1_2_13 1.000000 x_1_3_0 1.000000 x_1_4_25 1.000000 x_1_5_15 1.000000 x_1_6_19 1.000000 f_1_0(1,0)_(6,16) 1.000000 f_1_1(0,2)_(6,11) 1.000000 f_1_1(0,2)_(11,13) 1.000000 f_1_1(2,0)_(6,16) 1.000000 f_1_2(3,1)_(0,6) 1.000000 f_1_3(2,4)_(13,25) 1.000000 f_1_4(5,4)_(15,25) 1.000000 f_1_5(3,6)_(0,1) 1.000000 f_1_5(3,6)_(1,18) 1.000000 f_1_5(3,6)_(18,19) 1.000000 From __peter__ at web.de Fri Oct 17 04:57:38 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Oct 2014 10:57:38 +0200 Subject: Help in using grako for parsing References: <7228e528-c597-4fd3-8620-508361aa0f6b@googlegroups.com> Message-ID: varun7rs at gmail.com wrote: > Hello, > I am trying to parse a file which ahs the below content. I tried using the > split function but that wasn't a good programming practice. I had to use > it repeatedly to split the line and then read my data. I thought of doing > it in a better way which is when I came across grako. But I have no idea > whatsoever about the usage of grako in a script. It would be nice if any > of you could help me understand the usage of grako. I need to extract the > values beside the variables z, f and x. The numbers represent the request > ID, virtualNode ID and physical nodeID for x and it varies a bit for f, We know Python, but not necessarily any terminology you throw at us. I didn't respond to your previous post because I had no idea what a .sol file is and what you're up to. As far as I can see no-one did. Now you make it even harder to help you by forcing us to look up "grako" to not (sic!) understand your question... You give sample input below. Perhaps you'll get more/better feedback if you provide a sample of the output you need, too, together with a more elaborate and accessible explanation of how you think you could get there. > z_0 1.000000 > x_0_0_1 1.000000 > x_0_1_5 1.000000 > x_0_2_20 1.000000 > x_0_3_21 1.000000 > x_0_4_8 1.000000 > f_0_0(0,1)_(1,5) 1.000000 > f_0_1(1,2)_(5,9) 1.000000 > f_0_1(1,2)_(9,20) 1.000000 > f_0_2(2,3)_(2,21) 1.000000 > f_0_2(3,2)_(2,22) 1.000000 > f_0_2(2,3)_(20,22) 1.000000 > f_0_3(4,3)_(8,10) 1.000000 > f_0_3(3,4)_(0,10) 1.000000 > f_0_3(4,3)_(0,14) 1.000000 > f_0_3(4,3)_(14,21) 1.000000 > z_1 1.000000 > x_1_0_16 1.000000 > x_1_1_6 1.000000 > x_1_2_13 1.000000 > x_1_3_0 1.000000 > x_1_4_25 1.000000 > x_1_5_15 1.000000 > x_1_6_19 1.000000 > f_1_0(1,0)_(6,16) 1.000000 > f_1_1(0,2)_(6,11) 1.000000 > f_1_1(0,2)_(11,13) 1.000000 > f_1_1(2,0)_(6,16) 1.000000 > f_1_2(3,1)_(0,6) 1.000000 > f_1_3(2,4)_(13,25) 1.000000 > f_1_4(5,4)_(15,25) 1.000000 > f_1_5(3,6)_(0,1) 1.000000 > f_1_5(3,6)_(1,18) 1.000000 > f_1_5(3,6)_(18,19) 1.000000 From varun7rs at gmail.com Fri Oct 17 05:17:01 2014 From: varun7rs at gmail.com (varun7rs at gmail.com) Date: Fri, 17 Oct 2014 02:17:01 -0700 (PDT) Subject: Help in using grako for parsing In-Reply-To: <7228e528-c597-4fd3-8620-508361aa0f6b@googlegroups.com> References: <7228e528-c597-4fd3-8620-508361aa0f6b@googlegroups.com> Message-ID: <3fbc4d4d-c992-4ca8-99fc-ec138fce3523@googlegroups.com> I'm really sorry for not being clear. I shall explain things in detail from now onwards. Really sorry. The output I would like is In a similar way I have something like this for every request. This is what I intend to get from the input that I had pasted earlier. From varun7rs at gmail.com Fri Oct 17 05:18:58 2014 From: varun7rs at gmail.com (varun7rs at gmail.com) Date: Fri, 17 Oct 2014 02:18:58 -0700 (PDT) Subject: Help in using grako for parsing In-Reply-To: <7228e528-c597-4fd3-8620-508361aa0f6b@googlegroups.com> References: <7228e528-c597-4fd3-8620-508361aa0f6b@googlegroups.com> Message-ID: <92338730-467b-49a5-b235-ca6b9015b089@googlegroups.com> Oh damn, it turned out really crappy. I could not format it properly From a.nandagoban at traxens.com Fri Oct 17 05:59:48 2014 From: a.nandagoban at traxens.com (Arulnambi Nandagoban) Date: Fri, 17 Oct 2014 11:59:48 +0200 Subject: windows log to event viewer Message-ID: <001501cfe9f1$16ff6460$44fe2d20$@traxens.com> Hello, I am trying to run a tcp server as a windows service. The project also includes an application layer protocol somewhat like CoAP and few soap calls to data base. There is some moment the code enter into exception during a soap method call. This exception is not viewed in Windows event viewer. Should I specify somewhere to log these exception in windows event viewer. Or, give me some suggestion how to log some Critical message in windows log. -- nambi -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Fri Oct 17 06:43:16 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 17 Oct 2014 21:43:16 +1100 Subject: your mail In-Reply-To: References: Message-ID: <20141017104316.GA49644@cskk.homeip.net> On 17Oct2014 11:45, Dhananjay wrote: >This might be simple, but I guess I am missing something here. >I have data file as follows: > >2.1576318858 -1.8651195165 4.2333428278 >2.1681875208 -1.9229968780 4.1989176884 >2.3387636157 -2.0376253255 2.4460899122 >2.1696565965 -2.6186941271 4.4172007912 >2.0848862071 -2.1708981985 3.3404520962 >2.0824347942 -1.9142798955 3.3629290206 >2.0281685821 -1.8103363482 2.5446721669 >2.3309993378 -1.8721153619 2.7006893016 >2.0957461483 -1.5379071451 4.5228264441 >2.2761376261 -2.5935979811 3.9231744717 >(total of 200 lines) > >Columns 1,2,3 corresponds to x,y,z axis data points. >This is not a continuous data. I wish to make a plot as a 2D with 3rd >dimension (i.e z-axis data) as a color map with color bar on right hand side. > >As a beginner, I tried to follow tutorial with some modification as follows: >http://matplotlib.org/examples/pylab_examples/tricontour_vs_griddata.html [...] Initially I've just got comments about the code in general, though they may help you find your issues. ># Read data from file: >fl1 = open('flooding-psiphi.dat','r').readlines() This reads all the lines into memory, into the list "fl1". For 200 lines this is not a bit issue, but since you process them immediately you are usually better off reading the file progressively. >xs = ys = zs = [] This is actually a bug in your code. I would guess you've based it on other example code such as: x = y = z = 0 The problem is that both these assignment statements assign the _same_ object to all 3 variables. With an int or a str this isn't an issue because they are immutable; any further math or modification actually makes new objects. However, you use: xs = ys = zs = [] This makes exactly _one_ list, and assigns it ("binds it" in Python terms) to all three names. The result is that when you append to the list, you're appending to the same list every time. Effectively this means (1) that xs, ys and zs have the same values and (2) they're 3 times as long as they should be. Do this: xs = [] ys = [] zs = [] That makes three separate lists. >for line in fl1: >??? line = line.split() >??? xs.append(float(line[0])) >??? ys.append(float(line[1])) >??? zs.append(float(line[2])) Returning to the "reading the file progressively" thing, for a really big file (and as a matter of general practice) you're better off writing this like: for line in open('flooding-psiphi.dat','r'): ??? line = line.split() ??? xs.append(float(line[0])) ??? ys.append(float(line[1])) ??? zs.append(float(line[2])) which only ever reads one line of text from the file at a time. Start by fixing the: xs = ys = zs = [] assignment and see how the behaviour changes. Cheers, Cameron Simpson From jeanmichel at sequans.com Fri Oct 17 09:13:50 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 17 Oct 2014 15:13:50 +0200 (CEST) Subject: Permissions on files installed by pip? In-Reply-To: Message-ID: <259662419.89442.1413551630644.JavaMail.root@sequans.com> ----- Original Message ----- > From: "Adam Funk" > To: python-list at python.org > Sent: Thursday, 16 October, 2014 9:29:46 PM > Subject: Permissions on files installed by pip? > > I've been using the python-nltk package on Ubuntu, but I need ntlk > 3.0 > now. I used 'sudo aptitude purge python-nltk' to get rid of my > existing installation, & followed instructions on the nltk website > [1] > starting at step 4 (since I already have python-pip & python-numpy > packages installed). > > $ sudo pip install -U > > I couldn't get it to work, until I realized that the permissions & > ownership on /usr/local/lib/python2.7/dist-packages were 'drwx--S--- > root staff'. A 'chmod -R a+rX' on that directory seems to have fixed > it. Is it normal for sudo pip install to set the permissions that > way, or did I do something wrong? On debian wheezy: ls -al /usr/local/lib/python2.7/dist-packages drwxrwsr-x 5 root staff 4.0K Jun 30 15:16 ./ I'm not sure pip is responsible for this anyway, so my money goes on "you did something wrong" :) JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From tycho at tycho.ws Fri Oct 17 09:37:07 2014 From: tycho at tycho.ws (Tycho Andersen) Date: Fri, 17 Oct 2014 15:37:07 +0200 Subject: non-gobject based dbus library? Message-ID: Hi all, An application I maintain recently moved away from the gobject event loop to the tulip/trollius/asyncio event loop. However, we were using python-dbus, which internally uses the gobject event loop, as our main event loop. This worked nicely when we were gobject based, but now that we're not, I'm trying to find alternatives to python-dbus so that we can re-implement the dbus-based functionality. I tried gbulb: https://bitbucket.org/a_ba/gbulb but it seems mostly abandoned, and I had to hack on it to even get our application to boot, and some things didn't work correctly. Does anyone have any ideas? (Please keep me in CC, I'm not subscribed.) Thanks! Tycho From pkpearson at nowhere.invalid Fri Oct 17 11:51:21 2014 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 17 Oct 2014 15:51:21 GMT Subject: 2d color-bar map plot References: Message-ID: On Fri, 17 Oct 2014 14:28:13 +0800, Dhananjay wrote: [snip] > xs = ys = zs = [] > for line in fl1: > line = line.split() > xs.append(float(line[0])) > ys.append(float(line[1])) > zs.append(float(line[2])) > > print xs[0], ys[0], zs[0] The line "xs = ys = zs = []" is almost surely not what you want to do. It results in xs, ys, and zs all being the same object. Look: >>> xs = ys = zs = [] >>> xs.append(1) >>> print(ys) [1] >>> Since your xs, ys, and zs are all identical, some unfortunate part of the plotting package is trying in vain to find some thickness to the thing it's plotting, but it can't, because all the points you've given it lie on the x=y=z plane. (It's sad that it tries so heroically to give a detailed error message that turns out to be so obscure.) So spend a few more characters: xs = [] ys = [] zs = [] Then, on to the next problem. -- To email me, substitute nowhere->runbox, invalid->com. From tjreedy at udel.edu Fri Oct 17 12:37:03 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 17 Oct 2014 12:37:03 -0400 Subject: your mail In-Reply-To: <20141017104316.GA49644@cskk.homeip.net> References: <20141017104316.GA49644@cskk.homeip.net> Message-ID: On 10/17/2014 6:43 AM, Cameron Simpson wrote: > On 17Oct2014 11:45, Dhananjay wrote: >> 2.1576318858 -1.8651195165 4.2333428278 >> ... >> (total of 200 lines) >> >> Columns 1,2,3 corresponds to x,y,z axis data points. > for line in open('flooding-psiphi.dat','r'): > line = line.split() > xs.append(float(line[0])) > ys.append(float(line[1])) > zs.append(float(line[2])) A further refinement: for line in open('flooding-psiphi.dat','r'): x, y, z = map(float, line.split()) xs.append(x) ys.append(y) zs.append(z) -- Terry Jan Reedy From tbaror at gmail.com Fri Oct 17 12:56:17 2014 From: tbaror at gmail.com (Tal Bar-Or) Date: Fri, 17 Oct 2014 09:56:17 -0700 (PDT) Subject: Write list to new column in existent csv Message-ID: Hello Group, I am tryin to figure how to write a list i have as follows ['info', '19987???445 [SYN] Seq=0 Win=8192 Len=0 MSS=1460 WS=256 SACK_PERM=1\n', '445???19987 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1460 WS=64 SACK_PERM=1\n', '19987???445 [ACK] Seq=1 Ack=1 Win=65536 Len=0\n', 'Negotiate Protocol Request\n', '[TCP Retransmission] Negotiate Protocol Request\n', '445???19987 [ACK] Seq=1 Ack=160 Win=1049536 Len=0\n', 'Negotiate Protocol Response\n', 'Negotiate Protocol Request\n', 'Negotiate Protocol Response\n', 'Session Setup Request, NTLMSSP_NEGOTIATE\n', 'Session Setup Response, Error: STATUS_MORE_PROCESSING_REQUIRED, NTLMSSP_CHALLENGE\n', 'Session Setup Request, NTLMSSP_AUTH, User: GEFEN\\tbaror\n', '445???19987 [ACK] Seq=768 Ack=1016 Win=1049728 Len=0\n', 'Session Setup Response\n', 'Tree Connect Request Tree: \\\\media.isilon.gefen.local\\Media\n', 'Tree Connect Response\n', 'Create Request File: New Text document.txt\n', 'Create Response File: New Text document.txt\n', 'GetInfo Request FS_INFO/SMB2_FS_INFO_01 File: New Text document.txt;GetInfo Request FS_INFO/SMB2_FS_INFO_05 File: New Text document.txt\n'] To a a csv to for example the 3rd column , i am really got stacked here i tried few codes with csv.writerow() but didn't got it work ,will really appreciate if someone could help me with that Please advice Thanks The csv ip.src,ip.dst,smb.file,smb2.filename,smb.path,smb2.tree,smb.time,smb2.time,smb.cmd,smb2.cmd,tcp.time_delta,tcp.analysis.ack_rtt,tcp.analysis.ack_lost_segment,tcp.analysis.duplicate_ack,tcp.analysis.lost_segment,tcp.analysis.retransmission,tcp.analysis.out_of_order,tcp.analysis.window_full,tcp.analysis.window_update,tcp.analysis.zero_window 172.18.2.54,172.18.5.64,,,,,,,,,0,,,,,,,,, 172.18.5.64,172.18.2.54,,,,,,,,,0.003322,0.003322,,,,,,,, 172.18.2.54,172.18.5.64,,,,,,,,,0.000029,0.000029,,,,,,,, 172.18.2.54,172.18.5.64,,,,,,,114,,0.000084,,,,,,,,, 172.18.2.54,172.18.5.64,,,,,,,114,,0.300507,,,,,1,,,, 172.18.5.64,172.18.2.54,,,,,,,,,0.000114,0.300621,,,,,,,, 172.18.5.64,172.18.2.54,,,,,,,,0,0.000266,,,,,,,,, 172.18.2.54,172.18.5.64,,,,,,,,0,0.000092,0.000092,,,,,,,, 172.18.5.64,172.18.2.54,,,,,,0.000192,,0,0.000192,0.000192,,,,,,,, 172.18.2.54,172.18.5.64,,,,,,,,1,0.000589,0.000589,,,,,,,, 172.18.5.64,172.18.2.54,,,,,,0.001788,,1,0.001788,0.001788,,,,,,,, 172.18.2.54,172.18.5.64,,,,,,,,1,0.000193,0.000193,,,,,,,, 172.18.5.64,172.18.2.54,,,,,,,,,0.005582,0.005582,,,,,,,, 172.18.5.64,172.18.2.54,,,,,,0.008014,,1,0.002432,,,,,,,,, 172.18.2.54,172.18.5.64,,,,\\media.isilon.gefen.local\Media,,,,3,0.000203,0.000203,,,,,,,, 172.18.5.64,172.18.2.54,,,,,,0.000458,,3,0.000458,0.000458,,,,,,,, 172.18.2.54,172.18.5.64,,New Text document.txt,,\\media.isilon.gefen.local\Media,,,,5,0.000189,0.000189,,,,,,,, 172.18.5.64,172.18.2.54,,,,\\media.isilon.gefen.local\Media,,0.000274,,5,0.000274,0.000274,,,,,,,, From irmen.NOSPAM at xs4all.nl Fri Oct 17 13:15:22 2014 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Fri, 17 Oct 2014 19:15:22 +0200 Subject: windows log to event viewer In-Reply-To: References: Message-ID: <54414eab$0$2901$e4fe514c@news.xs4all.nl> On 17-10-2014 11:59, Arulnambi Nandagoban wrote: > Hello, > > > > I am trying to run a tcp server as a windows service. > > The project also includes an application layer protocol somewhat like CoAP and few soap > calls to data base. > > There is some moment the code enter into exception during a soap method call. This > exception is not viewed in > > Windows event viewer. Should I specify somewhere to log these exception in windows event > viewer. Or, give me some suggestion how to log some > > Critical message in windows log. > What I would try is to catch the exception and log it, including a message, to the NT Event log. You should be able to do this using the NTEventLogHandler from Python's standard logging module, see: https://docs.python.org/3.4/library/logging.handlers.html#logging.handlers.NTEventLogHandler Irmen From __peter__ at web.de Fri Oct 17 14:08:42 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 17 Oct 2014 20:08:42 +0200 Subject: Write list to new column in existent csv References: Message-ID: Tal Bar-Or wrote: > I am tryin to figure how to write a list i have as follows > To a a csv to for example the 3rd column , i am really got stacked here i > tried few codes with csv.writerow() but didn't got it work ,will really > appreciate if someone could help me with that Please advice Thanks Here's a sketch: Open the source file using a csv.reader(); open the destination file using a csv.writer(). Use zip() and a for-loop to iterate over the new column and the rows in the source. Insert the new field into the source row, e. g. row.insert(3, field) Use writerow() to write the modified row. From breamoreboy at yahoo.co.uk Fri Oct 17 14:51:25 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 17 Oct 2014 19:51:25 +0100 Subject: 2d color-bar map plot In-Reply-To: References: Message-ID: On 17/10/2014 07:28, Dhananjay wrote: > Dear all, > I am bit new to the python/pyplot. > This might be simple, but I guess I am missing something here. I doubt that you'll get detailed answers here so suggest you try https://lists.sourceforge.net/lists/listinfo/matplotlib-users which is also available as gmane.comp.python.matplotlib.general -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Fri Oct 17 14:56:02 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 17 Oct 2014 19:56:02 +0100 Subject: windows log to event viewer In-Reply-To: <001501cfe9f1$16ff6460$44fe2d20$@traxens.com> References: <001501cfe9f1$16ff6460$44fe2d20$@traxens.com> Message-ID: On 17/10/2014 10:59, Arulnambi Nandagoban wrote: > Hello, > > I am trying to run a tcp server as a windows service. > > The project also includes an application layer protocol somewhat like > CoAP and few soap calls to data base. > > There is some moment the code enter into exception during a soap method > call. This exception is not viewed in > > Windows event viewer. Should I specify somewhere to log these exception > in windows event viewer. Or, give me some suggestion how to log some > > Critical message in windows log. > > -- > > nambi > http://stackoverflow.com/questions/113007/writing-to-the-windows-logs-in-python -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From jcasale at activenetwerx.com Fri Oct 17 16:35:02 2014 From: jcasale at activenetwerx.com (Joseph L. Casale) Date: Fri, 17 Oct 2014 20:35:02 +0000 Subject: Processing xml for output with cElementTree Message-ID: <1413578102216.94005@activenetwerx.com> I am unfortunately?unable to use lxml for a project and must resort to base only libraries to create several nested elements located directly under a root element. The caveat is the incremental writing and flushing of the nested elements as they are created. So assuming the structure is texttext if I would like to manually deconstruct this in order to write each element in order of appearance, is there any built in facility for this? The way I am currently doing is rather pathetic... Thanks, jlc From eryksun at gmail.com Sat Oct 18 00:02:36 2014 From: eryksun at gmail.com (eryksun) Date: Fri, 17 Oct 2014 23:02:36 -0500 Subject: [Tutor] Convert Qstring to string in windows In-Reply-To: <969535236.13984943.1413472898089.JavaMail.zimbra@estudiantes.uci.cu> References: <1549164247.13980291.1413472329833.JavaMail.zimbra@estudiantes.uci.cu> <969535236.13984943.1413472898089.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On Thu, Oct 16, 2014 at 10:21 AM, C at rlos wrote: > in linux i do for this way: > pythonstringtext=qstringtext.text().toUtf8.data() > and it return a python string correctly. pythonstringtext is a byte string that has to be decoded as UTF-8. Here's the 'mojibake' result when it gets decoded as UTF-16LE or Windows codepages 850 and 1252: >>> s = u'?????' >>> b = s.encode('utf-8') >>> print b.decode('utf-16le') ????? >>> print b.decode('850') ?????????? >>> print b.decode('1252') ?????????? The native character size in the Windows kernel is 2 bytes, so UTF-16 is the path of least resistance for in-memory strings used with GUI controls and file/registry paths. UTF-8 is preferred for text data in files and network communication. From emptya45 at gmail.com Fri Oct 17 07:38:54 2014 From: emptya45 at gmail.com (Empty Account) Date: Fri, 17 Oct 2014 12:38:54 +0100 Subject: Flush stdin Message-ID: Hi, I am using netcat to listen to a port and python to read stdin and print to the console. nc -l 2003 | python print_metrics.py sys.stdin.flush() doesn?t seem to flush stdin, so I am using the termios module. while True: input = sys.stdin.readline() # do some parsing ? sys.stdout.write(parsed_data) time.sleep(3) termios.tcflush(sys.stdin, termios.TCIOFLUSH) I am receiving this exception termios.error: (25, 'Inappropriate ioctl for device') I will be using this script on Unix based systems and I wondered what approach I could use to flush stdin? Many Thanks Aidy -------------- next part -------------- An HTML attachment was scrubbed... URL: From vbubbly21 at gmail.com Sat Oct 18 01:58:02 2014 From: vbubbly21 at gmail.com (Artur Bercik) Date: Sat, 18 Oct 2014 14:58:02 +0900 Subject: Extract Indices of Numpy Array Based on Given Bit Information Message-ID: Dear Python and Numpy Users: My data are in the form of '32-bit unsigned integer' as follows: myData = np.array([1073741824, 1073741877, 1073742657, 1073742709, 1073742723, 1073755137, 1073755189,1073755969],dtype=np.int32) I want to get the index of my data where the following occurs: Bit No. 0?1 Bit Combination: 00 How can I do it? I heard this type of problem first time, please help me. Artur -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Sat Oct 18 02:24:39 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 18 Oct 2014 17:24:39 +1100 Subject: Extract Indices of Numpy Array Based on Given Bit Information In-Reply-To: References: Message-ID: On Sat, Oct 18, 2014 at 4:58 PM, Artur Bercik wrote: > I want to get the index of my data where the following occurs: > > Bit No. 0?1 > Bit Combination: 00 So, what you want to do is look at each number in binary, and find the ones that have two zeroes in the last two places? 1073741824: 1000000000000000000000000000000 1073741877: 1000000000000000000000000110101 The easiest way to do this is with simple bitwise operations: >>> 1073741824 & 3 0 >>> 1073741877 & 3 1 3 is 0000000000000011 in binary, so a bitwise AND with that will tell you about just the last two bits. The result will be an integer - 0, 1, 2, or 3, representing 00, 01, 10, or 11 for those last two bits. So all you have to do is AND each number with 3, and when the result is 0, that's what you want. Does that make sense? ChrisA From rosuav at gmail.com Sat Oct 18 02:25:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 18 Oct 2014 17:25:29 +1100 Subject: Flush stdin In-Reply-To: References: Message-ID: On Fri, Oct 17, 2014 at 10:38 PM, Empty Account wrote: > I will be using this script on Unix based systems and I wondered what > approach I could use > to flush stdin? Why exactly do you need to flush stdin? If you've written a small amount of data to the console, it's stdout that you need to flush. ChrisA From rosuav at gmail.com Sat Oct 18 02:50:47 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 18 Oct 2014 17:50:47 +1100 Subject: Extract Indices of Numpy Array Based on Given Bit Information In-Reply-To: References: Message-ID: On Sat, Oct 18, 2014 at 5:42 PM, Artur Bercik wrote: > I got some sense, but could not imagine if required Bit No. 2?5, and Bit > Combination 0000. > > I hope example with the new case would make me more sense. > Just write the number in binary, with the bits you're interested in set to 1, and everything else 0: ... 876543210 ... 000111100 >>> 0b000111100 60 >>> 1073741877 & 0b000111100 52 So this number does _not_ have all zeroes there. If it did, the result would be zero. To look for some other pattern, just do the same thing - suppose we want to find numbers where it's 1001, we just look for the result to be 0b000100100, or 36. ChrisA From pecore at pascolo.net Sat Oct 18 03:06:33 2014 From: pecore at pascolo.net (giacomo boffi) Date: Sat, 18 Oct 2014 09:06:33 +0200 Subject: [OT] spelling colour / color was Re: Toggle References: <5435e4e6$0$12982$c3e8da3$5496439d@news.astraweb.com> <5436d2f0$0$48145$862e30e2@ngroups.net> <877g099dgb.fsf@elektro.pacujo.net> <87y4sneok9.fsf@elektro.pacujo.net> <7L8_v.450636$NQ4.108421@fx26.am4> <54394c37$0$48107$862e30e2@ngroups.net> <5439bffe$0$48338$862e30e2@ngroups.net> Message-ID: <87d29peu12.fsf@pascolo.net> duncan smith writes: > [...] It was the "top / bottom of the [TV] programme" that I didn't > immediately get, because I was thinking of a timeline running left > to right (perhaps rather than the script used by the presenters). is it just me that thinks of a timeline running from the wall behind the tv set into my dinette? From rosuav at gmail.com Sat Oct 18 03:10:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 18 Oct 2014 18:10:40 +1100 Subject: Extract Indices of Numpy Array Based on Given Bit Information In-Reply-To: References: Message-ID: On Sat, Oct 18, 2014 at 6:02 PM, Artur Bercik wrote: > So, the Bit No. 2-5 for the following case is '1101', right? > > 1073741877: 1000000000000000000000000110101 > > If my required bit combination for Bit No. 2-5 is '1011', then the above > number (1073741877) is not chosen, right?? > > Look forward to know your confirmation. (Side point: Please don't top-post. The convention on this mailing list, and most other technical mailing lists, is what's sometimes called "interleaved style"; you trim the quoted text to what's needed for context, and put your text underneath what you're referring to. See https://en.wikipedia.org/wiki/Posting_style#Interleaved_style for more info.) >>> 1073741877&60 52 >>> bin(52) '0b110100' Everything I've written with the triple-angle-bracket marker can be typed in at the Python prompt, and you'll see exactly what it does. In this case, you can see that you're absolutely right: 1073741877 has 1101 in those positions, so if you're looking for 1011, it won't match: >>> 0b101100 44 However, 1073741869 would: >>> 1073741869&60 44 The way to test would be something like this: >>> (1073741877 & 0b111100) == 0b101100 False >>> (1073741869 & 0b111100) == 0b101100 True ChrisA From cs at zip.com.au Sat Oct 18 03:11:45 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 18 Oct 2014 18:11:45 +1100 Subject: Flush stdin In-Reply-To: References: Message-ID: <20141018071145.GA11963@cskk.homeip.net> On 17Oct2014 12:38, Empty Account wrote: >I am using netcat to listen to a port and python to read stdin and print to >the console. > >nc -l 2003 | python print_metrics.py > >sys.stdin.flush() doesn?t seem to flush stdin, so I am using the termios >module.? You're aware that a stdio flush and a termios flush operate on two totally unrelated buffers? >while True:? >? ?input = sys.stdin.readline() >? ?# do some parsing? >? ?? ? >? ?sys.stdout.write(parsed_data) >? ?time.sleep(3) >? ?termios.tcflush(sys.stdin, termios.TCIOFLUSH) > >I am receiving this exception >termios.error: (25, 'Inappropriate ioctl for device') That is because stdin is attached to the pipe from netcat. A pipe is not a terminal. >I will be using this script on Unix based systems and I wondered what >approach I could use? >to flush stdin? Like Chris, I think you need to explain why you even want to flush stdin. There's probably something better you can do. Cheers, Cameron Simpson I strongly suspect so. Practically everyone on sci.physics has a theory that is far superior to special relativity, general relativity, quantum mechanics *and* the standard model. Around here, it's only a small clique of arrogant young members of the physics establishment who fail to recognize these revolutionary theories. I'd explain why, but I have to go finish designing my faster-than-light vacuum energy perpetual motion telekinetic aether-powered time machine. - John Baez From rosuav at gmail.com Sat Oct 18 03:22:26 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 18 Oct 2014 18:22:26 +1100 Subject: Extract Indices of Numpy Array Based on Given Bit Information In-Reply-To: References: Message-ID: On Sat, Oct 18, 2014 at 6:21 PM, Artur Bercik wrote: > Thank you very much Chris Angelico, I have come to know it. > You're most welcome. And thank you for taking heed of the request to not top-post. :) Hang around, you never know what weird and wonderful things you'll learn! From vbubbly21 at gmail.com Sat Oct 18 02:42:00 2014 From: vbubbly21 at gmail.com (Artur Bercik) Date: Sat, 18 Oct 2014 15:42:00 +0900 Subject: Extract Indices of Numpy Array Based on Given Bit Information In-Reply-To: References: Message-ID: Thanks Chris Angelico for your nice answer. I got some sense, but could not imagine if required Bit No. 2?5, and Bit Combination 0000. I hope example with the new case would make me more sense. Artur On Sat, Oct 18, 2014 at 3:24 PM, Chris Angelico wrote: > On Sat, Oct 18, 2014 at 4:58 PM, Artur Bercik wrote: > > I want to get the index of my data where the following occurs: > > > > Bit No. 0?1 > > Bit Combination: 00 > > So, what you want to do is look at each number in binary, and find the > ones that have two zeroes in the last two places? > 1073741824: 1000000000000000000000000000000 > 1073741877: 1000000000000000000000000110101 > > The easiest way to do this is with simple bitwise operations: > > >>> 1073741824 & 3 > 0 > >>> 1073741877 & 3 > 1 > > 3 is 0000000000000011 in binary, so a bitwise AND with that will tell > you about just the last two bits. The result will be an integer - 0, > 1, 2, or 3, representing 00, 01, 10, or 11 for those last two bits. So > all you have to do is AND each number with 3, and when the result is > 0, that's what you want. > > Does that make sense? > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vbubbly21 at gmail.com Sat Oct 18 03:02:25 2014 From: vbubbly21 at gmail.com (Artur Bercik) Date: Sat, 18 Oct 2014 16:02:25 +0900 Subject: Extract Indices of Numpy Array Based on Given Bit Information In-Reply-To: References: Message-ID: So, the Bit No. 2-5 for the following case is '1101', right? 1073741877: 1000000000000000000000000110101 If my required bit combination for Bit No. 2-5 is '1011', then the above number (1073741877) is not chosen, right?? Look forward to know your confirmation. On Sat, Oct 18, 2014 at 3:50 PM, Chris Angelico wrote: > On Sat, Oct 18, 2014 at 5:42 PM, Artur Bercik wrote: > > I got some sense, but could not imagine if required Bit No. 2?5, and Bit > > Combination 0000. > > > > I hope example with the new case would make me more sense. > > > > Just write the number in binary, with the bits you're interested in > set to 1, and everything else 0: > > ... 876543210 > ... 000111100 > > >>> 0b000111100 > 60 > >>> 1073741877 & 0b000111100 > 52 > > So this number does _not_ have all zeroes there. If it did, the result > would be zero. To look for some other pattern, just do the same thing > - suppose we want to find numbers where it's 1001, we just look for > the result to be 0b000100100, or 36. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vbubbly21 at gmail.com Sat Oct 18 03:21:02 2014 From: vbubbly21 at gmail.com (Artur Bercik) Date: Sat, 18 Oct 2014 16:21:02 +0900 Subject: Extract Indices of Numpy Array Based on Given Bit Information In-Reply-To: References: Message-ID: On Sat, Oct 18, 2014 at 4:10 PM, Chris Angelico wrote: > On Sat, Oct 18, 2014 at 6:02 PM, Artur Bercik wrote: > > So, the Bit No. 2-5 for the following case is '1101', right? > > > > 1073741877: 1000000000000000000000000110101 > > > > If my required bit combination for Bit No. 2-5 is '1011', then the above > > number (1073741877) is not chosen, right?? > > > > Look forward to know your confirmation. > > (Side point: Please don't top-post. The convention on this mailing > list, and most other technical mailing lists, is what's sometimes > called "interleaved style"; you trim the quoted text to what's needed > for context, and put your text underneath what you're referring to. > See https://en.wikipedia.org/wiki/Posting_style#Interleaved_style for > more info.) > > >>> 1073741877&60 > 52 > >>> bin(52) > '0b110100' > > Everything I've written with the triple-angle-bracket marker can be > typed in at the Python prompt, and you'll see exactly what it does. In > this case, you can see that you're absolutely right: 1073741877 has > 1101 in those positions, so if you're looking for 1011, it won't > match: > > >>> 0b101100 > 44 > > However, 1073741869 would: > > >>> 1073741869&60 > 44 > > The way to test would be something like this: > > >>> (1073741877 & 0b111100) == 0b101100 > False > >>> (1073741869 & 0b111100) == 0b101100 > True > Thank you very much Chris Angelico, I have come to know it. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nulla.epistola at web.de Sat Oct 18 06:27:37 2014 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sat, 18 Oct 2014 12:27:37 +0200 Subject: Sqlite3 help In-Reply-To: <4a691d82-be63-4355-8898-0ecbd9cb16bd@googlegroups.com> References: <4a691d82-be63-4355-8898-0ecbd9cb16bd@googlegroups.com> Message-ID: <54424099.3060207@web.de> Am 14.10.2014 15:36, schrieb Chuck: > I am building a simple podcast program where I download all the data from a feed with feedparser and store the data in sqlite3. I am spanking new to sqlite and database programming. Should I create the database in the __init__ method of my class, or is that a bad idea. I haven't done any designing that included databases. > > Thanks! > Chuck > When I first answered this question, I sent the answer erroneously to the OP and not to the list. So here it is again. On Tue, Oct 14, 2014 at 1:19 PM, Sibylle Koczian wrote: > > As I don't know anything at all about podcasts and feeds, I'll just > answer your question about creating the database in the __init__ > method of your class: > > That would destroy the existing database and create a new one without > any data. If you don't want to keep data from former runs of your > application, this wouldn't be necessary, because you could just > delete the data and keep the database. But most probably you want to > keep your data and add to it. In this case, you certainly don't want > to create a new database. > > The __init__ method of your class might be the right place to open > the database, though. > > You know that the documentation for the sqlite3 module is part of the > Python documentation? It contains links to the SQLite web page and to > a website with beginner information about SQL itself. So that should > help to get you started. Am 15.10.2014 18:51, schrieb Chuck Johnson: > > I was thinking that I could fix that by using ' ' ' CREATE TABLE IF > NOT EXISTS ' ' ' Should I make the sqlite3.connect() command a > global variable? I am not sure about how to design this properly. > That should work. I wouldn't make the connection a global variable. Use it as a parameter for every function that needs it. Roughly like this: import sqlite3 # other imports as needed def one_of_my_functions(myconn, my_other_parameters): mycurs = myconn.cursor() try: # do things with mycurs and my_other_parameters finally: mycurs.close() myconn.commit() # more of the same ... def main(): conn = sqlite3.connect('path/to/my/database') try: one_of_my_functions(conn, params) # more of the same finally: conn.close() if __name__ == "__main__": main() Or, if your program gets bigger, you might start and stop a connection inside a function instead of keeping one connection open for all of the application. HTH Sibylle From gandalf at shopzeus.com Sat Oct 18 05:17:18 2014 From: gandalf at shopzeus.com (=?ISO-8859-2?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Sat, 18 Oct 2014 11:17:18 +0200 Subject: pyserial on freebsd 10.10 i386 Message-ID: <5442301E.9060205@shopzeus.com> I'm trying to open a serial port with pyserial on a Compaq Deskpro EN machine. Operating system is FreeBSD 10.10 RELEASE, i386. root at merleg:~ # kldload scc root at merleg:~ # python2.7 -m serial.tools.list_ports no ports found root at merleg:~ # whoami root Here are all the devices: root at merleg:~ # ls /dev acpi ctty klog stdin ttyva ad0 cuau0 kmem stdout ttyvb ad0p1 cuau0.init log sysmouse ttyvc ad0p2 cuau0.lock lpt0 ttyu0 ttyvd ad0p3 cuau1 lpt0.ctl ttyu0.init ttyve ada0 cuau1.init mdctl ttyu0.lock ttyvf ada0p1 cuau1.lock mem ttyu1 ufssuspend ada0p2 devctl midistat ttyu1.init ugen0.1 ada0p3 devstat mixer0 ttyu1.lock ugen0.2 agpgart fd nfslock ttyv0 uhid0 apm fd0 null ttyv1 ukbd0 apmctl fido pass0 ttyv2 urandom atkbd0 geom.ctl pass1 ttyv3 usb audit gptid pci ttyv4 usbctl bpf io ppi0 ttyv5 xpt0 bpf0 kbd0 pts ttyv6 zero cd0 kbd1 random ttyv7 console kbd2 sndstat ttyv8 consolectl kbdmux0 stderr ttyv9 And here is what I see in dmesg: root at merleg:~ # dmesg | grep uart uart0: <16550 or compatible> port 0x3f8-0x3ff irq 4 flags 0x10 on acpi0 uart1: <16550 or compatible> port 0x2f8-0x2ff irq 3 on acpi0 Obviously the question is: how do I open the COM port from pyserial on this machine? From nulla.epistola at web.de Sat Oct 18 06:27:37 2014 From: nulla.epistola at web.de (Sibylle Koczian) Date: Sat, 18 Oct 2014 12:27:37 +0200 Subject: Sqlite3 help In-Reply-To: <4a691d82-be63-4355-8898-0ecbd9cb16bd@googlegroups.com> References: <4a691d82-be63-4355-8898-0ecbd9cb16bd@googlegroups.com> Message-ID: <54424099.3060207@web.de> Am 14.10.2014 15:36, schrieb Chuck: > I am building a simple podcast program where I download all the data from a feed with feedparser and store the data in sqlite3. I am spanking new to sqlite and database programming. Should I create the database in the __init__ method of my class, or is that a bad idea. I haven't done any designing that included databases. > > Thanks! > Chuck > When I first answered this question, I sent the answer erroneously to the OP and not to the list. So here it is again. On Tue, Oct 14, 2014 at 1:19 PM, Sibylle Koczian wrote: > > As I don't know anything at all about podcasts and feeds, I'll just > answer your question about creating the database in the __init__ > method of your class: > > That would destroy the existing database and create a new one without > any data. If you don't want to keep data from former runs of your > application, this wouldn't be necessary, because you could just > delete the data and keep the database. But most probably you want to > keep your data and add to it. In this case, you certainly don't want > to create a new database. > > The __init__ method of your class might be the right place to open > the database, though. > > You know that the documentation for the sqlite3 module is part of the > Python documentation? It contains links to the SQLite web page and to > a website with beginner information about SQL itself. So that should > help to get you started. Am 15.10.2014 18:51, schrieb Chuck Johnson: > > I was thinking that I could fix that by using ' ' ' CREATE TABLE IF > NOT EXISTS ' ' ' Should I make the sqlite3.connect() command a > global variable? I am not sure about how to design this properly. > That should work. I wouldn't make the connection a global variable. Use it as a parameter for every function that needs it. Roughly like this: import sqlite3 # other imports as needed def one_of_my_functions(myconn, my_other_parameters): mycurs = myconn.cursor() try: # do things with mycurs and my_other_parameters finally: mycurs.close() myconn.commit() # more of the same ... def main(): conn = sqlite3.connect('path/to/my/database') try: one_of_my_functions(conn, params) # more of the same finally: conn.close() if __name__ == "__main__": main() Or, if your program gets bigger, you might start and stop a connection inside a function instead of keeping one connection open for all of the application. HTH Sibylle From steve+comp.lang.python at pearwood.info Sat Oct 18 06:53:04 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 18 Oct 2014 21:53:04 +1100 Subject: Is there an easy way to control indents in Python References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> Simon Kennedy wrote: > On Wednesday, 15 October 2014 20:31:15 UTC+1, Ian wrote: >> I agree. I very rarely use blank lines inside functions. As I see it, >> if you feel you need a blank line for separation within a function, >> that's an indication your function is overly complex and should be >> broken up. > > Whereas I feel that if I wanted to write code which looked like that I'd > have learnt/learned Perl ;-) I'm curious what aspect of idiomatic Perl code you are referring to. When people talk about Perl code dismissively, I normally think of three things: - excessively long one-liners; - excessive use of symbols and sigils ("line noise"); - "More Than One [Thousand] Ways To Do It" Are you suggesting that Perl functions tend to be too small? What do you consider "too small"? -- Steven From alain at dpt-info.u-strasbg.fr Sat Oct 18 07:15:56 2014 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Sat, 18 Oct 2014 13:15:56 +0200 Subject: your mail References: <20141017104316.GA49644@cskk.homeip.net> Message-ID: <87ppdp39xv.fsf@dpt-info.u-strasbg.fr> Terry Reedy writes: > On 10/17/2014 6:43 AM, Cameron Simpson wrote: >> On 17Oct2014 11:45, Dhananjay wrote: > >>> 2.1576318858 -1.8651195165 4.2333428278 >>> ... >>> (total of 200 lines) >>> >>> Columns 1,2,3 corresponds to x,y,z axis data points. > >> for line in open('flooding-psiphi.dat','r'): >> line = line.split() >> xs.append(float(line[0])) >> ys.append(float(line[1])) >> zs.append(float(line[2])) > > A further refinement: > for line in open('flooding-psiphi.dat','r'): > x, y, z = map(float, line.split()) > xs.append(x) > ys.append(y) > zs.append(z) Or even: xs,ys,zs = zip(*[ map(float,line.split()) for line in open('flooding-psiphi.dat','r') ]) You get tuples, though. Use map(list,zip(...)) if you need lists. Easy to update when you move to 4D data... -- Alain. From gandalf at shopzeus.com Sat Oct 18 06:35:12 2014 From: gandalf at shopzeus.com (=?ISO-8859-1?Q?Nagy_L=E1szl=F3_Zsolt?=) Date: Sat, 18 Oct 2014 12:35:12 +0200 Subject: pyserial on freebsd 10.10 i386 [SOLVED] In-Reply-To: <5442301E.9060205@shopzeus.com> References: <5442301E.9060205@shopzeus.com> Message-ID: <54424260.6050308@shopzeus.com> The port parameter of serial.Serial should be /dev/ttyu0 instead of COM1, and /dev/ttyu1 instead of COM2. Strangely, pyserial will accept the number 0, but then it tries to open a device that exists on Linux only... Anyway, problem solved. From __peter__ at web.de Sat Oct 18 09:03:08 2014 From: __peter__ at web.de (Peter Otten) Date: Sat, 18 Oct 2014 15:03:08 +0200 Subject: your mail References: <20141017104316.GA49644@cskk.homeip.net> <87ppdp39xv.fsf@dpt-info.u-strasbg.fr> Message-ID: Alain Ketterlin wrote: > Terry Reedy writes: > >> On 10/17/2014 6:43 AM, Cameron Simpson wrote: >>> On 17Oct2014 11:45, Dhananjay wrote: >> >>>> 2.1576318858 -1.8651195165 4.2333428278 >>>> ... >>>> (total of 200 lines) >>>> >>>> Columns 1,2,3 corresponds to x,y,z axis data points. >> >>> for line in open('flooding-psiphi.dat','r'): >>> line = line.split() >>> xs.append(float(line[0])) >>> ys.append(float(line[1])) >>> zs.append(float(line[2])) >> >> A further refinement: >> for line in open('flooding-psiphi.dat','r'): >> x, y, z = map(float, line.split()) >> xs.append(x) >> ys.append(y) >> zs.append(z) > > Or even: > > xs,ys,zs = zip(*[ map(float,line.split()) > for line in open('flooding-psiphi.dat','r') ]) > > You get tuples, though. Use map(list,zip(...)) if you need lists. Easy > to update when you move to 4D data... Given the context (the script uses numpy) there is another option: xs, ys, zs = numpy.loadtxt('flooding-psiphi.dat').T There may also be a way to feed the array to matplotlib without breaking it into the three columns... From nobody at nowhere.invalid Sat Oct 18 12:55:19 2014 From: nobody at nowhere.invalid (Nobody) Date: Sat, 18 Oct 2014 17:55:19 +0100 Subject: Flush stdin References: Message-ID: On Fri, 17 Oct 2014 12:38:54 +0100, Empty Account wrote: > I am using netcat to listen to a port and python to read stdin and print > to the console. > > nc -l 2003 | python print_metrics.py > > sys.stdin.flush() doesn?t seem to flush stdin, You can't "flush" an input stream. > so I am using the termios module. > I am receiving this exception > termios.error: (25, 'Inappropriate ioctl for device') termios only works on terminals, not pipes. It's a safe bet that your problem is that "nc" isn't flushing its stdout after each line (this is the default behaviour for stdio streams which don't correspond to a terminal). Check whether "nc" has a flag to line-buffer its output. If it doesn't, the simplest solution is probably to write a Python script which creates a pseudo-tty (using the "pty" module) and executes "nc" with its stdout associated with the pty. From python.list at tim.thechases.com Sat Oct 18 13:32:07 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 18 Oct 2014 12:32:07 -0500 Subject: Flush stdin In-Reply-To: References: Message-ID: <20141018123207.51459a4c@bigbox.christie.dr> On 2014-10-18 17:55, Nobody wrote: > On Fri, 17 Oct 2014 12:38:54 +0100, Empty Account wrote: > > > I am using netcat to listen to a port and python to read stdin > > and print to the console. > > > > nc -l 2003 | python print_metrics.py > > > > sys.stdin.flush() doesn?t seem to flush stdin, > > You can't "flush" an input stream. You can't flush it, but you can make it unbuffered. You can either force python to use unbuffered stdio: python -u myfile.py or you can get an unbuffered handle to the file import os, sys buffer_size = 1 new_stdin = os.fdopen(sys.stdin.fileno(), 'r', buffer_size) for c in new_stdin: do_something(c) though based on my reading, the first method works with both Py2 and Py3k while the second method doesn't reliably work in Py3k. -tkc From python at mrabarnett.plus.com Sat Oct 18 13:55:04 2014 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 18 Oct 2014 18:55:04 +0100 Subject: Flush stdin In-Reply-To: References: Message-ID: <5442A978.3020205@mrabarnett.plus.com> On 2014-10-18 17:55, Nobody wrote: > On Fri, 17 Oct 2014 12:38:54 +0100, Empty Account wrote: > >> I am using netcat to listen to a port and python to read stdin and print >> to the console. >> >> nc -l 2003 | python print_metrics.py >> >> sys.stdin.flush() doesn?t seem to flush stdin, > > You can't "flush" an input stream. > [snip] Flushing an input stream means (or could mean) discarding any data that's currently in the buffer. From ryanshuell at gmail.com Sat Oct 18 15:54:45 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Sat, 18 Oct 2014 12:54:45 -0700 (PDT) Subject: Quick Question About Setting Up Pytz Message-ID: I downloaded PYTZ and put it here. C:\Python27\pytz Now, in the cmd window, I typed this: C:\Python27\pytz\setup.py A text file opens and nothing else happens. I thought it was supposed to install the PYTZ library. What am I doing wrong? From joel.goldstick at gmail.com Sat Oct 18 16:01:17 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 18 Oct 2014 16:01:17 -0400 Subject: Quick Question About Setting Up Pytz In-Reply-To: References: Message-ID: On Sat, Oct 18, 2014 at 3:54 PM, ryguy7272 wrote: > I downloaded PYTZ and put it here. > C:\Python27\pytz > > Now, in the cmd window, I typed this: > C:\Python27\pytz\setup.py > > A text file opens and nothing else happens. I thought it was supposed to install the PYTZ library. > > What am I doing wrong? > -- > https://mail.python.org/mailman/listinfo/python-list have you tried: python c:\Python27/pytz/setup.py -- Joel Goldstick http://joelgoldstick.com From ryanshuell at gmail.com Sat Oct 18 16:00:23 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Sat, 18 Oct 2014 13:00:23 -0700 (PDT) Subject: Question about PANDAS Message-ID: I'm trying to install Pandas. I went to this link. https://pypi.python.org/pypi/pandas/0.14.1/#downloads I downloaded this: pandas-0.14.1.win32-py2.7.exe (md5) I have Python27 installed. So, I run the executable and re-run my Python script and I get the same error as before. Traceback (most recent call last): File "C:/Python27/stock_data.py", line 3, in import pandas as pd ImportError: No module named pandas I thought I just installed it! Isn't that what the executable is for? It seems like 100% of my errors are with uninstalled libraries. I don't understand why there are so, so, so many dependencies running Python. Also, I don't understand why something isn't installed, right after I just installed it. Can someone please explain the logic to me? Thanks. From breamoreboy at yahoo.co.uk Sat Oct 18 16:20:43 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 18 Oct 2014 21:20:43 +0100 Subject: Quick Question About Setting Up Pytz In-Reply-To: References: Message-ID: On 18/10/2014 20:54, ryguy7272 wrote: > I downloaded PYTZ and put it here. > C:\Python27\pytz > > Now, in the cmd window, I typed this: > C:\Python27\pytz\setup.py > > A text file opens and nothing else happens. I thought it was supposed to install the PYTZ library. > > What am I doing wrong? > You will end up confusing yourself very quickly if you insist on placing files in c:\Python27. Please put them anywhere except that spot, say in downloads or on the desktop. Let's assume your desktop is here c:\Users\ryguy7272\Desktop. Open a cmd window then cd c:\Users\ryguy7272\Desktop setup.py install should work if and only if you have the file types and file associations correctly set, please see https://docs.python.org/2/using/windows.html#executing-scripts Better still take the hard work out of it by getting pip by following the instructions here http://pip.readthedocs.org/en/latest/installing.html -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From cs at zip.com.au Sat Oct 18 17:01:11 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 19 Oct 2014 08:01:11 +1100 Subject: Flush stdin In-Reply-To: References: Message-ID: <20141018210111.GA33086@cskk.homeip.net> On 18Oct2014 17:55, Nobody wrote: >On Fri, 17 Oct 2014 12:38:54 +0100, Empty Account wrote: >> I am using netcat to listen to a port and python to read stdin and print >> to the console. >> >> nc -l 2003 | python print_metrics.py >> >> sys.stdin.flush() doesn?t seem to flush stdin, > >You can't "flush" an input stream. Sure you can. Most streams are read through an API which buffers. That buffer can be discarded. I'm not sure it is what the OP needs, but it is not a nonsensical idea. Cheers, Cameron Simpson I've seen things you people wouldn't believe. Attack ships on fire off the shoulder of Orion. I've watched C-beams glitter in the dark near the Tannhauser Gate. All these memories will be lost in time, like tears in rain. - Roy Baty, _Blade Runner_ From tjreedy at udel.edu Sat Oct 18 18:35:17 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 18 Oct 2014 18:35:17 -0400 Subject: Flush stdin In-Reply-To: <20141018210111.GA33086@cskk.homeip.net> References: <20141018210111.GA33086@cskk.homeip.net> Message-ID: On 10/18/2014 5:01 PM, Cameron Simpson wrote: > On 18Oct2014 17:55, Nobody wrote: >> On Fri, 17 Oct 2014 12:38:54 +0100, Empty Account wrote: >>> I am using netcat to listen to a port and python to read stdin and print >>> to the console. >>> >>> nc -l 2003 | python print_metrics.py >>> >>> sys.stdin.flush() doesn?t seem to flush stdin, >> >> You can't "flush" an input stream. > Sure you can. You are collectively confusing three different meaning of 'flush'. Python and its docs are the best authority on what python can and cannot do. One can "call .flush() on an imput stream" (meaning 1). >>> import sys >>> sys.stdin.flush() >>> However, one cannot "empty the steam buffer by calling .flush()" (meaning 2). " class IOBase ... flush() Flush the write buffers of the stream if applicable. This does nothing for read-only and non-blocking streams." > Most streams are read through an API which buffers. That > buffer can be discarded. But one can "empty and discard the buffer" (meaning 3) with stream.read() And, of course, an 'input stream' 'down here' is an 'output stream' 'up there, where ever' and one can 'flush' pending output into the stream so that it can be read here. -- Terry Jan Reedy From nobody at nowhere.invalid Sat Oct 18 21:11:56 2014 From: nobody at nowhere.invalid (Nobody) Date: Sun, 19 Oct 2014 02:11:56 +0100 Subject: Flush stdin References: Message-ID: On Sat, 18 Oct 2014 12:32:07 -0500, Tim Chase wrote: > On 2014-10-18 17:55, Nobody wrote: >> On Fri, 17 Oct 2014 12:38:54 +0100, Empty Account wrote: >> >> > I am using netcat to listen to a port and python to read stdin and >> > print to the console. >> > >> > nc -l 2003 | python print_metrics.py >> > >> > sys.stdin.flush() doesn?t seem to flush stdin, >> >> You can't "flush" an input stream. > > You can't flush it, but you can make it unbuffered. You can either force > python to use unbuffered stdio: [snipped] None of this helps in any way, as it's not the behaviour of the Python script which is causing the problem, but that "nc" is (probably) buffering its output, so the data isn't passed to the OS (let alone to the Python script) in a timely manner. Once the "nc" process actually write()s the data to its standard output (i.e. desriptor 1, not the "stdout" FILE*), it will be available to the Python script immediately thereafter without requiring any low-level tweaks. From rosuav at gmail.com Sat Oct 18 21:23:00 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 19 Oct 2014 12:23:00 +1100 Subject: Flush stdin In-Reply-To: References: Message-ID: On Fri, Oct 17, 2014 at 10:38 PM, Empty Account wrote: > I am using netcat to listen to a port and python to read stdin and print to > the console. > > nc -l 2003 | python print_metrics.py After lengthy discussion about what it means to flush stdin, I think it's high time someone asked the question: Why not skip nc altogether, and have your Python program do its own socket work? Then you don't have to worry about stream flushing at all. ChrisA From drsalists at gmail.com Sat Oct 18 21:34:51 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Sat, 18 Oct 2014 18:34:51 -0700 Subject: Flush stdin In-Reply-To: References: Message-ID: On Sat, Oct 18, 2014 at 6:11 PM, Nobody wrote: > On Sat, 18 Oct 2014 12:32:07 -0500, Tim Chase wrote: > >> On 2014-10-18 17:55, Nobody wrote: >>> On Fri, 17 Oct 2014 12:38:54 +0100, Empty Account wrote: >>> >>> > I am using netcat to listen to a port and python to read stdin and >>> > print to the console. >>> > >>> > nc -l 2003 | python print_metrics.py >>> > >>> > sys.stdin.flush() doesn?t seem to flush stdin, >>> >>> You can't "flush" an input stream. >> >> You can't flush it, but you can make it unbuffered. You can either force >> python to use unbuffered stdio: > > [snipped] > > None of this helps in any way, as it's not the behaviour of the Python > script which is causing the problem, but that "nc" is (probably) buffering > its output, so the data isn't passed to the OS (let alone to the Python > script) in a timely manner. Agreed. > Once the "nc" process actually write()s the data to its standard > output (i.e. desriptor 1, not the "stdout" FILE*) I'm not sure why you're excluding stdout, but even if nc is using filedes 1 instead of FILE * stdout, isn't it kind of irrelevant? > it will be available to > the Python script immediately thereafter without requiring any low-level > tweaks. Which, on a pipe, generally means either the buffer filled and needed to be passed along to make room, or the process exited. I'd probably rewrite just enough nc in Python to make it so you don't need to depend on a pipe (example: http://stromberg.dnsalias.org/~strombrg/pnetcat.html), but if you're on *ix you could try http://ftp.sunet.se/pub/usenet/ftp.uu.net/comp.sources.unix/volume23/pty/ in an effort to persuade nc to think that it's on a tty and hence should output line buffered data instead of block buffered - despite being on a pipe in reality. HTH. From drsalists at gmail.com Sat Oct 18 21:42:00 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Sat, 18 Oct 2014 18:42:00 -0700 Subject: Flush stdin In-Reply-To: References: Message-ID: On Sat, Oct 18, 2014 at 6:34 PM, Dan Stromberg wrote: >> Once the "nc" process actually write()s the data to its standard >> output (i.e. desriptor 1, not the "stdout" FILE*) > I'm not sure why you're excluding stdout, but even if nc is using > filedes 1 instead of FILE * stdout, isn't it kind of irrelevant? On further reflection, isn't it stdio that does the varied buffering, and filedes 1 that's always unbuffered? IOW, the OP might wish nc was using 1, but it probably can't be given what they're seeing. From ryanshuell at gmail.com Sat Oct 18 22:44:28 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Sat, 18 Oct 2014 19:44:28 -0700 (PDT) Subject: Quick Question About Setting Up Pytz In-Reply-To: References: Message-ID: On Saturday, October 18, 2014 3:55:02 PM UTC-4, ryguy7272 wrote: > I downloaded PYTZ and put it here. > > C:\Python27\pytz > > > > Now, in the cmd window, I typed this: > > C:\Python27\pytz\setup.py > > > > A text file opens and nothing else happens. I thought it was supposed to install the PYTZ library. > > > > What am I doing wrong? Thanks Mark. That makes sense. I moved the folder to the desktop and I just tried that: C:\Users\Ryan\Desktop\pytz>setup.py install So, when I run it, the setup.py text file opens. Nothing runs; nothing installs. This makes no sense whatsoever. If I tell a program to install something, it should install something. It should not pop open a text file. I'll probably give it until the end of the year, and start learning Chinese. There's other things I want to do with my time. I know 10 programming languages. I thought it would be fun to learn Python, but after 2 months, I still can't run a single line of code. This language makes no sense whatsoever, and it never does anything that you tell it to do. From rosuav at gmail.com Sat Oct 18 22:49:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 19 Oct 2014 13:49:01 +1100 Subject: Quick Question About Setting Up Pytz In-Reply-To: References: Message-ID: On Sun, Oct 19, 2014 at 1:44 PM, ryguy7272 wrote: > I'll probably give it until the end of the year, and start learning Chinese. There's other things I want to do with my time. I know 10 programming languages. I thought it would be fun to learn Python, but after 2 months, I still can't run a single line of code. This language makes no sense whatsoever, and it never does anything that you tell it to do. > Try learning Python itself, rather than playing around with extension packages like pytz. You're having trouble installing add-ons - that's like saying "Computers are total rubbish, I bought this fancy new ISA card and I can't make it work!". Start with what you have, and worry about the extra complexities later. ChrisA From ben+python at benfinney.id.au Sat Oct 18 22:50:18 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 19 Oct 2014 13:50:18 +1100 Subject: Quick Question About Setting Up Pytz References: Message-ID: <85ppdon579.fsf@benfinney.id.au> ryguy7272 writes: > So, when I run it, the setup.py text file opens. Nothing runs; nothing > installs. You have somehow (either manually, or by answering a question to some program) associated the ?.py? suffix with ?Open this file in my text editor?. That's fine, but it means that if you don't want to edit the file but instead want to execute it, you need to *explicitly* start Python: python /whatever/path/to/setup.py install > This makes no sense whatsoever. This is an issue with your operating system, so I would hope you can learn more about that to distinguish what is causing your frustration :-) -- \ ?I got an answering machine for my phone. Now when someone | `\ calls me up and I'm not home, they get a recording of a busy | _o__) signal.? ?Steven Wright | Ben Finney From ben+python at benfinney.id.au Sat Oct 18 22:54:10 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 19 Oct 2014 13:54:10 +1100 Subject: Quick Question About Setting Up Pytz References: Message-ID: <85iojgn50t.fsf@benfinney.id.au> Chris Angelico writes: > Try learning Python itself, rather than playing around with extension > packages like pytz. To be fair, ?You need to install ?pytz? to work correctly with date and time values? is correct advice. If the OP doesn't install it early, then works with timestamps, problems are inevitable ? at which point ?oh, you needed to do that first? will be inevitable. It's lose?lose. It's a sad fact that MS Windows has completely useless timezone support, and this ?install a third-party package? hurdle is a cost that is paid by all people trying to set up Python on MS Windows. -- \ ?Nothing is more sacred than the facts.? ?Sam Harris, _The End | `\ of Faith_, 2004 | _o__) | Ben Finney From rosuav at gmail.com Sat Oct 18 23:10:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 19 Oct 2014 14:10:53 +1100 Subject: Quick Question About Setting Up Pytz In-Reply-To: <85iojgn50t.fsf@benfinney.id.au> References: <85iojgn50t.fsf@benfinney.id.au> Message-ID: On Sun, Oct 19, 2014 at 1:54 PM, Ben Finney wrote: > Chris Angelico writes: > >> Try learning Python itself, rather than playing around with extension >> packages like pytz. > > To be fair, ?You need to install ?pytz? to work correctly with date and > time values? is correct advice. If the OP doesn't install it early, then > works with timestamps, problems are inevitable ? at which point ?oh, you > needed to do that first? will be inevitable. It's lose?lose. > > It's a sad fact that MS Windows has completely useless timezone support, > and this ?install a third-party package? hurdle is a cost that is paid > by all people trying to set up Python on MS Windows. That's a rough business to be in... I mean... that's unfortunate. However, I'd still advise anyone to learn the language itself first, even if that means a rule like "avoid working with international or historical time". There are plenty of other things Python can do, even just with a basic Windows installation. ChrisA From rustompmody at gmail.com Sat Oct 18 23:16:05 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 18 Oct 2014 20:16:05 -0700 (PDT) Subject: Quick Question About Setting Up Pytz In-Reply-To: References: Message-ID: <1d9290de-e6a0-4591-9163-eab19771a68c@googlegroups.com> On Sunday, October 19, 2014 8:25:53 AM UTC+5:30, Ben Finney wrote: > Chris Angelico writes: > > Try learning Python itself, rather than playing around with extension > > packages like pytz. > To be fair, "You need to install 'pytz' to work correctly with date and > time values" is correct advice. If the OP doesn't install it early, then > works with timestamps, problems are inevitable -- at which point "oh, you > needed to do that first" will be inevitable. It's lose-lose. Yes > It's a sad fact that MS Windows has completely useless timezone support, > and this "install a third-party package" hurdle is a cost that is paid > by all people trying to set up Python on MS Windows. About MS-lacunae Ive nothing to say [Just head over to a debian list like users or vote or.. and witness the riot going on over systemd... Hard to believe all's right in Linux-land] As for this OP and similar problems -- yes python is in a peculiar position. Because of 'batteries included' beginners can do powerful stuff. However sometimes the batteries need to be supplemented. And then there's a problem -- its not clear whether - the beginner is having classic noob problems. Expert just needs to tweak a command a bit and he's sailing - the beginner is in somewhat uncharted (research-needed) land -- charting the route between mutually complementary AND competing setup tools I believe python must be some sort of record setter in this that o pip is a replacement for easy_install o you install pip with easy_install !! From breamoreboy at yahoo.co.uk Sun Oct 19 10:19:31 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 19 Oct 2014 15:19:31 +0100 Subject: Question about PANDAS In-Reply-To: References: Message-ID: On 18/10/2014 21:00, ryguy7272 wrote: > I'm trying to install Pandas. I went to this link. > https://pypi.python.org/pypi/pandas/0.14.1/#downloads > > I downloaded this: pandas-0.14.1.win32-py2.7.exe (md5) > I have Python27 installed. > > So, I run the executable and re-run my Python script and I get the same error as before. > > > Traceback (most recent call last): > File "C:/Python27/stock_data.py", line 3, in > import pandas as pd > ImportError: No module named pandas > > I thought I just installed it! Isn't that what the executable is for? It seems like 100% of my errors are with uninstalled libraries. I don't understand why there are so, so, so many dependencies running Python. Also, I don't understand why something isn't installed, right after I just installed it. > > Can someone please explain the logic to me? > > Thanks. > Have you actually run any code from the Python tutorial yet? You can do lots of things with Python that require no third party libraries. In fact many questions here go "I need a solution to this that must be in the stdlib". It strikes me that you're trying to enter an Iron Man competition before you can crawl. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From joel.goldstick at gmail.com Sun Oct 19 10:48:36 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 19 Oct 2014 10:48:36 -0400 Subject: Question about PANDAS In-Reply-To: References: Message-ID: On Sun, Oct 19, 2014 at 10:19 AM, Mark Lawrence wrote: > On 18/10/2014 21:00, ryguy7272 wrote: >> >> I'm trying to install Pandas. I went to this link. >> https://pypi.python.org/pypi/pandas/0.14.1/#downloads >> >> I downloaded this: pandas-0.14.1.win32-py2.7.exe (md5) >> I have Python27 installed. >> >> So, I run the executable and re-run my Python script and I get the same >> error as before. >> >> >> Traceback (most recent call last): >> File "C:/Python27/stock_data.py", line 3, in >> import pandas as pd >> ImportError: No module named pandas >> What messages did you get when you run the installer? Most people use pip to install python packages Are you writing code and putting it in C:/Python27/ ? isn't that where python is installed. You should write your code in some directory under your user tree. >> I thought I just installed it! Isn't that what the executable is for? It >> seems like 100% of my errors are with uninstalled libraries. I don't >> understand why there are so, so, so many dependencies running Python. Also, >> I don't understand why something isn't installed, right after I just >> installed it. >> >> Can someone please explain the logic to me? >> >> Thanks. >> > > Have you actually run any code from the Python tutorial yet? You can do > lots of things with Python that require no third party libraries. In fact > many questions here go "I need a solution to this that must be in the > stdlib". It strikes me that you're trying to enter an Iron Man competition > before you can crawl. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From invalid at invalid.invalid Sun Oct 19 11:06:07 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Sun, 19 Oct 2014 15:06:07 +0000 (UTC) Subject: pyserial on freebsd 10.10 i386 [SOLVED] References: <5442301E.9060205@shopzeus.com> Message-ID: On 2014-10-18, Nagy L?szl? Zsolt wrote: > Strangely, pyserial will accept the number 0, but then it tries to open > a device that exists on Linux only... I'm sure Chris would be happy to accept a patch fixing that problem. -- Grant From humphreys404 at gmail.com Sun Oct 19 11:29:00 2014 From: humphreys404 at gmail.com (humphreys404 at gmail.com) Date: Sun, 19 Oct 2014 08:29:00 -0700 (PDT) Subject: BASIC vs Python In-Reply-To: References: Message-ID: <7ec034af-0e47-4656-8e33-9e0c54fbe70f@googlegroups.com> On Thursday, December 16, 2004 6:36:18 PM UTC, abisofile wrote: > hi > > I'm new to programming.I've try a little BASIC so I want ask since > Python is also interpreted lang if it's similar to BASIC. Hi. I want to know if SMALL basic is the same as/like python. From joel.goldstick at gmail.com Sun Oct 19 11:36:41 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 19 Oct 2014 11:36:41 -0400 Subject: BASIC vs Python In-Reply-To: <7ec034af-0e47-4656-8e33-9e0c54fbe70f@googlegroups.com> References: <7ec034af-0e47-4656-8e33-9e0c54fbe70f@googlegroups.com> Message-ID: On Sun, Oct 19, 2014 at 11:29 AM, wrote: > On Thursday, December 16, 2004 6:36:18 PM UTC, abisofile wrote: >> hi >> >> I'm new to programming.I've try a little BASIC so I want ask since >> Python is also interpreted lang if it's similar to BASIC. > > Hi. > I want to know if SMALL basic is the same as/like python. > -- > https://mail.python.org/mailman/listinfo/python-list Much richer language and more modern. Easy to learn (but you keep learning more!) -- Joel Goldstick http://joelgoldstick.com From rosuav at gmail.com Sun Oct 19 11:42:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 20 Oct 2014 02:42:45 +1100 Subject: BASIC vs Python In-Reply-To: <7ec034af-0e47-4656-8e33-9e0c54fbe70f@googlegroups.com> References: <7ec034af-0e47-4656-8e33-9e0c54fbe70f@googlegroups.com> Message-ID: On Mon, Oct 20, 2014 at 2:29 AM, wrote: > On Thursday, December 16, 2004 6:36:18 PM UTC, abisofile wrote: >> hi >> >> I'm new to programming.I've try a little BASIC so I want ask since >> Python is also interpreted lang if it's similar to BASIC. > > Hi. > I want to know if SMALL basic is the same as/like python. You're responding to something from ten years ago. You'll do better to ask your own question on its own merits; a lot can happen in ten years. What's "SMALL basic"? (I found two languages of approximately that name, one by Microsoft and the other hosted on sourceforge. And there may be others.) It won't be "the same as" Python; if it were, one language or the other wouldn't exist. And "like Python" is a matter of degree and area - Pike is very like Python in semantics, but very unlike Python in syntax; REXX has a vaguely similar syntactic style, but extremely different semantics; ECMAScript has a few similarities, though not that many; etcetera. Are you familiar with some other language(s) and wanting to learn Python, or familiar with Python and wanting to learn this other language? Just for reference, by the way: being interpreted is almost completely non-significant. It's a feature of an implementation, not a language; plus, pretty much every modern interpreted language is first compiled into some kind of byte-code. (The only one I can think of that isn't would be some forms of shell script or batch file; I do remember editing batch files under DOS and having the changes happen live, not sure if that's true under any of the modern Windowses.) There are Python compilers (eg Cython), and I've seen C interpreters, so I think that proves there's no real difference there :) ChrisA From breamoreboy at yahoo.co.uk Sun Oct 19 11:55:01 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 19 Oct 2014 16:55:01 +0100 Subject: pyserial on freebsd 10.10 i386 [SOLVED] In-Reply-To: References: <5442301E.9060205@shopzeus.com> Message-ID: On 19/10/2014 16:06, Grant Edwards wrote: > On 2014-10-18, Nagy L?szl? Zsolt wrote: > >> Strangely, pyserial will accept the number 0, but then it tries to open >> a device that exists on Linux only... > > I'm sure Chris would be happy to accept a patch fixing that problem. > Sadly to some people a patch is a thing that mends your flat tyre or goes over your eye. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From joel.goldstick at gmail.com Sun Oct 19 16:57:17 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 19 Oct 2014 16:57:17 -0400 Subject: Question about PANDAS In-Reply-To: References: Message-ID: On Sun, Oct 19, 2014 at 3:57 PM, Ryan Shuell wrote: > > Thanks guys. I just feel frustrated that I can't do something useful. > I'm reading all about dictionaries, and types, and touples. Then I read > about string manipulation and loops; two of my favorite things to do. Then > I read about logic: > -719 >= 833 > False > > That's great, but it's just not very useful for me. I thought I could use > Python to do screen scraping. Right now, I use R to do almost all my screen > scraping. I used to use Excel, but r is just light years easier to use, so > I'll go with that. I thought Python may be even easier to use than R, and > perhaps even more powerful too. However, since I picked up my first Python > book about 3 months ago, I seem to be learning all kinds of useless things, > and no practical things. When I find cool code samples online, I can't even > get them to run. Last week I found a small sample of code that supposedly > merges data from several text files in a folder into one single file. I > played with it for a couple hours, and never got it to work. In less than > 15 minutes, I could have done the merging task, using Excel, Access, VB.NET, > C#.NET, or even a batch file. So you have a lot of experience with Microsoft world. The Open Source world is a different slant. That might contribute to your frustration. I just looked up R, and I see it is for statistics, which is something you also seem to know about. I think there will come an 'aha' moment when python clicks for you. Or maybe not. Its a very well constructed language. Good luck, though. > > I guess I'll just keep reading these books. I have 10 books, and I'm most > of the way throguh 4 of them. So far, none are teaching me anything that I > could use in my role managing financial assets. Maybe something will click > soon. I hope so. > > Thanks again everyone. > > > On Sun, Oct 19, 2014 at 10:48 AM, Joel Goldstick > wrote: >> >> On Sun, Oct 19, 2014 at 10:19 AM, Mark Lawrence >> wrote: >> > On 18/10/2014 21:00, ryguy7272 wrote: >> >> >> >> I'm trying to install Pandas. I went to this link. >> >> https://pypi.python.org/pypi/pandas/0.14.1/#downloads >> >> >> >> I downloaded this: pandas-0.14.1.win32-py2.7.exe (md5) >> >> I have Python27 installed. >> >> >> >> So, I run the executable and re-run my Python script and I get the same >> >> error as before. >> >> >> >> >> >> Traceback (most recent call last): >> >> File "C:/Python27/stock_data.py", line 3, in >> >> import pandas as pd >> >> ImportError: No module named pandas >> >> >> >> What messages did you get when you run the installer? >> Most people use pip to install python packages >> Are you writing code and putting it in C:/Python27/ ? isn't that where >> python is installed. You should write your code in some directory >> under your user tree. >> >> >> >> I thought I just installed it! Isn't that what the executable is for? >> >> It >> >> seems like 100% of my errors are with uninstalled libraries. I don't >> >> understand why there are so, so, so many dependencies running Python. >> >> Also, >> >> I don't understand why something isn't installed, right after I just >> >> installed it. >> >> >> >> Can someone please explain the logic to me? >> >> >> >> Thanks. >> >> >> > >> > Have you actually run any code from the Python tutorial yet? You can do >> > lots of things with Python that require no third party libraries. In >> > fact >> > many questions here go "I need a solution to this that must be in the >> > stdlib". It strikes me that you're trying to enter an Iron Man >> > competition >> > before you can crawl. >> > >> > -- >> > My fellow Pythonistas, ask not what our language can do for you, ask >> > what you can do for our language. >> > >> > Mark Lawrence >> > >> > -- >> > https://mail.python.org/mailman/listinfo/python-list >> >> >> >> -- >> Joel Goldstick >> http://joelgoldstick.com >> -- >> https://mail.python.org/mailman/listinfo/python-list > > -- Joel Goldstick http://joelgoldstick.com From noblebell at gmail.com Sun Oct 19 19:22:27 2014 From: noblebell at gmail.com (Noble Bell) Date: Sun, 19 Oct 2014 16:22:27 -0700 (PDT) Subject: OS X Menubar in Tkinter Message-ID: I am using Python 3.4 on Mac OS X and Tinter 8.5. Does anyone have any code that they would share with me on how to remove the "Python" menu in the menubar at the top next to the "apple'? I would like to have the name of my program there instead and my menu. I can add menus but not sure how to do the special menubar. Any help would be appreciated. NB From nad at acm.org Sun Oct 19 20:49:09 2014 From: nad at acm.org (Ned Deily) Date: Sun, 19 Oct 2014 17:49:09 -0700 Subject: OS X Menubar in Tkinter References: Message-ID: In article , Noble Bell wrote: > I am using Python 3.4 on Mac OS X and Tinter 8.5. Does anyone have any code > that they would share with me on how to remove the "Python" menu in the > menubar at the top next to the "apple'? > > I would like to have the name of my program there instead and my menu. I can > add menus but not sure how to do the special menubar. Any help would be > appreciated. The name that shows up in the menu is derived by OS X from the application name in the executing application bundle. If you don't package your program up as an OS X application bundle, defaults will be used; in the case of Python OS X framework builds, Python provides a Python.app within the framework to allow the Python process to be automatically promoted to a full OS X gui process. Probably the simplest approach is to use py2app to create a double-clickable app with the name you want. There's an example in an answer to a similar question on Stackoverflow. And there are some old but still relevant details documented in the Tcl/TkAqua FAQ. https://pypi.python.org/pypi/py2app http://stackoverflow.com/questions/8695926/remove-default-python-submenu- with-tkinter-menu-on-mac-osx http://wiki.tcl.tk/12987 -- Ned Deily, nad at acm.org From flebber.crue at gmail.com Sun Oct 19 23:54:16 2014 From: flebber.crue at gmail.com (flebber) Date: Sun, 19 Oct 2014 20:54:16 -0700 (PDT) Subject: Question about PANDAS In-Reply-To: References: Message-ID: On Windows my advice would be to use the anaconda installer. Linux pip will work flawlessly. If you install anaconda full then you will have pandas as well as an ipython launcher installed. Sayth From cs at zip.com.au Sun Oct 19 23:56:17 2014 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 20 Oct 2014 14:56:17 +1100 Subject: Flush stdin In-Reply-To: References: Message-ID: <20141020035617.GA31327@cskk.homeip.net> On 18Oct2014 18:42, Dan Stromberg wrote: >On Sat, Oct 18, 2014 at 6:34 PM, Dan Stromberg wrote: >>> Once the "nc" process actually write()s the data to its standard >>> output (i.e. desriptor 1, not the "stdout" FILE*) >> I'm not sure why you're excluding stdout, but even if nc is using >> filedes 1 instead of FILE * stdout, isn't it kind of irrelevant? > >On further reflection, isn't it stdio that does the varied buffering, >and filedes 1 that's always unbuffered? IOW, the OP might wish nc was >using 1, but it probably can't be given what they're seeing. Traditionally, fd 1 (standard output, _generally_ associated with FILE *stdout), gets stdio buffering; line buffered for a terminal, block buffered otherwise. fd 2 (standard error, _generally_ associated with FILE *stderr) gets an unbuffered stdio stream by default. However, nc may well be behaving like "tail -f": always unbuffered. However, as I recall the OP seemed to want to "flush" the stream from nc to python. Even if nc itself does no buffering (handing data to the OS as soon as received, highly desirable for a tool like nc), the OS keeps a buffer for the pipeline between nc and python, and python itself keeps a buffer for sys.stdin. Both of those are candidates for some kind of flush/discard. IF (a big IF) that is what the OP really needs. Have we heard anything from the OP since this discussion took off? I think we need to better understand his/her use case. Cheers, Cameron Simpson Do you even know anything about perl? - AC replying to Tom Christiansen post From marko at pacujo.net Mon Oct 20 00:45:22 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Mon, 20 Oct 2014 07:45:22 +0300 Subject: Flush stdin References: Message-ID: <87a94rgxi5.fsf@elektro.pacujo.net> Cameron Simpson : > Even if nc itself does no buffering (handing data to the OS as soon as > received, highly desirable for a tool like nc), the OS keeps a buffer > for the pipeline between nc and python, Yes, there is a buffer associated with the pipe, but linux/unix never withholds any data from the reader. As soon as there is a single byte in the pipe buffer, the reader process becomes ready to run and read(2) on the pipe returns immediately. > and python itself keeps a buffer for sys.stdin. I found this comment in CPython's source code (pythonrun.c): /* stdin is always opened in buffered mode, first because it shouldn't make a difference in common use cases, second because TextIOWrapper depends on the presence of a read1() method which only exists on buffered streams. */ The solution is to use os.read(). Marko From rustompmody at gmail.com Mon Oct 20 01:12:22 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 19 Oct 2014 22:12:22 -0700 (PDT) Subject: Question about PANDAS In-Reply-To: References: Message-ID: <835650b5-5cab-4044-ab2d-7bf5e931420f@googlegroups.com> On Sun, Oct 19, 2014 at 3:57 PM, Ryan Shuell wrote: > > Thanks guys. I just feel frustrated that I can't do something useful. > I'm reading all about dictionaries, and types, and touples. Then I read > about string manipulation and loops; two of my favorite things to do. Then > I read about logic: > -719 >= 833 > False > > That's great, but it's just not very useful for me. I thought I could use > Python to do screen scraping. Right now, I use R to do almost all my screen > scraping. I used to use Excel, but r is just light years easier to use, so > I'll go with that. I thought Python may be even easier to use than R, and > perhaps even more powerful too. However, since I picked up my first Python > book about 3 months ago, I seem to be learning all kinds of useless things, > and no practical things. When I find cool code samples online, I can't even > get them to run. Last week I found a small sample of code that supposedly > merges data from several text files in a folder into one single file. I > played with it for a couple hours, and never got it to work. In less than > 15 minutes, I could have done the merging task, using Excel, Access, VB.NET, > C#.NET, or even a batch file. You have my sympathies. Most of what help you'll get here is 'inside-out': Start with small toys. Work slowly towards more realistic problems Many people (like you) would like to go the other way -- Start with trying to solve a real problem. Handle the small nitty-gritties as they arise. On and off Ive expressed a need in a similar direction eg https://mail.python.org/pipermail/python-list/2011-November/615522.html https://mail.python.org/pipermail/python-list/2011-May/603506.html https://mail.python.org/pipermail/python-list/2011-May/603635.html The problem with your approach is that its very system-specific >>> [1,2]+[3,4] [1, 2, 3, 4] will be the same on any python. Any OS. Any version. However installing a package will vary. And the best way of installing will vary widely. So its harder to help OTOH I will say this: Any learning requires some faith at least temporary and provisional. If you pick up some book which purports to educate on some subject and decide before opening it that - subject is bogus - author is a rogue etc etc you are not likely to get much out of it.? So it may irritate you to listen to the advice you get here to start baby-steps first. However if you dont listen, you are wasting time - most of all your own. ----------- ? Of course your suspicions may be true. Thats the fun of life! From greg.ewing at canterbury.ac.nz Mon Oct 20 02:47:38 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 20 Oct 2014 19:47:38 +1300 Subject: OS X Menubar in Tkinter In-Reply-To: References: Message-ID: Ned Deily wrote: > The name that shows up in the menu is derived by OS X from the > application name in the executing application bundle. I found a hackish way to change it at run time while working on PyGUI, but it requires using PyObjC: from Foundation import NSBundle def change_application_name(new_name): # Arrange for the application name to be used as the title # of the application menu. ns_bundle = NSBundle.mainBundle() if ns_bundle: ns_info = ns_bundle.localizedInfoDictionary() if not ns_info: ns_info = ns_bundle.infoDictionary() if ns_info: if ns_info['CFBundleName'] == "Python": ns_info['CFBundleName'] = new_name -- Greg From ryanshuell at gmail.com Sun Oct 19 15:57:27 2014 From: ryanshuell at gmail.com (Ryan Shuell) Date: Sun, 19 Oct 2014 15:57:27 -0400 Subject: Question about PANDAS In-Reply-To: References: Message-ID: Thanks guys. I just feel frustrated that I can't do something useful. I'm reading all about dictionaries, and types, and touples. Then I read about string manipulation and loops; two of my favorite things to do. Then I read about logic: -719 >= 833 False That's great, but it's just not very useful for me. I thought I could use Python to do screen scraping. Right now, I use R to do almost all my screen scraping. I used to use Excel, but r is just light years easier to use, so I'll go with that. I thought Python may be even easier to use than R, and perhaps even more powerful too. However, since I picked up my first Python book about 3 months ago, I seem to be learning all kinds of useless things, and no practical things. When I find cool code samples online, I can't even get them to run. Last week I found a small sample of code that supposedly merges data from several text files in a folder into one single file. I played with it for a couple hours, and never got it to work. In less than 15 minutes, I could have done the merging task, using Excel, Access, VB.NET, C#.NET, or even a batch file. I guess I'll just keep reading these books. I have 10 books, and I'm most of the way throguh 4 of them. So far, none are teaching me anything that I could use in my role managing financial assets. Maybe something will click soon. I hope so. Thanks again everyone. On Sun, Oct 19, 2014 at 10:48 AM, Joel Goldstick wrote: > On Sun, Oct 19, 2014 at 10:19 AM, Mark Lawrence > wrote: > > On 18/10/2014 21:00, ryguy7272 wrote: > >> > >> I'm trying to install Pandas. I went to this link. > >> https://pypi.python.org/pypi/pandas/0.14.1/#downloads > >> > >> I downloaded this: pandas-0.14.1.win32-py2.7.exe (md5) > >> I have Python27 installed. > >> > >> So, I run the executable and re-run my Python script and I get the same > >> error as before. > >> > >> > >> Traceback (most recent call last): > >> File "C:/Python27/stock_data.py", line 3, in > >> import pandas as pd > >> ImportError: No module named pandas > >> > > What messages did you get when you run the installer? > Most people use pip to install python packages > Are you writing code and putting it in C:/Python27/ ? isn't that where > python is installed. You should write your code in some directory > under your user tree. > > > >> I thought I just installed it! Isn't that what the executable is for? > It > >> seems like 100% of my errors are with uninstalled libraries. I don't > >> understand why there are so, so, so many dependencies running Python. > Also, > >> I don't understand why something isn't installed, right after I just > >> installed it. > >> > >> Can someone please explain the logic to me? > >> > >> Thanks. > >> > > > > Have you actually run any code from the Python tutorial yet? You can do > > lots of things with Python that require no third party libraries. In > fact > > many questions here go "I need a solution to this that must be in the > > stdlib". It strikes me that you're trying to enter an Iron Man > competition > > before you can crawl. > > > > -- > > My fellow Pythonistas, ask not what our language can do for you, ask > > what you can do for our language. > > > > Mark Lawrence > > > > -- > > https://mail.python.org/mailman/listinfo/python-list > > > > -- > Joel Goldstick > http://joelgoldstick.com > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ryanshuell at gmail.com Sun Oct 19 16:18:41 2014 From: ryanshuell at gmail.com (Ryan Shuell) Date: Sun, 19 Oct 2014 16:18:41 -0400 Subject: Quick Question About Setting Up Pytz In-Reply-To: <1d9290de-e6a0-4591-9163-eab19771a68c@googlegroups.com> References: <1d9290de-e6a0-4591-9163-eab19771a68c@googlegroups.com> Message-ID: Ok, thanks everyone. I just need to spend more time with this stuff. It's definitely slow going. On Sat, Oct 18, 2014 at 11:16 PM, Rustom Mody wrote: > On Sunday, October 19, 2014 8:25:53 AM UTC+5:30, Ben Finney wrote: > > Chris Angelico writes: > > > > Try learning Python itself, rather than playing around with extension > > > packages like pytz. > > > To be fair, "You need to install 'pytz' to work correctly with date and > > time values" is correct advice. If the OP doesn't install it early, then > > works with timestamps, problems are inevitable -- at which point "oh, you > > needed to do that first" will be inevitable. It's lose-lose. > > Yes > > > It's a sad fact that MS Windows has completely useless timezone support, > > and this "install a third-party package" hurdle is a cost that is paid > > by all people trying to set up Python on MS Windows. > > About MS-lacunae Ive nothing to say > > [Just head over to a debian list like users or vote or.. and witness the > riot going on over systemd... Hard to believe all's right in Linux-land] > > As for this OP and similar problems -- yes python is in a peculiar > position. > Because of 'batteries included' beginners can do powerful stuff. > However sometimes the batteries need to be supplemented. > And then there's a problem -- its not clear whether > - the beginner is having classic noob problems. > Expert just needs to tweak a command a bit and he's sailing > - the beginner is in somewhat uncharted (research-needed) land -- charting > the route between mutually complementary AND competing setup tools > > I believe python must be some sort of record setter in this that > o pip is a replacement for easy_install > o you install pip with easy_install > > !! > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mailinglists at xgm.de Mon Oct 20 03:47:42 2014 From: mailinglists at xgm.de (Florian Lindner) Date: Mon, 20 Oct 2014 09:47:42 +0200 Subject: time.perf_counter in Python 2? Message-ID: Hello, I wrote a script that does some time measurements. It uses time.perf_counter() from Python 3 which works very well. Now I need to backport it to python 2. Docs say that time.clock() is way to go: time.clock() On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of ?processor time?, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms. On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond. But for me it always returns the almost same number, nothing time like: Python 2.7.3 (default, Feb 27 2014, 19:58:35) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.clock() 0.03 >>> time.clock() 0.03 >>> time.clock() 0.04 >>> time.clock() 0.04 What's wrong there? Thanks, Florian From rosuav at gmail.com Mon Oct 20 03:58:28 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 20 Oct 2014 18:58:28 +1100 Subject: time.perf_counter in Python 2? In-Reply-To: References: Message-ID: On Mon, Oct 20, 2014 at 6:47 PM, Florian Lindner wrote: > time.clock() > On Unix, return the current processor time as a floating point number > expressed in seconds. The precision, and in fact the very definition of the > meaning of ?processor time?, depends on that of the C function of the same > name, but in any case, this is the function to use for benchmarking Python > or timing algorithms. > > But for me it always returns the almost same number, nothing time like: You're doing practically no work in there. You're using almost no processor time - the interpreter's waiting for the user, not actually busy. If you create a busyloop, you'll see time.clock() go up roughly linearly: rosuav at sikorsky:~$ python Python 2.7.3 (default, Mar 13 2014, 11:03:55) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> def killtime(): ... start=time.time() ... end=time.clock()+1 ... while time.clock()>> killtime() 1.0048420429229736 >>> killtime() 1.004641056060791 >>> killtime() 1.0081689357757568 >>> killtime() 1.0019969940185547 >>> killtime() 1.0044770240783691 This function will do its best to waste one second of CPU time. As you see, it's taking pretty much exactly one second of wall time to do so (as measured by time.time()). At the end of a few of these runs, time.clock() will return a value that's fairly close to 1.0 times the number of executions of killtime(), as the other work Python's doing is insignificant by comparison. ChrisA From __peter__ at web.de Mon Oct 20 04:09:32 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 20 Oct 2014 10:09:32 +0200 Subject: time.perf_counter in Python 2? References: Message-ID: Florian Lindner wrote: > Hello, > > I wrote a script that does some time measurements. It uses > time.perf_counter() from Python 3 which works very well. Now I need to > backport it to python 2. > > Docs say that time.clock() is way to go: > > time.clock() > On Unix, return the current processor time as a floating point number > expressed in seconds. The precision, and in fact the very definition of > the meaning of ?processor time?, depends on that of the C function of the > same name, but in any case, this is the function to use for benchmarking > Python or timing algorithms. > > On Windows, this function returns wall-clock seconds elapsed since the > first call to this function, as a floating point number, based on the > Win32 function QueryPerformanceCounter(). The resolution is typically > better than one microsecond. > > But for me it always returns the almost same number, nothing time like: > > Python 2.7.3 (default, Feb 27 2014, 19:58:35) > [GCC 4.6.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import time >>>> time.clock() > 0.03 >>>> time.clock() > 0.03 >>>> time.clock() > 0.04 >>>> time.clock() > 0.04 > > > What's wrong there? While clock is not the recommended timer on Linux the granularity is still higher over here: >>> time.clock() 0.06874 >>> time.clock() 0.069221 >>> time.clock() 0.069782 >>> time.clock() 0.070309 That or you can type faster ;) Here's an excerpt from the 2.7 timeit.py: if sys.platform == "win32": # On Windows, the best timer is time.clock() default_timer = time.clock else: # On most other platforms the best timer is time.time() default_timer = time.time In Python3.4 this has become default_timer = time.perf_counter So I'd go with timeit.default_timer(). From breamoreboy at yahoo.co.uk Mon Oct 20 04:18:15 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 20 Oct 2014 09:18:15 +0100 Subject: Question about PANDAS In-Reply-To: References: Message-ID: On 19/10/2014 20:57, Ryan Shuell wrote: > > Thanks guys. I just feel frustrated that I can't do something useful. > I'm reading all about dictionaries, and types, and touples. Then I read > about string manipulation and loops; two of my favorite things to do. > Then I read about logic: > -719 >= 833 > False > > That's great, but it's just not very useful for me. I thought I could > use Python to do screen scraping. Right now, I use R to do almost all > my screen scraping. I used to use Excel, but r is just light years > easier to use, so I'll go with that. I thought Python may be even > easier to use than R, and perhaps even more powerful too. However, > since I picked up my first Python book about 3 months ago, I seem to be > learning all kinds of useless things, and no practical things. When I > find cool code samples online, I can't even get them to run. Last week > I found a small sample of code that supposedly merges data from several > text files in a folder into one single file. I played with it for a > couple hours, and never got it to work. In less than 15 minutes, I > could have done the merging task, using Excel, Access, VB.NET > , C#.NET, or even a batch file. > > I guess I'll just keep reading these books. I have 10 books, and I'm > most of the way throguh 4 of them. So far, none are teaching me > anything that I could use in my role managing financial assets. Maybe > something will click soon. I hope so. > > Thanks again everyone. > For screen scraping you need Beautiful Soup, but if you can't run anything yet and can't install anything yet what is the point? You can read as many books as you like, but until you understand the basics of Python and not other languages that you've previously used, you'll get precisely nowhere. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From breamoreboy at yahoo.co.uk Mon Oct 20 04:19:27 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 20 Oct 2014 09:19:27 +0100 Subject: Quick Question About Setting Up Pytz In-Reply-To: References: <1d9290de-e6a0-4591-9163-eab19771a68c@googlegroups.com> Message-ID: On 19/10/2014 21:18, Ryan Shuell wrote: > Ok, thanks everyone. I just need to spend more time with this stuff. > It's definitely slow going. > Please don't top post on this list, thank you. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From pecore at pascolo.net Mon Oct 20 04:30:14 2014 From: pecore at pascolo.net (giacomo boffi) Date: Mon, 20 Oct 2014 10:30:14 +0200 Subject: Question about PANDAS References: Message-ID: <87lhobb0tl.fsf@pascolo.net> Ryan Shuell writes: > Thanks guys.? I just feel frustrated that I can't do something useful. I had read many of your messages in the recent past, and I'm under the impression that your frustration has more to do with "Python the Infrastructure" rather than "Python the Language" my suggestions will somehow reiterate what was told you in previous threads, 1. scrap everything python from your hard disk and your registry, using unistall as far as possible 2. choose ONE flavour of python, either 2.7.x or 3.4.x - future is with 3.4, - most exaples you'll find were written (are still written...) for 2.7.x 3. the Pyton distribution from official sources contains piles of stuff (batteries included is the motto) but you seem interested in what is called "the python scientific stack" and this is not there. If you want at once the stdlib AND the great majority of the extra modules you're looking for AND an easy way to install other packages, there are quite a number of third party distributions that fit your ticket very well: entought, anaconda, active state, pyxy, all of them should be good enough but I'n not a Windows guy and I'm not be able to judge. Anyway, read or ask for advice on python windows distributions, chose one, _install using the_ _defaults_, STICK WITH THAT DISTRIBUTION, familiarizing with its infrastructure in terms of installing extra packages, setting virtual environments, using the development tools it offers etc in my very humble opinion, you are discomforted by the multiplicity of the solutions and your quest for the best one... choose one, maybe not the best one for you but trust me, it will be good enough! as soon as you'll be in good terms with Python the language and python the infrastructure, as presented to you by a single language version and a single 3rd party distribution, you will gather momentum in a very short time my best wishes, g From noblebell at gmail.com Mon Oct 20 06:47:01 2014 From: noblebell at gmail.com (Noble Bell) Date: Mon, 20 Oct 2014 03:47:01 -0700 (PDT) Subject: OS X Menubar in Tkinter In-Reply-To: References: Message-ID: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> On Sunday, October 19, 2014 7:49:34 PM UTC-5, Ned Deily wrote: > In article , > > Noble Bell wrote: > > > I am using Python 3.4 on Mac OS X and Tinter 8.5. Does anyone have any code > > > that they would share with me on how to remove the "Python" menu in the > > > menubar at the top next to the "apple'? > > > > > > I would like to have the name of my program there instead and my menu. I can > > > add menus but not sure how to do the special menubar. Any help would be > > > appreciated. > > > > The name that shows up in the menu is derived by OS X from the > > application name in the executing application bundle. If you don't > > package your program up as an OS X application bundle, defaults will be > > used; in the case of Python OS X framework builds, Python provides a > > Python.app within the framework to allow the Python process to be > > automatically promoted to a full OS X gui process. Probably the > > simplest approach is to use py2app to create a double-clickable app with > > the name you want. There's an example in an answer to a similar > > question on Stackoverflow. And there are some old but still relevant > > details documented in the Tcl/TkAqua FAQ. > > > > https://pypi.python.org/pypi/py2app > > http://stackoverflow.com/questions/8695926/remove-default-python-submenu- > > with-tkinter-menu-on-mac-osx > > http://wiki.tcl.tk/12987 > > > > -- > > Ned Deily, > > nad at acm.org Thank you. I will take a look at all that this afternoon. Seems like I might have seen that post on stack overflow but not for sure. From rustompmody at gmail.com Mon Oct 20 09:07:33 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 20 Oct 2014 06:07:33 -0700 (PDT) Subject: formal program verification in python? Message-ID: <0bf646e0-cc9d-4472-9412-accf221e2056@googlegroups.com> A colleague asked me if there were any formal program verification (or derivation) books which are python based. Sometimes known as 'Hoare/Dijkstra logic' I would be pleasantly surprised if there are! Still... In case anyone knows of any From jhibschman at gmail.com Mon Oct 20 09:41:17 2014 From: jhibschman at gmail.com (Johann Hibschman) Date: Mon, 20 Oct 2014 09:41:17 -0400 Subject: Question about PANDAS References: <87lhobb0tl.fsf@pascolo.net> Message-ID: giacomo boffi writes: > 2. choose ONE flavour of python, either 2.7.x or 3.4.x > - future is with 3.4, > - most exaples you'll find were written (are still written...) > for 2.7.x If you're interested in statistics (as comparisons to R suggest), I'd recommend anaconda. It comes with pandas built-in, for one. I'd also suggest the 3.4 version. Finally, just over the past few months, we've crossed over to where 3.4 is fully-functional in the anaconda distribution. (For a while statsmodels was the hold-out; matplotlib had problems before that. Now, though, all is good.) Cheers, Johann From sffjunkie at gmail.com Mon Oct 20 11:54:46 2014 From: sffjunkie at gmail.com (Simon Kennedy) Date: Mon, 20 Oct 2014 08:54:46 -0700 (PDT) Subject: Is there an easy way to control indents in Python In-Reply-To: <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Saturday, 18 October 2014 11:53:16 UTC+1, Steven D'Aprano wrote: > I'm curious what aspect of idiomatic Perl code you are referring to. When > people talk about Perl code dismissively, I normally think of three things: > > - excessively long one-liners; > - excessive use of symbols and sigils ("line noise"); > - "More Than One [Thousand] Ways To Do It" I'll preface the following by stating that I program in Python as a hobby and that the only programming I've done professionally was a few years ago now and consisted of a Visual Basic style language (Wonderware Intouch) and a piece of software called ABB Sattline. Not having ever attempted to go beyond even the basics of Perl, the aspect that causes me to refer to Perl 'dismissively' as well comment in this thread, is that I don't find Perl to be an aesthetically pleasing language and I consider Python functions which have no blank lines in them to be a small step towards Perl. Some people do not like Python's indentation rules but for me it's a large part of what draws me to program in Python. Spaces for indentation and blank lines are both aspects of how I like to program. I write in Python because I like to, not because I have to. I think the only reason I might code a function with no blank lines was if I was programming in a language that using blank lines caused it to run too slowly. > Are you suggesting that Perl functions tend to be too small? What do you > consider "too small"? No function is "too small". A one line function if it helps to describe the higher level code where it is called is fine by me. From ian.g.kelly at gmail.com Mon Oct 20 13:54:25 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 20 Oct 2014 11:54:25 -0600 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Oct 20, 2014 at 9:54 AM, Simon Kennedy wrote: > Not having ever attempted to go beyond even the basics of Perl, the aspect that causes me to refer to Perl 'dismissively' as well comment in this thread, is that I don't find Perl to be an aesthetically pleasing language and I consider Python functions which have no blank lines in them to be a small step towards Perl. > > Some people do not like Python's indentation rules but for me it's a large part of what draws me to program in Python. Spaces for indentation and blank lines are both aspects of how I like to program. > > I write in Python because I like to, not because I have to. > > I think the only reason I might code a function with no blank lines was if I was programming in a language that using blank lines caused it to run too slowly. So to be clear, I'm not talking about taking a function like this (contrived) example and just removing the blank line: def find_path(graphdata, start, end): edges = map(str.split, lines) graph = collections.defaultdict(list) for node1, node2, weight in edges: graph[node1].append((node[2], int(weight))) graph[node2].append((node[1], int(weight))) open_heap = [(0, (start,))] closed_set = set() while open_heap: cost, path = heapq.heappop(open_heap) current_node = path[-1] if current_node == end: return path if current_node in closed_set: continue for next_node, weight in graph[current_node]: heapq.heappush((cost + weight, path + (next_node,))) closed_set.add(current_node) else: raise ValueError("No path from start to end") Rather, I'm saying that where the blank line is should be the start of a new function. There would still be a blank line, just no longer inside the function. Now, maybe you think there should be more blank lines in the above, in which case we'll just have to disagree on that point. From ian.g.kelly at gmail.com Mon Oct 20 13:57:44 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 20 Oct 2014 11:57:44 -0600 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Oct 20, 2014 at 11:54 AM, Ian Kelly wrote: > On Mon, Oct 20, 2014 at 9:54 AM, Simon Kennedy wrote: >> Not having ever attempted to go beyond even the basics of Perl, the aspect that causes me to refer to Perl 'dismissively' as well comment in this thread, is that I don't find Perl to be an aesthetically pleasing language and I consider Python functions which have no blank lines in them to be a small step towards Perl. >> >> Some people do not like Python's indentation rules but for me it's a large part of what draws me to program in Python. Spaces for indentation and blank lines are both aspects of how I like to program. >> >> I write in Python because I like to, not because I have to. >> >> I think the only reason I might code a function with no blank lines was if I was programming in a language that using blank lines caused it to run too slowly. > > So to be clear, I'm not talking about taking a function like this > (contrived) example and just removing the blank line: > > def find_path(graphdata, start, end): > edges = map(str.split, lines) > graph = collections.defaultdict(list) > for node1, node2, weight in edges: > graph[node1].append((node[2], int(weight))) > graph[node2].append((node[1], int(weight))) > > open_heap = [(0, (start,))] > closed_set = set() > while open_heap: > cost, path = heapq.heappop(open_heap) > current_node = path[-1] > if current_node == end: > return path > if current_node in closed_set: > continue > for next_node, weight in graph[current_node]: > heapq.heappush((cost + weight, path + (next_node,))) > closed_set.add(current_node) > else: > raise ValueError("No path from start to end") > > Rather, I'm saying that where the blank line is should be the start of > a new function. There would still be a blank line, just no longer > inside the function. > > Now, maybe you think there should be more blank lines in the above, in > which case we'll just have to disagree on that point. By the way, I didn't test that at all, which is why I've spotted at least two bugs in it since sending the message. From Seymore4Head at Hotmail.invalid Mon Oct 20 14:10:49 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 20 Oct 2014 14:10:49 -0400 Subject: Building lists Message-ID: I haven't had a lot of practice doing this. If anyone knows of a site I would appreciate it. Will Python work like this: I am trying to come up with an example and work to it. Say I want a Grocery list and it will have a maximum size of 50 items. I want to do this with one list. Make a list of 0-50. Then can I add to that list so the second item will hold something like cheese, eggs, milk. Say then I want to add the price of cheese, eggs and milk. Say then I want to add another list of price of cheese, eggs milk from another store. Can this be done starting with just a list of numbers from 0-50? Please no hints, just answer directly how it is done. for store in range (50): print store How can I add to store where it looks like this: (0,cheese, 1,eggs 2,milk , 3-50,blank for now) From sohcahtoa82 at gmail.com Mon Oct 20 14:18:26 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Mon, 20 Oct 2014 11:18:26 -0700 (PDT) Subject: Building lists In-Reply-To: References: Message-ID: On Monday, October 20, 2014 11:13:17 AM UTC-7, Seymore4Head wrote: > I haven't had a lot of practice doing this. If anyone knows of a site > > I would appreciate it. > > > > Will Python work like this: > > I am trying to come up with an example and work to it. Say I want a > > Grocery list and it will have a maximum size of 50 items. > > > > I want to do this with one list. > > Make a list of 0-50. > > Then can I add to that list so the second item will hold something > > like cheese, eggs, milk. > > Say then I want to add the price of cheese, eggs and milk. > > Say then I want to add another list of price of cheese, eggs milk from > > another store. > > > > Can this be done starting with just a list of numbers from 0-50? > > Please no hints, just answer directly how it is done. > > > > for store in range (50): > > print store > > > > How can I add to store where it looks like this: > > (0,cheese, 1,eggs 2,milk , 3-50,blank for now) "Please no hints, just answer directly how it is done." That's pretty rude. We're not going to do your homework for you. From Seymore4Head at Hotmail.invalid Mon Oct 20 14:21:10 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 20 Oct 2014 14:21:10 -0400 Subject: Building lists References: Message-ID: On Mon, 20 Oct 2014 11:18:26 -0700 (PDT), sohcahtoa82 at gmail.com wrote: >On Monday, October 20, 2014 11:13:17 AM UTC-7, Seymore4Head wrote: >> I haven't had a lot of practice doing this. If anyone knows of a site >> >> I would appreciate it. >> >> >> >> Will Python work like this: >> >> I am trying to come up with an example and work to it. Say I want a >> >> Grocery list and it will have a maximum size of 50 items. >> >> >> >> I want to do this with one list. >> >> Make a list of 0-50. >> >> Then can I add to that list so the second item will hold something >> >> like cheese, eggs, milk. >> >> Say then I want to add the price of cheese, eggs and milk. >> >> Say then I want to add another list of price of cheese, eggs milk from >> >> another store. >> >> >> >> Can this be done starting with just a list of numbers from 0-50? >> >> Please no hints, just answer directly how it is done. >> >> >> >> for store in range (50): >> >> print store >> >> >> >> How can I add to store where it looks like this: >> >> (0,cheese, 1,eggs 2,milk , 3-50,blank for now) > >"Please no hints, just answer directly how it is done." > >That's pretty rude. We're not going to do your homework for you. I said please From sohcahtoa82 at gmail.com Mon Oct 20 14:33:22 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Mon, 20 Oct 2014 11:33:22 -0700 (PDT) Subject: Building lists In-Reply-To: References: Message-ID: <677ff292-256a-41e2-9f30-6fa5ff2ce928@googlegroups.com> On Monday, October 20, 2014 11:23:36 AM UTC-7, Seymore4Head wrote: > On Mon, 20 Oct 2014 11:18:26 -0700 (PDT), sohcahtoa82 wrote: > > > > >On Monday, October 20, 2014 11:13:17 AM UTC-7, Seymore4Head wrote: > > >> I haven't had a lot of practice doing this. If anyone knows of a site > > >> > > >> I would appreciate it. > > >> > > >> > > >> > > >> Will Python work like this: > > >> > > >> I am trying to come up with an example and work to it. Say I want a > > >> > > >> Grocery list and it will have a maximum size of 50 items. > > >> > > >> > > >> > > >> I want to do this with one list. > > >> > > >> Make a list of 0-50. > > >> > > >> Then can I add to that list so the second item will hold something > > >> > > >> like cheese, eggs, milk. > > >> > > >> Say then I want to add the price of cheese, eggs and milk. > > >> > > >> Say then I want to add another list of price of cheese, eggs milk from > > >> > > >> another store. > > >> > > >> > > >> > > >> Can this be done starting with just a list of numbers from 0-50? > > >> > > >> Please no hints, just answer directly how it is done. > > >> > > >> > > >> > > >> for store in range (50): > > >> > > >> print store > > >> > > >> > > >> > > >> How can I add to store where it looks like this: > > >> > > >> (0,cheese, 1,eggs 2,milk , 3-50,blank for now) > > > > > >"Please no hints, just answer directly how it is done." > > > > > >That's pretty rude. We're not going to do your homework for you. > > > > I said please Oh shit! It's the magic word! I better get right on it! From juan0christian at gmail.com Mon Oct 20 15:04:09 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 20 Oct 2014 17:04:09 -0200 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: Ok, new code using ?: import sqlite3 db = sqlite3.connect('db.sqlite') def create_db(): db.execute(''' CREATE TABLE TOPICS( ID INT PRIMARY KEY NOT NULL, URL VARCHAR NOT NULL, AUTHOR VARCHAR NOT NULL, MESSAGE VARCHAR NOT NULL ); ''') def insert_db(_id, url, author, message): db.execute("INSERT INTO TOPICS (ID, URL, AUTHOR, MESSAGE) VALUES (?, ?, ?, ?)", (_id, url, author, message)) db.commit() def get_db(_id): cursor = db.execute("SELECT ID, URL, AUTHOR, MESSAGE FROM TOPICS WHERE ID = ?", (_id)) return cursor.fetchone() if __name__ == '__main__': create_db() insert_db(12, 'abc.com', 'a', 'b') print(get_db(12)) db.close() ------------- But now when I execute I get Traceback (most recent call last): File ".\sql.py", line 30, in print(get_db(12)) File ".\sql.py", line 23, in get_db cursor = db.execute("SELECT ID, URL, AUTHOR, MESSAGE FROM TOPICS WHERE ID = ?", (_id)) ValueError: parameters are of unsupported type ------------- And the second time, again, I get Traceback (most recent call last): File ".\sql.py", line 28, in create_db() File ".\sql.py", line 14, in create_db ''') sqlite3.OperationalError: table TOPICS already exists On Mon, Oct 20, 2014 at 3:57 PM, Ian Kelly wrote: > On Mon, Oct 20, 2014 at 11:54 AM, Ian Kelly wrote: > > On Mon, Oct 20, 2014 at 9:54 AM, Simon Kennedy > wrote: > >> Not having ever attempted to go beyond even the basics of Perl, the > aspect that causes me to refer to Perl 'dismissively' as well comment in > this thread, is that I don't find Perl to be an aesthetically pleasing > language and I consider Python functions which have no blank lines in them > to be a small step towards Perl. > >> > >> Some people do not like Python's indentation rules but for me it's a > large part of what draws me to program in Python. Spaces for indentation > and blank lines are both aspects of how I like to program. > >> > >> I write in Python because I like to, not because I have to. > >> > >> I think the only reason I might code a function with no blank lines was > if I was programming in a language that using blank lines caused it to run > too slowly. > > > > So to be clear, I'm not talking about taking a function like this > > (contrived) example and just removing the blank line: > > > > def find_path(graphdata, start, end): > > edges = map(str.split, lines) > > graph = collections.defaultdict(list) > > for node1, node2, weight in edges: > > graph[node1].append((node[2], int(weight))) > > graph[node2].append((node[1], int(weight))) > > > > open_heap = [(0, (start,))] > > closed_set = set() > > while open_heap: > > cost, path = heapq.heappop(open_heap) > > current_node = path[-1] > > if current_node == end: > > return path > > if current_node in closed_set: > > continue > > for next_node, weight in graph[current_node]: > > heapq.heappush((cost + weight, path + (next_node,))) > > closed_set.add(current_node) > > else: > > raise ValueError("No path from start to end") > > > > Rather, I'm saying that where the blank line is should be the start of > > a new function. There would still be a blank line, just no longer > > inside the function. > > > > Now, maybe you think there should be more blank lines in the above, in > > which case we'll just have to disagree on that point. > > By the way, I didn't test that at all, which is why I've spotted at > least two bugs in it since sending the message. > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Mon Oct 20 15:40:18 2014 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 20 Oct 2014 20:40:18 +0100 Subject: Building lists In-Reply-To: References: Message-ID: <54456522.7000200@mrabarnett.plus.com> On 2014-10-20 19:10, Seymore4Head wrote: > I haven't had a lot of practice doing this. If anyone knows of a site > I would appreciate it. > > Will Python work like this: > I am trying to come up with an example and work to it. Say I want a > Grocery list and it will have a maximum size of 50 items. > > I want to do this with one list. > Make a list of 0-50. > Then can I add to that list so the second item will hold something > like cheese, eggs, milk. > Say then I want to add the price of cheese, eggs and milk. > Say then I want to add another list of price of cheese, eggs milk from > another store. > > Can this be done starting with just a list of numbers from 0-50? > Please no hints, just answer directly how it is done. > > for store in range (50): > print store > > How can I add to store where it looks like this: > (0,cheese, 1,eggs 2,milk , 3-50,blank for now) > The grocery list would be a list of the things you want to buy. There are a number of stores, so that would be a list of stores. For each store you want the price of each item, so that would be a dict where the key is the item and the value is the price of that item. That means it would be a list of dicts. Does that help? From ian.g.kelly at gmail.com Mon Oct 20 15:40:47 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 20 Oct 2014 13:40:47 -0600 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Oct 20, 2014 at 1:04 PM, Juan Christian wrote: > Ok, new code using ?: I suspect you meant to post this to some other thread. > def get_db(_id): > cursor = db.execute("SELECT ID, URL, AUTHOR, MESSAGE FROM TOPICS WHERE ID = > ?", (_id)) > return cursor.fetchone() (_id) is not a tuple; it's just a parenthesized variable name. To create a one-element tuple you need a trailing comma: (_id,) Remember that with the exception of the empty tuple (), tuples are created by commas, not parentheses. From python at mrabarnett.plus.com Mon Oct 20 15:43:36 2014 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 20 Oct 2014 20:43:36 +0100 Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <544565E8.6050702@mrabarnett.plus.com> On 2014-10-20 20:04, Juan Christian wrote: > Ok, new code using ?: > > import sqlite3 > > db = sqlite3.connect('db.sqlite') > > > def create_db(): > db.execute(''' > CREATE TABLE TOPICS( > ID INT PRIMARY KEY NOT NULL, > URL VARCHAR NOT NULL, > AUTHOR VARCHAR NOT NULL, > MESSAGE VARCHAR NOT NULL > ); > ''') > > > def insert_db(_id, url, author, message): > db.execute("INSERT INTO TOPICS (ID, URL, AUTHOR, MESSAGE) VALUES > (?, ?, ?, ?)", (_id, url, author, message)) > db.commit() > > > def get_db(_id): > cursor = db.execute("SELECT ID, URL, AUTHOR, MESSAGE FROM TOPICS WHERE > ID = ?", (_id)) > return cursor.fetchone() > > > if __name__ == '__main__': > create_db() > insert_db(12, 'abc.com ', 'a', 'b') > print(get_db(12)) > db.close() > > ------------- > > But now when I execute I get > > Traceback (most recent call last): > File ".\sql.py", line 30, in > print(get_db(12)) > File ".\sql.py", line 23, in get_db > cursor = db.execute("SELECT ID, URL, AUTHOR, MESSAGE FROM TOPICS > WHERE ID = ?", (_id)) > ValueError: parameters are of unsupported type > > ------------- > I'm not certain, but I think that the SQL type is called "INTEGER", not "INT". > And the second time, again, I get > > Traceback (most recent call last): > File ".\sql.py", line 28, in > create_db() > File ".\sql.py", line 14, in create_db > ''') > sqlite3.OperationalError: table TOPICS already exists > That's because you created the table the last time you ran it. From Seymore4Head at Hotmail.invalid Mon Oct 20 15:49:15 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 20 Oct 2014 15:49:15 -0400 Subject: Building lists References: Message-ID: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> On Mon, 20 Oct 2014 20:40:18 +0100, MRAB wrote: >On 2014-10-20 19:10, Seymore4Head wrote: >> I haven't had a lot of practice doing this. If anyone knows of a site >> I would appreciate it. >> >> Will Python work like this: >> I am trying to come up with an example and work to it. Say I want a >> Grocery list and it will have a maximum size of 50 items. >> >> I want to do this with one list. >> Make a list of 0-50. >> Then can I add to that list so the second item will hold something >> like cheese, eggs, milk. >> Say then I want to add the price of cheese, eggs and milk. >> Say then I want to add another list of price of cheese, eggs milk from >> another store. >> >> Can this be done starting with just a list of numbers from 0-50? >> Please no hints, just answer directly how it is done. >> >> for store in range (50): >> print store >> >> How can I add to store where it looks like this: >> (0,cheese, 1,eggs 2,milk , 3-50,blank for now) >> >The grocery list would be a list of the things you want to buy. > >There are a number of stores, so that would be a list of stores. For >each store you want the price of each item, so that would be a dict >where the key is the item and the value is the price of that item. That >means it would be a list of dicts. > >Does that help? No. I am pretty new to Python. For starters I would like to know if you can make a single item list and then turn it into a 2 item list. Is there a command for that? Do you have to know the number of items the list will have before making it? From breamoreboy at yahoo.co.uk Mon Oct 20 15:55:39 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 20 Oct 2014 20:55:39 +0100 Subject: Building lists In-Reply-To: <677ff292-256a-41e2-9f30-6fa5ff2ce928@googlegroups.com> References: <677ff292-256a-41e2-9f30-6fa5ff2ce928@googlegroups.com> Message-ID: On 20/10/2014 19:33, sohcahtoa82 at gmail.com wrote: > > Oh shit! It's the magic word! I better get right on it! > While you're at it would you please access this list via https://mail.python.org/mailman/listinfo/python-list or read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing and single line paragraphs, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ian.g.kelly at gmail.com Mon Oct 20 15:58:46 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 20 Oct 2014 13:58:46 -0600 Subject: Building lists In-Reply-To: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On Mon, Oct 20, 2014 at 1:49 PM, Seymore4Head wrote: > For starters I would like to know if you can make a single item list > and then turn it into a 2 item list. Is there a command for that? You mean like this? >>> the_list = ['first_item'] >>> the_list.append('second_item') >>> the_list ['first_item', 'second_item'] From breamoreboy at yahoo.co.uk Mon Oct 20 15:57:52 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 20 Oct 2014 20:57:52 +0100 Subject: Building lists In-Reply-To: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On 20/10/2014 20:49, Seymore4Head wrote: > On Mon, 20 Oct 2014 20:40:18 +0100, MRAB > wrote: > >> On 2014-10-20 19:10, Seymore4Head wrote: >>> I haven't had a lot of practice doing this. If anyone knows of a site >>> I would appreciate it. >>> >>> Will Python work like this: >>> I am trying to come up with an example and work to it. Say I want a >>> Grocery list and it will have a maximum size of 50 items. >>> >>> I want to do this with one list. >>> Make a list of 0-50. >>> Then can I add to that list so the second item will hold something >>> like cheese, eggs, milk. >>> Say then I want to add the price of cheese, eggs and milk. >>> Say then I want to add another list of price of cheese, eggs milk from >>> another store. >>> >>> Can this be done starting with just a list of numbers from 0-50? >>> Please no hints, just answer directly how it is done. >>> >>> for store in range (50): >>> print store >>> >>> How can I add to store where it looks like this: >>> (0,cheese, 1,eggs 2,milk , 3-50,blank for now) >>> >> The grocery list would be a list of the things you want to buy. >> >> There are a number of stores, so that would be a list of stores. For >> each store you want the price of each item, so that would be a dict >> where the key is the item and the value is the price of that item. That >> means it would be a list of dicts. >> >> Does that help? > > No. I am pretty new to Python. > > For starters I would like to know if you can make a single item list > and then turn it into a 2 item list. Is there a command for that? > > Do you have to know the number of items the list will have before > making it? > Python doesn't have commands and no. Perhaps you'd care to (re)read the tutorial. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From Seymore4Head at Hotmail.invalid Mon Oct 20 16:23:25 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 20 Oct 2014 16:23:25 -0400 Subject: Building lists References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On Mon, 20 Oct 2014 13:58:46 -0600, Ian Kelly wrote: >On Mon, Oct 20, 2014 at 1:49 PM, Seymore4Head > wrote: >> For starters I would like to know if you can make a single item list >> and then turn it into a 2 item list. Is there a command for that? > >You mean like this? > >>>> the_list = ['first_item'] >>>> the_list.append('second_item') >>>> the_list >['first_item', 'second_item'] a=(1,2,3) b=("Red", "Green", "Blue") c=("a"."b,"c") d=(1,red,a 2,green,b 3,blue,c) Something like that. From Seymore4Head at Hotmail.invalid Mon Oct 20 16:24:04 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 20 Oct 2014 16:24:04 -0400 Subject: Building lists References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On Mon, 20 Oct 2014 20:57:52 +0100, Mark Lawrence wrote: >On 20/10/2014 20:49, Seymore4Head wrote: >> On Mon, 20 Oct 2014 20:40:18 +0100, MRAB >> wrote: >> >>> On 2014-10-20 19:10, Seymore4Head wrote: >>>> I haven't had a lot of practice doing this. If anyone knows of a site >>>> I would appreciate it. >>>> >>>> Will Python work like this: >>>> I am trying to come up with an example and work to it. Say I want a >>>> Grocery list and it will have a maximum size of 50 items. >>>> >>>> I want to do this with one list. >>>> Make a list of 0-50. >>>> Then can I add to that list so the second item will hold something >>>> like cheese, eggs, milk. >>>> Say then I want to add the price of cheese, eggs and milk. >>>> Say then I want to add another list of price of cheese, eggs milk from >>>> another store. >>>> >>>> Can this be done starting with just a list of numbers from 0-50? >>>> Please no hints, just answer directly how it is done. >>>> >>>> for store in range (50): >>>> print store >>>> >>>> How can I add to store where it looks like this: >>>> (0,cheese, 1,eggs 2,milk , 3-50,blank for now) >>>> >>> The grocery list would be a list of the things you want to buy. >>> >>> There are a number of stores, so that would be a list of stores. For >>> each store you want the price of each item, so that would be a dict >>> where the key is the item and the value is the price of that item. That >>> means it would be a list of dicts. >>> >>> Does that help? >> >> No. I am pretty new to Python. >> >> For starters I would like to know if you can make a single item list >> and then turn it into a 2 item list. Is there a command for that? >> >> Do you have to know the number of items the list will have before >> making it? >> > >Python doesn't have commands and no. Perhaps you'd care to (re)read the >tutorial. Thank you From bv8bv8bv8 at gmail.com Mon Oct 20 16:37:29 2014 From: bv8bv8bv8 at gmail.com (BV BV) Date: Mon, 20 Oct 2014 13:37:29 -0700 (PDT) Subject: Women's Rights in Islam Message-ID: <32dd229e-18a2-4f91-9e58-34577517f553@googlegroups.com> Women's Rights in Islam Islam is the sole religion that gave women her rights, these are so many and recorded in the Quran verses and the traditional sayings of the prophet, these rights are condensed in points here as holy texts, if all written, will take many pages. Equality between man and women Islam acquits Eve from the original Sin which lived through generation and women have to bear it. In Quran God has remitted this sin the moment it was committed. Women have the same spiritual status as men in the eye of God. Female Embryo's rights A female embryo, like a male embryo, should be guarded against hereditary disease. Females' rights in infantry While in other religions the birth of a female is not always welcome, the birth of a female is celebrated in Islam. Females like males should be given beautiful names. Females like males are to be given love while still children without any preference of one sex over another as stated in the prophet's hadith. Islam is against denigrating females in any way especially killing them during their infantry- an old custom practiced by the pagan Arabs. Rights of Females over Parents Females are to receive the due care and be brought up in the best way( God's reward for this is shielding parents against the hellfire and raising their ranks high up to that of the prophet as stated in the hadiths). Even Female slaves are to be taught, this is doubly rewarded by God. Teaching females is mandatory in Islam. A female(married or unmarried) has the right to inherit her father, mother, husband , her children, sisters and daughters( Note that Females in Judeo-Christianity inherit only from their parents in case no brothers are found) A female is not to be killed in wars. A female chastity is to be given high care. Parents should not favor sons over daughters A woman has the right to argue with men even with the prophet himself. Women are equal to men as stated in the hadith" Women are sisters to men." A woman, just like a man, can give someone the right of refuge and security among the Muslims. Rights of Wives A female has the right to choose her husband. A wife has the right to manage her property and the husband should not take any of her property. A wife is not responsible for spending on her family, it is not allowed for a husband to take a penny from her property. A wife has the full right to her dowry ( The husband is not to take any from it ) A wife can divorce herself if she doesn't like her husband. A husband is responsible for feeding, dwelling, taking the utmost care of his wife to the extent that raising a piece of bread to a wife's mouth will be rewarded by God) A wife should be given her full right in bed and even such an act is rewarded by God because the husband and the wife are sinners if they commit adultery. During menses, contrary to the holy Book, a woman can live among her family members and whoever touches her remains clean. The best among the Muslims are those who are good to their wives. As a Mother To show how important is the obedience of mothers the prophet says "paradise is under the feet of mothers." Though both the father and the mother are to be given the utmost care, a mother should be always at the top priority. Mothers should always be given due care from her children A son must not prefer his wife to his mother under any circumstances. A Muslim should ask for his parent permission before joining the Muslim army, which is engaged in fighting. Caring about parents is more preferred to fighting in the cause of God, if they are old and need care. A mother, like father, is to be given the utmost care and be obeyed even if she is not a Muslim. The rights of the divorced woman in Islam The Faith of Islam has ordained certain financial and social obligations in the event of divorce, so as to discourage people from resorting to it. Islam ordains that when a man divorces his wife, he must pay her the delayed dowry agreed upon in the marriage contract, in addition to the expense of her maintenance of food, drink and living quarters for a certain period of time, known as the " iddat ". The custody of the children is granted to the mother until they grow up. In the event of her death or inability to look after her children, the custody of her children is granted to her relations. The husband is legally and religiously charged with his children's financial maintenance, and for wet nurses to breast feed them even if their mother breast feeds them herself, as is stated in the following Quranic verse "And if they suckle your (offspring) give them their recompense "[1][12] Rights of a widow The whole of the Islamic society is responsible for financing her. Widows are protected in Islam from their in-laws, but are forced and not protected in the Bible's NT and OT As a widow Allah (Glory be to Him) says in a Divine Hadith: "I only accept Salah from those who do it humbly to My Glory those who spend the day in mentioning me, and takes care of widows, the needy, and the wayfarer." Dead mothers Her children are to ask Allah for remitting her sins and ask Allah to have mercy on her. Her children are to honor her relatives and friends. Children can do righteous acts for them ( optional) After one's mother dies, it is Sunnah to fulfill any vows that she had made, and to give charity and perform Hajj and 'Umrah on her behalf. After she dies, it is also Sunnah to honour her by maintaining ties with those whom she used to keep in touch with, such as her relatives and friends. http://www.quran-m.com/firas/en1/index.php/human/496-women-s-rights-in-islam,condensed.html Thank you From ian.g.kelly at gmail.com Mon Oct 20 16:45:19 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 20 Oct 2014 14:45:19 -0600 Subject: Building lists In-Reply-To: References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On Mon, Oct 20, 2014 at 2:23 PM, Seymore4Head wrote: > On Mon, 20 Oct 2014 13:58:46 -0600, Ian Kelly > wrote: > >>On Mon, Oct 20, 2014 at 1:49 PM, Seymore4Head >> wrote: >>> For starters I would like to know if you can make a single item list >>> and then turn it into a 2 item list. Is there a command for that? >> >>You mean like this? >> >>>>> the_list = ['first_item'] >>>>> the_list.append('second_item') >>>>> the_list >>['first_item', 'second_item'] > > > a=(1,2,3) > b=("Red", "Green", "Blue") > c=("a"."b,"c") > > d=(1,red,a 2,green,b 3,blue,c) > > Something like that. Those are tuples, not lists. Are you trying to create a list of tuples from a, b, and c? If so, then zip does what you want: >>> d = list(zip(a, b, c)) >>> d [(1, 'Red', 'a'), (2, 'Green', 'b'), (3, 'Blue', 'c')] Or do you want all those elements merged into a single list? >>> d = list(sum(zip(a, b, c), ())) >>> d [1, 'Red', 'a', 2, 'Green', 'b', 3, 'Blue', 'c'] From breamoreboy at yahoo.co.uk Mon Oct 20 16:47:36 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Mon, 20 Oct 2014 21:47:36 +0100 Subject: Building lists In-Reply-To: References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On 20/10/2014 21:23, Seymore4Head wrote: > On Mon, 20 Oct 2014 13:58:46 -0600, Ian Kelly > wrote: > >> On Mon, Oct 20, 2014 at 1:49 PM, Seymore4Head >> wrote: >>> For starters I would like to know if you can make a single item list >>> and then turn it into a 2 item list. Is there a command for that? >> >> You mean like this? >> >>>>> the_list = ['first_item'] >>>>> the_list.append('second_item') >>>>> the_list >> ['first_item', 'second_item'] > > > a=(1,2,3) > b=("Red", "Green", "Blue") > c=("a"."b,"c") > > d=(1,red,a 2,green,b 3,blue,c) > > Something like that. > https://docs.python.org/3/library/functions.html#zip -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From gordon at panix.com Mon Oct 20 16:48:54 2014 From: gordon at panix.com (John Gordon) Date: Mon, 20 Oct 2014 20:48:54 +0000 (UTC) Subject: Building lists References: Message-ID: In Seymore4Head writes: > Will Python work like this: Python is a capable general-purpose language, so yes, it can pretty much do anything you want. The trick is knowing how to do it. > Make a list of 0-50. > Then can I add to that list so the second item will hold something > like cheese, eggs, milk. You want one item to have cheese, eggs, and milk? What's the point of calling it one "item" if it holds three things? > Say then I want to add the price of cheese, eggs and milk. > Say then I want to add another list of price of cheese, eggs milk from > another store. > Can this be done starting with just a list of numbers from 0-50? > Please no hints, just answer directly how it is done. Each list item could be a tuple consisting of the item name and a dict containing the item's price at various stores, for example: # start with an empty list shopping_list = [] # make a 'cheese' item cheese = ('Cheese', { 'Walmart' : 5.00, 'Publix': 5.50, 'Costco': 4.99 } ) # add cheese to the shopping list shopping_list.append(cheese) -- John Gordon Imagine what it must be like for a real medical doctor to gordon at panix.com watch 'House', or a real serial killer to watch 'Dexter'. From Seymore4Head at Hotmail.invalid Mon Oct 20 16:55:09 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 20 Oct 2014 16:55:09 -0400 Subject: Building lists References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: <03ta4ahogsj145ijd7lfshm7emh6hh52gh@4ax.com> On Mon, 20 Oct 2014 14:45:19 -0600, Ian Kelly wrote: >On Mon, Oct 20, 2014 at 2:23 PM, Seymore4Head > wrote: >> On Mon, 20 Oct 2014 13:58:46 -0600, Ian Kelly >> wrote: >> >>>On Mon, Oct 20, 2014 at 1:49 PM, Seymore4Head >>> wrote: >>>> For starters I would like to know if you can make a single item list >>>> and then turn it into a 2 item list. Is there a command for that? >>> >>>You mean like this? >>> >>>>>> the_list = ['first_item'] >>>>>> the_list.append('second_item') >>>>>> the_list >>>['first_item', 'second_item'] >> >> >> a=(1,2,3) >> b=("Red", "Green", "Blue") >> c=("a"."b,"c") >> >> d=(1,red,a 2,green,b 3,blue,c) >> >> Something like that. > >Those are tuples, not lists. Are you trying to create a list of tuples >from a, b, and c? If so, then zip does what you want: > >>>> d = list(zip(a, b, c)) >>>> d >[(1, 'Red', 'a'), (2, 'Green', 'b'), (3, 'Blue', 'c')] > >Or do you want all those elements merged into a single list? > >>>> d = list(sum(zip(a, b, c), ())) >>>> d > >[1, 'Red', 'a', 2, 'Green', 'b', 3, 'Blue', 'c'] I am not sure really. I know I need more practice, but I haven't found a reliable way to find practice problems. Thank you From Seymore4Head at Hotmail.invalid Mon Oct 20 17:25:31 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 20 Oct 2014 17:25:31 -0400 Subject: Building lists References: Message-ID: On Mon, 20 Oct 2014 20:48:54 +0000 (UTC), John Gordon wrote: >In Seymore4Head writes: > >> Will Python work like this: > >Python is a capable general-purpose language, so yes, it can pretty >much do anything you want. The trick is knowing how to do it. > >> Make a list of 0-50. >> Then can I add to that list so the second item will hold something >> like cheese, eggs, milk. > >You want one item to have cheese, eggs, and milk? What's the point >of calling it one "item" if it holds three things? > >> Say then I want to add the price of cheese, eggs and milk. >> Say then I want to add another list of price of cheese, eggs milk from >> another store. > >> Can this be done starting with just a list of numbers from 0-50? >> Please no hints, just answer directly how it is done. > >Each list item could be a tuple consisting of the item name and a dict >containing the item's price at various stores, for example: > > # start with an empty list > shopping_list = [] > > # make a 'cheese' item > cheese = ('Cheese', { 'Walmart' : 5.00, > 'Publix': 5.50, > 'Costco': 4.99 } ) > > # add cheese to the shopping list > shopping_list.append(cheese) The thing is I am not really sure what I want. I do know I need more practice to find out. Since I am taking a course now, I can't really ask a direct question and my first example wasn't so good. I think what I am going to have to have is a master list that keeps track of several things and I will need to change some of them so I know that rules out tuples. I need more practice examples with indexing and don't know where to find it. Thanks It is hard to ask questions when you don't know all the terms yet. I also know that makes it even harder for you guys to answer them. :) From ian.g.kelly at gmail.com Mon Oct 20 17:34:40 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 20 Oct 2014 15:34:40 -0600 Subject: Building lists In-Reply-To: References: Message-ID: On Mon, Oct 20, 2014 at 3:25 PM, Seymore4Head wrote: > I think what I am going to have to have is a master list that keeps > track of several things and I will need to change some of them so I > know that rules out tuples. It sounds to me like what you really want is a list of class instances. Define a class to contain the properties that you want to have for one item in the list. Then create a list to contain multiple instances of that class. From greg.ewing at canterbury.ac.nz Mon Oct 20 17:54:55 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Tue, 21 Oct 2014 10:54:55 +1300 Subject: Building lists In-Reply-To: References: Message-ID: Seymore4Head wrote: > Say I want a > Grocery list and it will have a maximum size of 50 items. In Python it's actually easier to deal with variable-sized lists having no maximum size. Instead of pre-creating a list of a given size, just start with an empty list and append things to it. Unless there's some external reason for a size limit (e.g. you can't fit more than 50 items in your shopping bag) there's no need to impose limit at all. You should certainly start without a limit and only add it later if needed. Some things to get you started: items = [] # Start with an empty list items.append("cheese") # Add some items to it items.append("eggs") items.append("milk") for item in items: # Process the items print(item) If you really need to limit the number of items, you can do something like this: def add_item(item): if len(items) < 50: items.append(item) else: raise Exception("Shopping list is full") -- Greg From drsalists at gmail.com Mon Oct 20 17:59:29 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 20 Oct 2014 14:59:29 -0700 Subject: Flush stdin In-Reply-To: <87a94rgxi5.fsf@elektro.pacujo.net> References: <87a94rgxi5.fsf@elektro.pacujo.net> Message-ID: On Sun, Oct 19, 2014 at 9:45 PM, Marko Rauhamaa wrote: > I found this comment in CPython's source code (pythonrun.c): > > /* stdin is always opened in buffered mode, first because it shouldn't > make a difference in common use cases, second because TextIOWrapper > depends on the presence of a read1() method which only exists on > buffered streams. > */ > > The solution is to use os.read(). Seriously? From Seymore4Head at Hotmail.invalid Mon Oct 20 17:57:17 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 20 Oct 2014 17:57:17 -0400 Subject: Building lists References: Message-ID: On Tue, 21 Oct 2014 10:54:55 +1300, Gregory Ewing wrote: >Seymore4Head wrote: >> Say I want a >> Grocery list and it will have a maximum size of 50 items. > >In Python it's actually easier to deal with variable-sized >lists having no maximum size. Instead of pre-creating a list >of a given size, just start with an empty list and append >things to it. > >Unless there's some external reason for a size limit (e.g. >you can't fit more than 50 items in your shopping bag) >there's no need to impose limit at all. You should >certainly start without a limit and only add it later >if needed. > >Some things to get you started: > >items = [] # Start with an empty list >items.append("cheese") # Add some items to it >items.append("eggs") >items.append("milk") >for item in items: # Process the items > print(item) > >If you really need to limit the number of items, you >can do something like this: > >def add_item(item): > if len(items) < 50: > items.append(item) > else: > raise Exception("Shopping list is full") Thanks. From juan0christian at gmail.com Mon Oct 20 18:30:35 2014 From: juan0christian at gmail.com (Juan Christian) Date: Mon, 20 Oct 2014 20:30:35 -0200 Subject: Is there an easy way to control indents in Python In-Reply-To: <544565E8.6050702@mrabarnett.plus.com> References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> <544565E8.6050702@mrabarnett.plus.com> Message-ID: Sorry guys, my post about SQL was not meant to be here!!! On Mon, Oct 20, 2014 at 5:43 PM, MRAB wrote: > On 2014-10-20 20:04, Juan Christian wrote: > >> Ok, new code using ?: >> >> import sqlite3 >> >> db = sqlite3.connect('db.sqlite') >> >> >> def create_db(): >> db.execute(''' >> CREATE TABLE TOPICS( >> ID INT PRIMARY KEY NOT NULL, >> URL VARCHAR NOT NULL, >> AUTHOR VARCHAR NOT NULL, >> MESSAGE VARCHAR NOT NULL >> ); >> ''') >> >> >> def insert_db(_id, url, author, message): >> db.execute("INSERT INTO TOPICS (ID, URL, AUTHOR, MESSAGE) VALUES >> (?, ?, ?, ?)", (_id, url, author, message)) >> db.commit() >> >> >> def get_db(_id): >> cursor = db.execute("SELECT ID, URL, AUTHOR, MESSAGE FROM TOPICS WHERE >> ID = ?", (_id)) >> return cursor.fetchone() >> >> >> if __name__ == '__main__': >> create_db() >> insert_db(12, 'abc.com ', 'a', 'b') >> print(get_db(12)) >> db.close() >> >> ------------- >> >> But now when I execute I get >> >> Traceback (most recent call last): >> File ".\sql.py", line 30, in >> print(get_db(12)) >> File ".\sql.py", line 23, in get_db >> cursor = db.execute("SELECT ID, URL, AUTHOR, MESSAGE FROM TOPICS >> WHERE ID = ?", (_id)) >> ValueError: parameters are of unsupported type >> >> ------------- >> >> I'm not certain, but I think that the SQL type is called "INTEGER", not > "INT". > > And the second time, again, I get >> >> Traceback (most recent call last): >> File ".\sql.py", line 28, in >> create_db() >> File ".\sql.py", line 14, in create_db >> ''') >> sqlite3.OperationalError: table TOPICS already exists >> >> That's because you created the table the last time you ran it. > > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From denismfmcmahon at gmail.com Mon Oct 20 18:30:27 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Mon, 20 Oct 2014 22:30:27 +0000 (UTC) Subject: Building lists References: Message-ID: On Mon, 20 Oct 2014 20:40:18 +0100, MRAB wrote: > There are a number of stores, so that would be a list of stores. For > each store you want the price of each item, so that would be a dict > where the key is the item and the value is the price of that item. That > means it would be a list of dicts. > > Does that help? It think it would be a dict of dicts: shopping = { "store1" : { "item1": price1, "item2": price2, ... }, "store2" : { "item3": price3, "item4": price4, ... }, ... } -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Mon Oct 20 18:40:50 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Mon, 20 Oct 2014 22:40:50 +0000 (UTC) Subject: Building lists References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On Mon, 20 Oct 2014 15:49:15 -0400, Seymore4Head wrote: > For starters I would like to know if you can make a single item list and > then turn it into a 2 item list. Is there a command for that? Yes, it's called assignment. You can for example change a member of a list from an string to a tuple such as ( string, number ): >>> x = [ "fred", "jim", "susan" ] >>> x[x.index("jim")] = ( "jim", 11, ) >>> print x ['fred', ('jim', 11), 'susan'] > Do you have to know the number of items the list will have before making > it? No. See the append() method of the list object. -- Denis McMahon, denismfmcmahon at gmail.com From Seymore4Head at Hotmail.invalid Mon Oct 20 18:44:37 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 20 Oct 2014 18:44:37 -0400 Subject: Building lists References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On Mon, 20 Oct 2014 22:40:50 +0000 (UTC), Denis McMahon wrote: >On Mon, 20 Oct 2014 15:49:15 -0400, Seymore4Head wrote: > >> For starters I would like to know if you can make a single item list and >> then turn it into a 2 item list. Is there a command for that? > >Yes, it's called assignment. You can for example change a member of a >list from an string to a tuple such as ( string, number ): > >>>> x = [ "fred", "jim", "susan" ] >>>> x[x.index("jim")] = ( "jim", 11, ) >>>> print x >['fred', ('jim', 11), 'susan'] > >> Do you have to know the number of items the list will have before making >> it? > >No. See the append() method of the list object. Thanks From drsalists at gmail.com Mon Oct 20 18:52:51 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 20 Oct 2014 15:52:51 -0700 Subject: Flush stdin In-Reply-To: References: <87a94rgxi5.fsf@elektro.pacujo.net> Message-ID: If I run the following in one tty: nc -l localhost 9000 | /tmp/z ...where /tmp/z has just: #!/usr/bin/python3 import sys for line in sys.stdin.buffer: print(line) And then run the following in another tty on the same computer: while read line; do echo $line; sleep 1; done < /etc/passwd | nc localhost 9000 ...then everything acts line buffered, or perhaps even character buffered (the two are pretty indistinguishable in this test). What I see is my /etc/passwd file popping out of the nc -l side, one line at a time, each line one second apart. I suppose this suggests that it's the client that's sending TCP data that is buffering. That, or we're using two different versions of netcat (there are at least two available). From marko at pacujo.net Mon Oct 20 18:54:47 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 21 Oct 2014 01:54:47 +0300 Subject: Flush stdin References: <87a94rgxi5.fsf@elektro.pacujo.net> Message-ID: <87tx2yfj2g.fsf@elektro.pacujo.net> Dan Stromberg : > On Sun, Oct 19, 2014 at 9:45 PM, Marko Rauhamaa wrote: >> I found this comment in CPython's source code (pythonrun.c): >> >> /* stdin is always opened in buffered mode, first because it shouldn't >> make a difference in common use cases, second because TextIOWrapper >> depends on the presence of a read1() method which only exists on >> buffered streams. >> */ >> >> The solution is to use os.read(). > > Seriously? I wasn't joking. Marko From python at mrabarnett.plus.com Mon Oct 20 18:57:54 2014 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 20 Oct 2014 23:57:54 +0100 Subject: Building lists In-Reply-To: References: Message-ID: <54459372.8090609@mrabarnett.plus.com> On 2014-10-20 23:30, Denis McMahon wrote: > On Mon, 20 Oct 2014 20:40:18 +0100, MRAB wrote: > >> There are a number of stores, so that would be a list of stores. For >> each store you want the price of each item, so that would be a dict >> where the key is the item and the value is the price of that item. That >> means it would be a list of dicts. >> >> Does that help? > > It think it would be a dict of dicts: > > shopping = { "store1" : { "item1": price1, "item2": price2, ... }, > "store2" : { "item3": price3, "item4": price4, ... }, ... } > The OP never said that the stores have names! :-) From marko at pacujo.net Mon Oct 20 19:18:17 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 21 Oct 2014 02:18:17 +0300 Subject: Flush stdin References: <87a94rgxi5.fsf@elektro.pacujo.net> Message-ID: <87mw8qfhza.fsf@elektro.pacujo.net> Dan Stromberg : > ...then everything acts line buffered, or perhaps even character > buffered [...] > > That, or we're using two different versions of netcat (there are at > least two available). Let's unconfuse the issue a bit. I'll take line buffering, netcat and the OS out of the picture. Here's a character generator (test.sh): ======================================================================== while : ; do echo -n x sleep 1 done ======================================================================== and here's a character sink (test.py): ======================================================================== import sys while True: c = sys.stdin.read(1) if not c: break print(ord(c[0])) ======================================================================== Then, I run: ======================================================================== $ bash ./test.sh | python3 ./test.py 120 120 120 120 ======================================================================== The lines are output at one-second intervals. That demonstrates that sys.stdin.read(1) does not block for more than one character. IOW, there is no buffering whatsoever. If I change the sink a bit: "c = sys.stdin.read(5)", I get the same output but at five-second intervals indicating that sys.stdin.read() calls the underlying os.read() function five times before returning. In fact, that conclusion is made explicit by running: ======================================================================== $ bash ./test.sh | strace python3 ./test.py ... read(0, "x", 4096) = 1 read(0, "x", 4096) = 1 read(0, "x", 4096) = 1 read(0, "x", 4096) = 1 read(0, "x", 4096) = 1 fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 3), ...}) = 0 mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f3143bab000 write(1, "120\n", 4120 ) = 4 ... ======================================================================== If I modify test.py to call os.read(): ======================================================================== import os while True: c = os.read(0, 5) if not c: break print(ord(c[0])) ======================================================================== The output is again printed at one-second intervals: no buffering. Thus, we are back at my suggestion: use os.read() if you don't want Python to buffer stdin for you. Marko From moboyle79 at outlook.com Mon Oct 20 19:29:39 2014 From: moboyle79 at outlook.com (Mike Boyle) Date: Mon, 20 Oct 2014 23:29:39 +0000 Subject: Simple import in python 3 errors with complaint about bytes Message-ID: I'm modifying an extension written with the c-api to have a datatype of quaternions , with one of the goals being python 3 support. ?It works nicely in python 2.7, but for python 3.x gives an error that I can't find anywhere on the google. ?The directory looks like this: .../site-packages/ ? ? quaternion/ ? ? ? ? __init__.py ? ? ? ? numpy_quaternion.so __init__.py contains a line like this: ? ? from .numpy_quaternion import quaternion But when it hits that line, python 3 throws its hands up in disgust: > python -c 'import quaternion' Traceback (most recent call last): ? File "", line 1, in ? File "/Users/mynamehere/.continuum/anaconda/envs/py3k/lib/python3.4/site-packages/quaternion/__init__.py", line 3, in ? ? from .numpy_quaternion import quaternion TypeError: __import__() argument 1 must be str, not bytes The only thing before that line is `import numpy as np`, which typically works just fine. ?Obviously, I'm using python3.4 to compile and (attempt to) import (with a conda environment), so it's not something as dumb as using the wrong python. ?Also, this is the result for both me on my laptop and Travis-CI , so it doesn't seem to be anything peculiar to my installation. ?I've posted this question on stackoverflow, but haven't gotten much interest; the only responder suggested I ask here instead. Any ideas what's going wrong, or where I can go from here? Thanks, Mike From ckaynor at zindagigames.com Mon Oct 20 19:45:23 2014 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Mon, 20 Oct 2014 16:45:23 -0700 Subject: Simple import in python 3 errors with complaint about bytes In-Reply-To: References: Message-ID: Are you perhaps doing an import inside of the C code? Chris On Mon, Oct 20, 2014 at 4:29 PM, Mike Boyle wrote: > I'm modifying an extension written with the c-api to have a datatype of > quaternions , with one of the > goals being python 3 support. It works nicely in python 2.7, but for > python 3.x gives an error that I can't find anywhere on the google. The > directory looks like this: > > .../site-packages/ > quaternion/ > __init__.py > numpy_quaternion.so > > __init__.py contains a line like this: > > from .numpy_quaternion import quaternion > > But when it hits that line, python 3 throws its hands up in disgust: > > > python -c 'import quaternion' > Traceback (most recent call last): > File "", line 1, in > File > "/Users/mynamehere/.continuum/anaconda/envs/py3k/lib/python3.4/site-packages/quaternion/__init__.py", > line 3, in > from .numpy_quaternion import quaternion > TypeError: __import__() argument 1 must be str, not bytes > > The only thing before that line is `import numpy as np`, which typically > works just fine. Obviously, I'm using python3.4 to compile and (attempt > to) import (with a conda environment), so it's not something as dumb as > using the wrong python. Also, this is the result for both me on my laptop > and Travis-CI , so it > doesn't seem to be anything peculiar to my installation. I've posted this > question on stackoverflow, but haven't gotten much interest; the only > responder suggested I ask here instead. > > Any ideas what's going wrong, or where I can go from here? > > Thanks, > Mike > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ian.g.kelly at gmail.com Mon Oct 20 19:48:23 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 20 Oct 2014 17:48:23 -0600 Subject: Simple import in python 3 errors with complaint about bytes In-Reply-To: References: Message-ID: On Mon, Oct 20, 2014 at 5:29 PM, Mike Boyle wrote: > I'm modifying an extension written with the c-api to have a datatype of quaternions , with one of the goals being python 3 support. It works nicely in python 2.7, but for python 3.x gives an error that I can't find anywhere on the google. The directory looks like this: > > .../site-packages/ > quaternion/ > __init__.py > numpy_quaternion.so > > __init__.py contains a line like this: > > from .numpy_quaternion import quaternion > > But when it hits that line, python 3 throws its hands up in disgust: > >> python -c 'import quaternion' > Traceback (most recent call last): > File "", line 1, in > File "/Users/mynamehere/.continuum/anaconda/envs/py3k/lib/python3.4/site-packages/quaternion/__init__.py", line 3, in > from .numpy_quaternion import quaternion > TypeError: __import__() argument 1 must be str, not bytes > > The only thing before that line is `import numpy as np`, which typically works just fine. Obviously, I'm using python3.4 to compile and (attempt to) import (with a conda environment), so it's not something as dumb as using the wrong python. Also, this is the result for both me on my laptop and Travis-CI , so it doesn't seem to be anything peculiar to my installation. I've posted this question on stackoverflow, but haven't gotten much interest; the only responder suggested I ask here instead. > > Any ideas what's going wrong, or where I can go from here? I question whether the error is really coming from that particular import line. Try shadowing the __import__ function to see what's actually being passed there. E.g.: >>> orig_import = __import__ >>> def debug_import(name, globals=None, locals=None, fromlist=(), level=0): ... print("debug_import:", name, globals, locals, fromlist, level) ... return orig_import(name, globals, locals, fromlist, level) ... >>> import builtins >>> builtins.__import__ = debug_import >>> import sys debug_import: sys {'__spec__': None, '__loader__': , '__package__': None, 'builtins': , 'orig_import': , '__builtins__': , '__name__': '__main__', '__doc__': None, 'debug_import': } {'__spec__': None, '__loader__': , '__package__': None, 'builtins': , 'orig_import': , '__builtins__': , '__name__': '__main__', '__doc__': None, 'debug_import': } None 0 From rosuav at gmail.com Mon Oct 20 19:54:37 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 21 Oct 2014 10:54:37 +1100 Subject: Simple import in python 3 errors with complaint about bytes In-Reply-To: References: Message-ID: On Tue, Oct 21, 2014 at 10:29 AM, Mike Boyle wrote: > But when it hits that line, python 3 throws its hands up in disgust: > >> python -c 'import quaternion' Just something crazy to try: Instead of using python -c, create an actual script with just that one line in it. It might be that you have some strange console config that's causing problems. You may also want to try changing all your names to be unique ("quaternion1" as the package name, "quaternion2" as the Python file in it, etc), which should tell you which one it's actually failing on. ChrisA From steve+comp.lang.python at pearwood.info Mon Oct 20 19:55:08 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Tue, 21 Oct 2014 10:55:08 +1100 Subject: Building lists References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: <5445a0de$0$12981$c3e8da3$5496439d@news.astraweb.com> Seymore4Head wrote: > For starters I would like to know if you can make a single item list > and then turn it into a 2 item list. Is there a command for that? > > Do you have to know the number of items the list will have before > making it? Now these are the right sort of questions that you should be asking! They are concrete and tightly focused, not vague and so broad that they could mean anything, and they invite a concrete answer rather than hints. First question: can you take a single list item and turn it into a 2-item list? Yes, you can, you can turn a single list item into *anything*, including deleting it. Start with a list, and remember that lists are indexed starting with 0: py> alist = [1, 2, 4, 8, 16, 32, 64] py> alist[0] = "hello!" py> alist[1] = ["a", "b", "c"] py> del alist[4] py> print(alist) ['hello!', ['a', 'b', 'c'], 4, 8, 32, 64] Second question: do you need to know the number of items in a list in advance? No. You can add additional items to an existing list with the append() method: py> import random py> alist = [] py> while random.random() < 0.5: ... alist.append("spam") ... py> print(alist) ['spam', 'spam'] Because this is random, if you try it you will get an unpredictable number of "spam" words in the list. About half the time it will contain no words at all, about a quarter of the time it will contain a single word, an eighth of the time it will contain two words, and so forth. -- Steven From Seymore4Head at Hotmail.invalid Mon Oct 20 20:05:01 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 20 Oct 2014 20:05:01 -0400 Subject: Building lists References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> <5445a0de$0$12981$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Tue, 21 Oct 2014 10:55:08 +1100, Steven D'Aprano wrote: >Seymore4Head wrote: > >> For starters I would like to know if you can make a single item list >> and then turn it into a 2 item list. Is there a command for that? >> >> Do you have to know the number of items the list will have before >> making it? > >Now these are the right sort of questions that you should be asking! > >They are concrete and tightly focused, not vague and so broad that they >could mean anything, and they invite a concrete answer rather than hints. > >First question: can you take a single list item and turn it into a 2-item >list? Yes, you can, you can turn a single list item into *anything*, >including deleting it. Start with a list, and remember that lists are >indexed starting with 0: > >py> alist = [1, 2, 4, 8, 16, 32, 64] >py> alist[0] = "hello!" >py> alist[1] = ["a", "b", "c"] >py> del alist[4] >py> print(alist) >['hello!', ['a', 'b', 'c'], 4, 8, 32, 64] > > >Second question: do you need to know the number of items in a list in >advance? No. You can add additional items to an existing list with the >append() method: > >py> import random >py> alist = [] >py> while random.random() < 0.5: >... alist.append("spam") >... >py> print(alist) >['spam', 'spam'] > > >Because this is random, if you try it you will get an unpredictable number >of "spam" words in the list. About half the time it will contain no words >at all, about a quarter of the time it will contain a single word, an >eighth of the time it will contain two words, and so forth. Thanks From moboyle79 at outlook.com Mon Oct 20 20:20:54 2014 From: moboyle79 at outlook.com (Mike Boyle) Date: Tue, 21 Oct 2014 00:20:54 +0000 Subject: Simple import in python 3 errors with complaint about bytes In-Reply-To: References: , Message-ID: Ah, yes. ?Thanks to that clever import debug hack, and the suggestion that it would actually be an import within the module causing the trouble, I managed to track it down. ?I had tried copying some py3k changes from the "rational" module in numpy/numpy-dtypes, but evidently didn't do it right, or it just doesn't work. ?I was using `PyImport_Import` with a PyString. ?Now, going back to the original `PyImport_ImportModule` with a literal `char*`, everything seems to work great (for me at least; Travis isn't so sure...). Thanks very much! ---------------------------------------- > From: ian.g.kelly at gmail.com > Date: Mon, 20 Oct 2014 17:48:23 -0600 > Subject: Re: Simple import in python 3 errors with complaint about bytes > To: python-list at python.org > > On Mon, Oct 20, 2014 at 5:29 PM, Mike Boyle wrote: >> I'm modifying an extension written with the c-api to have a datatype of quaternions , with one of the goals being python 3 support. It works nicely in python 2.7, but for python 3.x gives an error that I can't find anywhere on the google. The directory looks like this: >> >> .../site-packages/ >> quaternion/ >> __init__.py >> numpy_quaternion.so >> >> __init__.py contains a line like this: >> >> from .numpy_quaternion import quaternion >> >> But when it hits that line, python 3 throws its hands up in disgust: >> >>> python -c 'import quaternion' >> Traceback (most recent call last): >> File "", line 1, in >> File "/Users/mynamehere/.continuum/anaconda/envs/py3k/lib/python3.4/site-packages/quaternion/__init__.py", line 3, in >> from .numpy_quaternion import quaternion >> TypeError: __import__() argument 1 must be str, not bytes >> >> The only thing before that line is `import numpy as np`, which typically works just fine. Obviously, I'm using python3.4 to compile and (attempt to) import (with a conda environment), so it's not something as dumb as using the wrong python. Also, this is the result for both me on my laptop and Travis-CI , so it doesn't seem to be anything peculiar to my installation. I've posted this question on stackoverflow, but haven't gotten much interest; the only responder suggested I ask here instead. >> >> Any ideas what's going wrong, or where I can go from here? > > I question whether the error is really coming from that particular > import line. Try shadowing the __import__ function to see what's > actually being passed there. E.g.: > >>>> orig_import = __import__ >>>> def debug_import(name, globals=None, locals=None, fromlist=(), level=0): > ... print("debug_import:", name, globals, locals, fromlist, level) > ... return orig_import(name, globals, locals, fromlist, level) > ... >>>> import builtins >>>> builtins.__import__ = debug_import >>>> import sys > debug_import: sys {'__spec__': None, '__loader__': '_frozen_importlib.BuiltinImporter'>, '__package__': None, 'builtins': > , 'orig_import': __import__>, '__builtins__': , > '__name__': '__main__', '__doc__': None, 'debug_import': debug_import at 0x7f6096aac9d8>} {'__spec__': None, '__loader__': > , '__package__': None, > 'builtins': , 'orig_import': function __import__>, '__builtins__': , > '__name__': '__main__', '__doc__': None, 'debug_import': debug_import at 0x7f6096aac9d8>} None 0 > -- > https://mail.python.org/mailman/listinfo/python-list From drsalists at gmail.com Mon Oct 20 20:30:13 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Mon, 20 Oct 2014 17:30:13 -0700 Subject: Flush stdin In-Reply-To: <87mw8qfhza.fsf@elektro.pacujo.net> References: <87a94rgxi5.fsf@elektro.pacujo.net> <87mw8qfhza.fsf@elektro.pacujo.net> Message-ID: On Mon, Oct 20, 2014 at 4:18 PM, Marko Rauhamaa wrote: > Dan Stromberg : >> ...then everything acts line buffered, or perhaps even character >> buffered [...] >> >> That, or we're using two different versions of netcat (there are at >> least two available). > > Let's unconfuse the issue a bit. I'll take line buffering, netcat and > the OS out of the picture. > > Here's a character generator (test.sh): > ======================================================================== > while : ; do > echo -n x > sleep 1 > done > ======================================================================== > > and here's a character sink (test.py): > ======================================================================== > import sys > while True: > c = sys.stdin.read(1) > if not c: > break > print(ord(c[0])) > ======================================================================== > > Then, I run: > ======================================================================== > $ bash ./test.sh | python3 ./test.py > 120 > 120 > 120 > 120 > ======================================================================== > > The lines are output at one-second intervals. > > That demonstrates that sys.stdin.read(1) does not block for more than > one character. IOW, there is no buffering whatsoever. Aren't character-buffered and unbuffered synonymous? Often with TCP protocols, line buffered is preferred to character buffered, both for performance and for simplicity: it doesn't suffer from tinygrams (as much), and telnet becomes a useful test client. Also, it's a straightforward way of framing your data, to avoid getting messed up by Nagle or fragmentation. One might find http://stromberg.dnsalias.org/~strombrg/bufsock.html worth a glance. It's buffered, but it keeps things framed, and doesn't fall prey to tinygrams nearly as much as character buffering. > If I change the sink a bit: "c = sys.stdin.read(5)", I get the same > output but at five-second intervals indicating that sys.stdin.read() > calls the underlying os.read() function five times before returning. In > fact, that conclusion is made explicit by running: > > ======================================================================== > $ bash ./test.sh | strace python3 ./test.py > ... > read(0, "x", 4096) = 1 > read(0, "x", 4096) = 1 > read(0, "x", 4096) = 1 > read(0, "x", 4096) = 1 > read(0, "x", 4096) = 1 > fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 3), ...}) = 0 > mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f3143bab000 > write(1, "120\n", 4120 > ) = 4 > ... ======================================================================== This is tremendously inefficient. It demands a context switch for every character. > If I modify test.py to call os.read(): > ======================================================================== > import os > while True: > c = os.read(0, 5) > if not c: > break > print(ord(c[0])) > ======================================================================== > > The output is again printed at one-second intervals: no buffering. > > Thus, we are back at my suggestion: use os.read() if you don't want > Python to buffer stdin for you. It's true that Python won't buffer (or will be character-buffered) then, but that takes some potentially-salient elements out of the picture. IOW, I don't think Python reading unbuffered is necessarily the whole issue, and may even be going to far. I have a habit of saying "necessary, but not necessarily sufficient", but in this case I believe it's more of a "not necessarily necessary, and not necessarily sufficient". A lot depends on the other pieces of the puzzle that you've chosen to "unconfuse" away. Yes, you can make Python unbuffered/character-buffered, but that's not the whole story. From noblebell at gmail.com Mon Oct 20 21:29:25 2014 From: noblebell at gmail.com (Noble Bell) Date: Mon, 20 Oct 2014 18:29:25 -0700 (PDT) Subject: Py2App - Could not import Tkinter error from resulting app Message-ID: <3b3f0e97-0633-4aa0-be53-ec2ddd799ce2@googlegroups.com> I have just created a python 3.4 application and created the setup.py file and then created an app with py2app. When I ran the resulting application I get an error in the console telling me that it could not import tkinter. Any ideas on how to correct this? Did I do something wrong? From noblebell at gmail.com Mon Oct 20 21:34:33 2014 From: noblebell at gmail.com (Noble Bell) Date: Mon, 20 Oct 2014 18:34:33 -0700 (PDT) Subject: OS X Menubar in Tkinter In-Reply-To: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> References: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> Message-ID: On Monday, October 20, 2014 5:47:14 AM UTC-5, Noble Bell wrote: > On Sunday, October 19, 2014 7:49:34 PM UTC-5, Ned Deily wrote: > > > In article , > > > > > > Noble Bell wrote: > > > > > > > I am using Python 3.4 on Mac OS X and Tinter 8.5. Does anyone have any code > > > > > > > that they would share with me on how to remove the "Python" menu in the > > > > > > > menubar at the top next to the "apple'? > > > > > > > > > > > > > > I would like to have the name of my program there instead and my menu. I can > > > > > > > add menus but not sure how to do the special menubar. Any help would be > > > > > > > appreciated. > > > > > > > > > > > > The name that shows up in the menu is derived by OS X from the > > > > > > application name in the executing application bundle. If you don't > > > > > > package your program up as an OS X application bundle, defaults will be > > > > > > used; in the case of Python OS X framework builds, Python provides a > > > > > > Python.app within the framework to allow the Python process to be > > > > > > automatically promoted to a full OS X gui process. Probably the > > > > > > simplest approach is to use py2app to create a double-clickable app with > > > > > > the name you want. There's an example in an answer to a similar > > > > > > question on Stackoverflow. And there are some old but still relevant > > > > > > details documented in the Tcl/TkAqua FAQ. > > > > > > > > > > > > https://pypi.python.org/pypi/py2app > > > > > > http://stackoverflow.com/questions/8695926/remove-default-python-submenu- > > > > > > with-tkinter-menu-on-mac-osx > > > > > > http://wiki.tcl.tk/12987 > > > > > > > > > > > > -- > > > > > > Ned Deily, > > > > > > nad at acm.org > > > > Thank you. I will take a look at all that this afternoon. Seems like I might have seen that post on stack overflow but not for sure. Creating the app with py2app fixed my problem. From galois271 at gmail.com Mon Oct 20 22:48:52 2014 From: galois271 at gmail.com (Chuck) Date: Mon, 20 Oct 2014 19:48:52 -0700 (PDT) Subject: Sqlite3 help In-Reply-To: References: <4a691d82-be63-4355-8898-0ecbd9cb16bd@googlegroups.com> Message-ID: Thanks a bunch Sibylle! That seems like a better approach. From tjreedy at udel.edu Tue Oct 21 00:07:24 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 21 Oct 2014 00:07:24 -0400 Subject: Py2App - Could not import Tkinter error from resulting app In-Reply-To: <3b3f0e97-0633-4aa0-be53-ec2ddd799ce2@googlegroups.com> References: <3b3f0e97-0633-4aa0-be53-ec2ddd799ce2@googlegroups.com> Message-ID: On 10/20/2014 9:29 PM, Noble Bell wrote: > I have just created a python 3.4 application and created the setup.py file and then created an app with py2app. > > When I ran the resulting application I get an error in the console telling me that it could not import tkinter. > > Any ideas on how to correct this? Did I do something wrong? tkinter imports _tkinter _tkinter connects with tclx.dll and tkx.dll (x is variable) So one possibility is no accessible tcl/tx. I have no idea how py2app is supposed to handle this on your undisclosed system. -- Terry Jan Reedy From marko at pacujo.net Tue Oct 21 00:41:07 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 21 Oct 2014 07:41:07 +0300 Subject: Flush stdin References: <87a94rgxi5.fsf@elektro.pacujo.net> <87mw8qfhza.fsf@elektro.pacujo.net> Message-ID: <87h9yyf318.fsf@elektro.pacujo.net> Dan Stromberg : > Often with TCP protocols, line buffered is preferred to character > buffered, Terminal devices support line buffering on write. Line buffering on read is an illusion created by higher-level libraries. The low-level read function reads in blocks of bytes. > Also, it's a straightforward way of framing your data, to avoid > getting messed up by Nagle or fragmentation. Nagle affects the communication between the peer OS kernels and isn't directly related to anything the application does. Also, Nagle doesn't play any role with pipes. >> ======================================================================== >> $ bash ./test.sh | strace python3 ./test.py >> ... >> read(0, "x", 4096) = 1 >> read(0, "x", 4096) = 1 >> read(0, "x", 4096) = 1 >> read(0, "x", 4096) = 1 >> read(0, "x", 4096) = 1 >> fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 3), ...}) = 0 >> mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, >> 0) = 0x7f3143bab000 >> write(1, "120\n", 4120 >> ) = 4 >> ... > ======================================================================== > > This is tremendously inefficient. It demands a context switch for > every character. Inefficiency isn't an issue when you generate one byte a second. If data were generated at a brisker pace, "read(0, ..., 4096)" could get more bytes at a time. Notice that even if the Python code requests 5 bytes, CPython requests up to 4096 bytes in a single read. Marko From breamoreboy at yahoo.co.uk Tue Oct 21 01:58:33 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 21 Oct 2014 06:58:33 +0100 Subject: OS X Menubar in Tkinter In-Reply-To: References: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> Message-ID: On 21/10/2014 02:34, Noble Bell wrote: > > Creating the app with py2app fixed my problem. > I'm pleased to see that you have an answer. In return would you please access this list via https://mail.python.org/mailman/listinfo/python-list or read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing and single line paragraphs, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From fomcl at yahoo.com Mon Oct 20 16:33:49 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Mon, 20 Oct 2014 13:33:49 -0700 Subject: real-life example LC_CTYPE effects? Message-ID: <1413837229.47847.BPMail_high_carrier@web163802.mail.gq1.yahoo.com> Hi, The locale category LC_CTYPE may affect character classification and case conversion. That's the theory. Can you give a practical example where this locale setting matters? Eg.: locale.setlocale(locale.LC_CTYPE, loc) m = re.match("\d+", s, re.I | re.L) So with two different values for loc, and s is identical, there will or won't be a match. Thanks! Albert-Jan From kumarpraveen.nitdgp at gmail.com Mon Oct 20 05:16:37 2014 From: kumarpraveen.nitdgp at gmail.com (Praveen Kumar) Date: Mon, 20 Oct 2014 14:46:37 +0530 Subject: Struggling with python-daemon and subprocess module to work together Message-ID: Hi, I am writing a very basic server side application[0] which get data from a client and create a virtual machine using provided data and also tells client about what's going on during *virt-install* command execution. Previously this basic server is executed using *openvt* but I thought it would be nice to have a daemon process for it and used python-daemon. Issue I am facing is after some time server will stop sending data to client which suppose to happen in #120 and get error message "Cannot run interactive console without a controlling TTY" . I am not able to figure out issue is occurred due to module or I missed something during daemon initialization. [0] http://fpaste.org/143455/ -- Praveen Kumar http://fedoraproject.org/wiki/User:Kumarpraveen http://fedoraproject.org/ http://kumar-pravin.blogspot.com From orgnut at yahoo.com Tue Oct 21 03:11:38 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Tue, 21 Oct 2014 00:11:38 -0700 Subject: Building lists In-Reply-To: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On 10/20/2014 12:49 PM, Seymore4Head wrote: > On Mon, 20 Oct 2014 20:40:18 +0100, MRAB > wrote: > Do you have to know the number of items the list will have before > making it? > No, it is not necessary, lists are NOT the same as arrays in other languages. But it IS possible to create an initial list of a specific size: myList = [None] * 50 That creates a 50-element list with each element set to None. (BTW, the indexes are from 0-49, not 0-50.) I have found this occasionally useful, but I'll emphasize, it's only RARELY useful. The .append() method is far more versatile. As to your original problem: my question to you is what is your purpose? 1) To solve this particular problem, using Python. or 2) To explore the usage of lists, applying them to this problem. If your purpose is the first, then I agree with the advice you have already been given here. Dictionaries are a much better fit to this problem. If your purpose is the second, then go ahead and use this for your exploration. But realize that to more experienced Pythonistas this would be a very un-pythonic approach. Even better would be to try multiple approaches -- lists, dictionaries, lists with dictionaries, dictionaries with lists or tuples... And any other combinations you can come up with. This will give you even more experience, and allow you to evaluate the different approaches. And no, I will not give you a ready-made "canned" answer. For one thing, your description is too vague to effectively do that. Good luck. -=- Larry -=- From orgnut at yahoo.com Tue Oct 21 03:40:06 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Tue, 21 Oct 2014 00:40:06 -0700 Subject: Building lists In-Reply-To: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On 10/20/2014 12:49 PM, Seymore4Head wrote: > On Mon, 20 Oct 2014 20:40:18 +0100, MRAB > wrote: > > Do you have to know the number of items the list will have before > making it? > No. Lists are NOT the same as arrays in other languages. But it IS possible to create an initial list of a specific size: myList = [None] * 50 This creates a 50-element list with each element set to None. (BTW, that makes the indexes 0-49, not 0-50.) I have occasionally found this useful, but I emphasize it is only RARELY useful. The .append() method is far more versatile. As to your original problem: my question to you is what is your purpose? 1) To solve this particular problem, using Python. or 2) To explore the usage of lists by applying them to this problem. If your purpose is the first, then I agree with the advice you have already been given here -- dictionaries are a much better fit to this problem. If your purpose is the second, then go ahead, have at it. But realize that to more experienced Pythonistas this approach the very un-pythonic for this problem. It would be even better to try multiple approaches -- lists, dictionaries, lists with dictionaries, dictionaries with lists or tuples... or whatever combination you can come up with. This will give you even more experience and allow you to evaluate these various techniques. And no, I won't give you a ready-made "canned" answer. For one thing your original description is much too vague. But good luck! -=- Larry -=- From anton.schattenfeld at gmail.com Tue Oct 21 03:48:23 2014 From: anton.schattenfeld at gmail.com (Anton) Date: Tue, 21 Oct 2014 00:48:23 -0700 (PDT) Subject: When to use assert In-Reply-To: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> References: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> Message-ID: <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> On Saturday, November 16, 2013 11:35:50 PM UTC-8, Steven D'Aprano wrote: > The question of when to use the assert statement comes up occasionally, > > usually in response to somebody misusing it, so I thought I'd write a > > post describing when and why to use assertions, and when not to. > > > > For those who aren't aware of it, Python's "assert" checks a condition, > > if it is true it does nothing, and if it is false it raises an > > AssertionError with an optional error message. For example: > > > > py> x = 23 > > py> assert x > 0, "x is not zero or negative" > > py> assert x%2 == 0, "x is not an even number" > > Traceback (most recent call last): > > File "", line 1, in > > AssertionError: x is not an even number > > > > > > Many people use asserts as a quick and easy way to raise an exception if > > an argument is given the wrong value. But this is wrong, dangerously > > wrong, for two reasons. The first is that AssertionError is usually the > > wrong error to give when testing function arguments. You wouldn't write > > code like this: > > > > if not isinstance(x, int): > > raise AssertionError("not an int") > > > > you'd raise TypeError instead. "assert" raises the wrong sort of > > exception. > > > > But, and more dangerously, there's a twist with assert: it can be > > compiled away and never executed, if you run Python with the -O or -OO > > optimization flags, and consequently there is no guarantee that assert > > statements will actually be run. When using assert properly, this is a > > feature, but when assert is used inappropriately, it leads to code that > > is completely broken when running with the -O flag. > > > > When should use assert? In no particular order, assertions should be used > > for: > > > > * defensive programming; > > * runtime checks on program logic; > > * checking contracts (e.g. pre-conditions and post-conditions); > > * program invariants; and > > * checked documentation. > > > > (It's also acceptable to use assert when testing code, as a sort of quick- > > and-dirty poor man's unit testing, so long as you accept that the tests > > simply won't do anything if you run with the -O flag. And I sometimes use > > "assert False" in code to mark code branches that haven't been written > > yet, and I want them to fail. Although "raise NotImplementedError" is > > probably better for that, if a little more verbose.) > > > > Opinions on assertions vary, because they can be a statement of > > confidence about the correctness of the code. If you're certain that the > > code is correct, then assertions are pointless, since they will never > > fail and you can safely remove them. If you're certain the checks can > > fail (e.g. when testing input data provided by the user), then you dare > > not use assert since it may be compiled away and then your checks will be > > skipped. > > > > It's the situations in between those two that are interesting, times when > > you're certain the code is correct but not *quite* absolutely certain. > > Perhaps you've missed some odd corner case (we're all only human). In > > this case an extra runtime check helps reassure you that any errors will > > be caught as early as possible rather than in distant parts of the code. > > > > (This is why assert can be divisive. Since we vary in our confidence > > about the correctness of code, one person's useful assert is another > > person's useless runtime test.) > > > > Another good use for asserts is checking program invariants. An invariant > > is some condition which you can rely on to be true unless a bug causes it > > to become false. If there's a bug, better to find out as early as > > possible, so we make a test for it, but we don't want to slow the code > > down with such tests. Hence assert, which can be turned on in development > > and off in production. > > > > An example of an invariant might be, if your function expects a database > > connection to be open when it starts, and promises that it will still be > > open when it returns, that's an invariant of the function: > > > > def some_function(arg): > > assert not DB.closed() > > ... # code goes here > > assert not DB.closed() > > return result > > > > > > Assertions also make good checked comments. Instead of writing a comment: > > > > # when we reach here, we know that n > 2 > > > > you can ensure it is checked at runtime by turning it into an assert: > > > > assert n > 2 > > > > Assertions are also a form of defensive programming. You're not > > protecting against errors in the code as it is now, but protecting > > against changes which introduce errors later. Ideally, unit tests will > > pick those up, but let's face it, even when tests exist at all, they're > > often incomplete. Build-bots can be down and nobody notices for weeks, or > > people forget to run tests before committing code. Having an internal > > check is another line of defence against errors sneaking in, especially > > those which don't noisily fail but cause the code to malfunction and > > return incorrect results. > > > > Suppose you have a series of if...elif blocks, where you know ahead of > > time what values some variable is expected to have: > > > > # target is expected to be one of x, y, or z, and nothing else. > > if target == x: > > run_x_code() > > elif target == y: > > run_y_code() > > else: > > run_z_code() > > > > > > Assume that this code is completely correct now. But will it stay > > correct? Requirements change. Code changes. What happens if the > > requirements change to allow target = w, with associated action > > run_w_code? If we change the code that sets target, but neglect to change > > this block of code, it will wrongly call run_z_code() and Bad Things will > > occur. It would be good to write this block of code defensively, so that > > it will either be correct, or fail immediately, even in the face of > > future changes. > > > > The comment at the start of the block is a good first step, but people > > are notorious for failing to read and update comments. Chances are it > > will soon be obsolete. But with an assertion, we can both document the > > assumptions of this block, and cause a clean, immediate failure if they > > are violated: > > > > assert target in (x, y, z) > > if target == x: > > run_x_code() > > elif target == y: > > run_y_code() > > else: > > assert target == z > > run_z_code() > > > > > > Here, the assertions are both defensive programming and checked > > documentation. I consider this to be a far superior solution than this: > > > > if target == x: > > run_x_code() > > elif target == y: > > run_y_code() > > elif target == z: > > run_z_code() > > else: > > # This can never happen. But just in case it does... > > raise RuntimeError("an unexpected error occurred") > > > > > > This tempts some helpful developer to "clean it up" by removing the > > "unnecessary" test for value==c and removing the "dead code" of the > > RuntimeError. Besides, "unexpected error" messages are embarrassing when > > they occur, and they will. > > > > Design by contract is another good use of assertions. In design by > > contract, we consider that functions make "contracts" with their callers. > > E.g. something like this: > > > > "If you pass me an non-empty string, I guarantee to return the first > > character of that string converted to uppercase." > > > > If the contract is broken by either the function or the code calling it, > > the code is buggy. We say that functions have pre-conditions (the > > constraints that arguments are expected to have) and post-conditions (the > > constraints on the return result). So this function might be coded as: > > > > def first_upper(astring): > > assert isinstance(astring, str) and len(astring) > 0 > > result = astring[0].upper() > > assert isinstance(result, str) and len(result) == 1 > > assert result == result.upper() > > return result > > > > > > The aim of Design By Contract is that in a correct program, the pre- > > conditions and post-conditions will always hold. Assertions are typically > > used, since (so the idea goes) by the time we release the bug-free > > program and put it into production, the program will be correct and we > > can safely remove the checks. > > > > Here's my advice when *not* to use assertions: > > > > * Never use them for testing user-supplied data, or for anything > > where the check must take place under all circumstances. > > > > * Don't use assert for checking anything that you expect might fail > > in the ordinary use of your program. Assertions are for extraordinary > > failure conditions. Your users should never see an AssertionError; > > if they do, it's a bug to be fixed. > > > > * In particular, don't use assert just because it's shorter than an > > explicit test followed by a raise. Assert is not a shortcut for > > lazy coders. > > > > * Don't use them for checking input arguments to public library > > functions (private ones are okay) since you don't control the > > caller and can't guarantee that it will never break the > > function's contract. > > > > * Don't use assert for any error which you expect to recover from. > > In other words, you've got no reason to catch an AssertionError > > exception in production code. > > > > * Don't use so many assertions that they obscure the code. > > > > > > > > -- > > Steven I use ORM and often need to write a function that either takes an id of the record or already loaded model object. So I end up writing a piece of code like below: def do_something(instance): if isinstance(instance_or_id, int): instance = Model.get(instance) assert isinstance(instance, Model) # Code that assumes that instance is an object of type Model do_somthing is not a part of public library, though it is a public function, which can and intended to be used by other programmers; and assert should never happen if a client uses the function as planned. I wonder if this use-case is controversial to this part: > Many people use asserts as a quick and easy way to raise an exception if > > an argument is given the wrong value. But this is wrong, dangerously > > wrong, for two reasons. The first is that AssertionError is usually the > > wrong error to give when testing function arguments. You wouldn't write > > code like this: > > > > if not isinstance(x, int): > > raise AssertionError("not an int") > > > > you'd raise TypeError instead. "assert" raises the wrong sort of > > exception. > Thanks, Anton. From sffjunkie at gmail.com Tue Oct 21 04:45:30 2014 From: sffjunkie at gmail.com (Simon Kennedy) Date: Tue, 21 Oct 2014 01:45:30 -0700 (PDT) Subject: Is there an easy way to control indents in Python In-Reply-To: References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <521b537d-c119-4858-8880-d1e1ddb76b55@googlegroups.com> On Monday, 20 October 2014 18:56:05 UTC+1, Ian wrote: > Rather, I'm saying that where the blank line is should be the start of > a new function. There would still be a blank line, just no longer > inside the function. > > Now, maybe you think there should be more blank lines in the above, in > which case we'll just have to disagree on that point. Why did you separate the above 2 sequences of thoughts by a blank line? Is the inherent pause in the communication of your thoughts not also applicable to your code? Where we see the pause between thoughts appears to be in a different place. I see them both within the function and between the functions and I assume you see them between the functions only. BTW I'm more than happy to disagree. There is no right or wrong answer unless Guido wants to pronounce on the issue :-J From noblebell at gmail.com Tue Oct 21 06:53:21 2014 From: noblebell at gmail.com (Noble Bell) Date: Tue, 21 Oct 2014 03:53:21 -0700 (PDT) Subject: OS X Menubar in Tkinter In-Reply-To: References: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> Message-ID: On Tuesday, October 21, 2014 12:59:08 AM UTC-5, Mark Lawrence wrote: > On 21/10/2014 02:34, Noble Bell wrote: > I'm pleased to see that you have an answer. In return would you please > > access this list via > > https://mail.python.org/mailman/listinfo/python-list or read and action > > this https://wiki.python.org/moin/GoogleGroupsPython to prevent us > > seeing double line spacing and single line paragraphs, thanks. I was not aware of the issue. Sorry. I will correct my posts in the future. Thanks for pointing it out to me. NB From random832 at fastmail.us Tue Oct 21 08:40:52 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Tue, 21 Oct 2014 08:40:52 -0400 Subject: real-life example LC_CTYPE effects? In-Reply-To: <1413837229.47847.BPMail_high_carrier@web163802.mail.gq1.yahoo.com> References: <1413837229.47847.BPMail_high_carrier@web163802.mail.gq1.yahoo.com> Message-ID: <1413895252.560763.181508729.1600A6CE@webmail.messagingengine.com> On Mon, Oct 20, 2014, at 16:33, Albert-Jan Roskam wrote: > Hi, > > The locale category LC_CTYPE may affect character classification and case > conversion. > > That's the theory. Can you give a practical example where this locale > setting matters? Eg.: > locale.setlocale(locale.LC_CTYPE, loc) > m = re.match("\d+", s, re.I | re.L) > > So with two different values for loc, and s is identical, there will or > won't be a match. You're generally isolated from this by using unicode strings - there are only a few unicode characters that have different case mappings in different languages. LC_CTYPE was designed in an era of 8-bit character sets. For example, in a Russian locale with KOI8-R character set, C0-DF are all lowercase letters, and E0-FF are all the uppercase equivalent, whereas in an English or other western european locale with ISO-8859-1, C0-DF [except D7] are all uppercase letters, with the lowercase versions in E0-FF [except F7], and in a Hebrew ISO-8859-8 locale only E0-FA are letters and are not uppercase/lowercase. Try setting the locale to tr_TR and matching "i" against "I", for a demonstration of one of the few remaining effects this can have. From Seymore4Head at Hotmail.invalid Tue Oct 21 08:54:18 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Tue, 21 Oct 2014 08:54:18 -0400 Subject: Building lists References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On Tue, 21 Oct 2014 00:11:38 -0700, Larry Hudson wrote: >On 10/20/2014 12:49 PM, Seymore4Head wrote: >> On Mon, 20 Oct 2014 20:40:18 +0100, MRAB >> wrote: > > > >> Do you have to know the number of items the list will have before >> making it? >> > >No, it is not necessary, lists are NOT the same as arrays in other languages. But it IS >possible to create an initial list of a specific size: > >myList = [None] * 50 > >That creates a 50-element list with each element set to None. (BTW, the indexes are from 0-49, >not 0-50.) I have found this occasionally useful, but I'll emphasize, it's only RARELY useful. > The .append() method is far more versatile. > >As to your original problem: my question to you is what is your purpose? > >1) To solve this particular problem, using Python. > or >2) To explore the usage of lists, applying them to this problem. > >If your purpose is the first, then I agree with the advice you have already been given here. >Dictionaries are a much better fit to this problem. > >If your purpose is the second, then go ahead and use this for your exploration. But realize >that to more experienced Pythonistas this would be a very un-pythonic approach. Even better >would be to try multiple approaches -- lists, dictionaries, lists with dictionaries, >dictionaries with lists or tuples... And any other combinations you can come up with. This >will give you even more experience, and allow you to evaluate the different approaches. > >And no, I will not give you a ready-made "canned" answer. For one thing, your description is >too vague to effectively do that. Good luck. > > -=- Larry -=- The concept I was asking about was a master list with my example of 1,2,3 as a index for the second and third items. It was suggested to make my task easier. It turns out that it didn't. Thanks for all the suggestions, though. From Seymore4Head at Hotmail.invalid Tue Oct 21 08:55:31 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Tue, 21 Oct 2014 08:55:31 -0400 Subject: Building lists References: <6jpa4ahhc8ln7hk8s0258hvqd3io51epa0@4ax.com> Message-ID: On Tue, 21 Oct 2014 00:40:06 -0700, Larry Hudson wrote: >On 10/20/2014 12:49 PM, Seymore4Head wrote: >> On Mon, 20 Oct 2014 20:40:18 +0100, MRAB >> wrote: >> > > >> Do you have to know the number of items the list will have before >> making it? >> > >No. Lists are NOT the same as arrays in other languages. But it IS possible to create an >initial list of a specific size: > >myList = [None] * 50 > >This creates a 50-element list with each element set to None. (BTW, that makes the indexes >0-49, not 0-50.) I have occasionally found this useful, but I emphasize it is only RARELY >useful. The .append() method is far more versatile. > >As to your original problem: my question to you is what is your purpose? > >1) To solve this particular problem, using Python. > or >2) To explore the usage of lists by applying them to this problem. > >If your purpose is the first, then I agree with the advice you have already been given here -- >dictionaries are a much better fit to this problem. > >If your purpose is the second, then go ahead, have at it. But realize that to more experienced >Pythonistas this approach the very un-pythonic for this problem. It would be even better to try >multiple approaches -- lists, dictionaries, lists with dictionaries, dictionaries with lists or >tuples... or whatever combination you can come up with. This will give you even more >experience and allow you to evaluate these various techniques. > >And no, I won't give you a ready-made "canned" answer. For one thing your original description >is much too vague. But good luck! > > -=- Larry -=- Also, I had no need to impose a limit on the list, but I asked that question, just in case. Thanks From Seymore4Head at Hotmail.invalid Tue Oct 21 08:55:57 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Tue, 21 Oct 2014 08:55:57 -0400 Subject: Building lists References: Message-ID: On Mon, 20 Oct 2014 21:31:05 -0400, Dennis Lee Bieber wrote: >On Mon, 20 Oct 2014 17:25:31 -0400, Seymore4Head > declaimed the following: > > >> >>The thing is I am not really sure what I want. I do know I need more >>practice to find out. Since I am taking a course now, I can't really >>ask a direct question and my first example wasn't so good. >> > Unfortunately, that puts your questions at the level of algorithm, not >language... Once you know the algorithm and data structures, THEN you can >figure out how to map them into Python (or Rexx, or any other language). Thanks From noblebell at gmail.com Tue Oct 21 09:20:16 2014 From: noblebell at gmail.com (Noble Bell) Date: Tue, 21 Oct 2014 06:20:16 -0700 (PDT) Subject: Py2App - Could not import Tkinter error from resulting app In-Reply-To: References: <3b3f0e97-0633-4aa0-be53-ec2ddd799ce2@googlegroups.com> Message-ID: On Monday, October 20, 2014 11:07:51 PM UTC-5, Terry Reedy wrote: > tkinter imports _tkinter > > _tkinter connects with tclx.dll and tkx.dll (x is variable) > > So one possibility is no accessible tcl/tx. I have no idea how py2app > > is supposed to handle this on your undisclosed system. > -- > > Terry Jan Reedy Thanks for the reply. I am using a Mac. The problem turns out that for some reason when I installed the py2app utility it got installed under python 2.7 instead of python 3, which I am using, and that caused it to create the bundle under 2.x instead of 3.x. The result was it was trying to use python 2.x instead of 3.x syntax. I realized this problem shortly after I posted the question and tried to go back to google groups and delete my post before anyone had seen it. NB From skip.montanaro at gmail.com Tue Oct 21 09:37:39 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Tue, 21 Oct 2014 08:37:39 -0500 Subject: Py2App - Could not import Tkinter error from resulting app In-Reply-To: References: <3b3f0e97-0633-4aa0-be53-ec2ddd799ce2@googlegroups.com> Message-ID: On Tue, Oct 21, 2014 at 8:20 AM, Noble Bell wrote: > I realized this problem shortly after I posted the question and tried to > go back to google groups and delete my post before anyone had seen it. In general, that won't work, as lots of people use email ( python-list at python.org) or Usenet (comp.lang.python) to read the group. In fact, Google Groups is very much a latecomer to the party. More importantly, just because you made a mistake doesn't mean you should delete your message. Other people might make the same mistake and learn from your post what the solution is. Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From jumppanen.jussi at gmail.com Tue Oct 21 09:51:35 2014 From: jumppanen.jussi at gmail.com (jumppanen.jussi at gmail.com) Date: Tue, 21 Oct 2014 06:51:35 -0700 (PDT) Subject: Is there an easy way to control indents in Python In-Reply-To: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> Message-ID: <18da7dec-432d-46be-9a77-25b0f7ad7584@googlegroups.com> On Wednesday, October 15, 2014 12:13:51 PM UTC+10, ryguy7272 wrote: > I'm just learning Python. One of the best ways to learn any language is to type in the example code by hand. As you type in the code you will make mistakes, you will learn from your mistakes and that will help you learn the language and in the process make you a better programmer. So if you really want to learn the language just type in the code by hand and the problem goes away. From christoph.wruck at gmail.com Tue Oct 21 10:32:30 2014 From: christoph.wruck at gmail.com (CWr) Date: Tue, 21 Oct 2014 07:32:30 -0700 (PDT) Subject: string processing - some problems whenever I have to parse a more complex string Message-ID: <2637a169-46a9-4787-8267-ac0775449e7e@googlegroups.com> Hello together, currently I have to parse a string in an atomic way. Normally - in this case too - I have a counter variable to keep the current position inside the string. So far, I think this is the most flexible solution to do some lookaround's inside the string if necessary. Subroutines will be feed by the underlying data and the current position. A subroutine returns a tuple of the new position and the result. But I would like process subroutines with the same flexibillity (slicing/lookaround) but without returning the new position every again. Is there any implementation like C++ StringPiece class? Or something like the following behavior: >>>s = StringSlice('abcdef') >>>s StringSlice('abcdef') at xxx >>>s[0] 'a' >>>s.chop(1) # chop the first item >>>s[0] # 'b' is the new first item 'b' >>>s[:2] 'bc' >>>s.chop(-1) # chop the last item >>>s[-1] 'e' >>>s[1:] 'cde' >>>while s[0] != 'e': s.chop(1) >>>s[0] 'e' >>>s.startswith('e') True >>>s.isdigit() False Subroutines could chop the number of processed items internally if no error occours. Another possibillty will be to chop the current item manually. But I don't know how efficient this is in case of large strings. >>>while string: c = string[0] # process it ... string = string[1:] But this assumes that I have to return rest of the string too and not useful for my problem covered abrove. Has anyone some tips what's the best practice to process a complex string, handling prositions in/and subroutines. Thanks for all answers... Cheers Chris From sam.raker at gmail.com Tue Oct 21 11:34:34 2014 From: sam.raker at gmail.com (Sam Raker) Date: Tue, 21 Oct 2014 08:34:34 -0700 (PDT) Subject: Pex import problems Message-ID: <2aba47c0-f420-4f91-944b-1ce7e42817c6@googlegroups.com> Hi all, I'm trying to use Pex (http://pex.readthedocs.org/en/latest/index.html) to include requests in a little script to ping a server from a machine that doesn't come with pip (or much of anything, really) installed. I'm running into problems outputting a pex file that depends on a local script. I've got a command-line file, `client.py`, that can be called with a few command-line options. I can run `pex -r requests -o client.pex -- client.py`, but when I try `./client.pex -h` I get an error about "no such file or directory: '-h'". Ok, next attempt: `pex -r requests -o client.pex -e client` --> "ImportError: No module named client". I dug around in the code a bit, and from what I can tell, `-e FOO` boils down to `__import__(FOO)`, which I can do, both from the interpreter and from a test script. So what am I missing? The only other option I can think of would be: `pex -r requests -o client.pex` & then write a script that calls `client.py` from the pex environment (i.e., `./client.pex client.py -h` or whatever), and bundle the pex file, `client.py`, and the script together. But that seems like a misuse of the tool, at best. Alternatively/additionally: is there any mailing list/help source for pex? It seems like a great project, but I've not been able to find many resources out there, which is why I'm turning to you guys. (Why not just install pip/requests on the target machine? Because this is part of an effort to automate provisioning of a bunch of machines.) (Why not use pants? Because literally all we need is requests, and that seems like overkill.) (Also: anyone who's planning on chewing me out about formatting: I TRIED posting by email to comp.lang.python at googlegroups.com, but it wouldn't let me. Sorry for the extra whitespace.) From rosuav at gmail.com Tue Oct 21 12:04:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 03:04:24 +1100 Subject: Pex import problems In-Reply-To: <2aba47c0-f420-4f91-944b-1ce7e42817c6@googlegroups.com> References: <2aba47c0-f420-4f91-944b-1ce7e42817c6@googlegroups.com> Message-ID: On Wed, Oct 22, 2014 at 2:34 AM, Sam Raker wrote: > (Also: anyone who's planning on chewing me out about formatting: I TRIED posting by email to comp.lang.python at googlegroups.com, but it wouldn't let me. Sorry for the extra whitespace.) That's because that isn't the mailing list's name. Sign up here: https://mail.python.org/mailman/listinfo/python-list ChrisA From sam.raker at gmail.com Tue Oct 21 12:36:27 2014 From: sam.raker at gmail.com (Sam Raker) Date: Tue, 21 Oct 2014 09:36:27 -0700 (PDT) Subject: Pex import problems In-Reply-To: References: <2aba47c0-f420-4f91-944b-1ce7e42817c6@googlegroups.com> Message-ID: On Tuesday, October 21, 2014 12:05:00 PM UTC-4, Chris Angelico wrote: > On Wed, Oct 22, 2014 at 2:34 AM, Sam Raker wrote: > > > (Also: anyone who's planning on chewing me out about formatting: I TRIED posting by email to comp.lang.python at googlegroups.com, but it wouldn't let me. Sorry for the extra whitespace.) > That's because that isn't the mailing list's name. Sign up here: > https://mail.python.org/mailman/listinfo/python-list > ChrisA Thank you for your help. From rosuav at gmail.com Tue Oct 21 12:45:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 03:45:01 +1100 Subject: Pex import problems In-Reply-To: References: <2aba47c0-f420-4f91-944b-1ce7e42817c6@googlegroups.com> Message-ID: On Wed, Oct 22, 2014 at 3:36 AM, Sam Raker wrote: >> That's because that isn't the mailing list's name. Sign up here: > >> https://mail.python.org/mailman/listinfo/python-list > >> ChrisA > > Thank you for your help. No probs. Sorry I can't help with your main issue, as I'm not at all familiar with pex. ChrisA From pjenvey at underboss.org Tue Oct 21 13:03:01 2014 From: pjenvey at underboss.org (Philip Jenvey) Date: Tue, 21 Oct 2014 10:03:01 -0700 Subject: PyPy3 2.4.0 released Message-ID: <1D51E541-E9DA-4737-91CA-66A2A3EF606E@underboss.org> ================================================= PyPy3 2.4 - Snow White ================================================= We're pleased to announce PyPy3 2.4, which contains significant performance enhancements and bug fixes. You can download the PyPy3 2.4.0 release here: http://pypy.org/download.html PyPy3 Highlights ================ Issues reported with our previous release were fixed after reports from users on our new issue tracker at https://bitbucket.org/pypy/pypy/issues or on IRC at #pypy. Here is a summary of the user-facing PyPy3 specific changes: * Better Windows compatibility, e.g. the nt module functions _getfinalpathname & _getfileinformation are now supported (the former is required for the popular pathlib library for example) * Various fsencode PEP 383 related fixes to the posix module (readlink, uname, ttyname and ctermid) and improved locale handling * Switched default binary name os POSIX distributions to 'pypy3' (which symlinks to to 'pypy3.2') * Fixed a couple different crashes related to parsing Python 3 source code Further Highlights (shared w/ PyPy2) ==================================== Benchmarks improved after internal enhancements in string and bytearray handling, and a major rewrite of the GIL handling. This means that external calls are now a lot faster, especially the CFFI ones. It also means better performance in a lot of corner cases with handling strings or bytearrays. The main bugfix is handling of many socket objects in your program which in the long run used to "leak" memory. We fixed a memory leak in IO in the sandbox_ code We welcomed more than 12 new contributors, and conducted two Google Summer of Code projects, as well as other student projects not directly related to Summer of Code. * Reduced internal copying of bytearray operations * Tweak the internal structure of StringBuilder to speed up large string handling, which becomes advantageous on large programs at the cost of slightly slower small *benchmark* type programs. * Boost performance of thread-local variables in both unjitted and jitted code, this mostly affects errno handling on linux, which makes external calls faster. * Move to a mixed polling and mutex GIL model that make mutlithreaded jitted code run *much* faster * Optimize errno handling in linux (x86 and x86-64 only) * Remove ctypes pythonapi and ctypes.PyDLL, which never worked on PyPy * Classes in the ast module are now distinct from structures used by the compiler, which simplifies and speeds up translation of our source code to the PyPy binary interpreter * Win32 now links statically to zlib, expat, bzip, and openssl-1.0.1i. No more missing DLLs * Many issues were resolved_ since the 2.3.1 release in June .. _`whats-new`: http://doc.pypy.org/en/latest/whatsnew-2.4.0.html .. _resolved: https://bitbucket.org/pypy/pypy/issues?status=resolved .. _sandbox: http://doc.pypy.org/en/latest/sandbox.html We have further improvements on the way: rpython file handling, numpy linalg compatibility, as well as improved GC and many smaller improvements. Please try it out and let us know what you think. We especially welcome success stories, we know you are using PyPy, please tell us about it! Cheers The PyPy Team From ian.g.kelly at gmail.com Tue Oct 21 13:09:11 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 21 Oct 2014 11:09:11 -0600 Subject: Is there an easy way to control indents in Python In-Reply-To: <521b537d-c119-4858-8880-d1e1ddb76b55@googlegroups.com> References: <9a0c67be-de3a-4770-bf06-e158783bfff0@googlegroups.com> <54424691$0$12978$c3e8da3$5496439d@news.astraweb.com> <521b537d-c119-4858-8880-d1e1ddb76b55@googlegroups.com> Message-ID: On Tue, Oct 21, 2014 at 2:45 AM, Simon Kennedy wrote: > On Monday, 20 October 2014 18:56:05 UTC+1, Ian wrote: >> Rather, I'm saying that where the blank line is should be the start of >> a new function. There would still be a blank line, just no longer >> inside the function. >> >> Now, maybe you think there should be more blank lines in the above, in >> which case we'll just have to disagree on that point. > > Why did you separate the above 2 sequences of thoughts by a blank line? Is the inherent pause in the communication of your thoughts not also applicable to your code? > > Where we see the pause between thoughts appears to be in a different place. I see them both within the function and between the functions and I assume you see them between the functions only. That makes sense. I see two distinct thoughts in the function that I posted: "build the graph" and "search the graph". The blank line separates them. By my view, a function should represent a single, complete thought. Thus, the function should be broken up at the blank line. From rosuav at gmail.com Tue Oct 21 13:14:13 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 04:14:13 +1100 Subject: PyPy3 2.4.0 released In-Reply-To: <1D51E541-E9DA-4737-91CA-66A2A3EF606E@underboss.org> References: <1D51E541-E9DA-4737-91CA-66A2A3EF606E@underboss.org> Message-ID: On Wed, Oct 22, 2014 at 4:03 AM, Philip Jenvey wrote: > PyPy3 2.4 - Snow White Interesting choice of name. I flipped through some of the release pages for previous versions and couldn't see a pattern to the names; is there a list somewhere of the code names and why they were selected? I'm sure there's a story behind this! ChrisA From chaselton at gmail.com Tue Oct 21 11:32:58 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Tue, 21 Oct 2014 10:32:58 -0500 Subject: Problem with Android Build Message-ID: Hello, If I have a problem with building Python on an Android device, would this be the list to post it to, or should I post it to python-help or python-dev? Thanks! Cyd From sam.raker at gmail.com Tue Oct 21 12:38:57 2014 From: sam.raker at gmail.com (Sam Raker) Date: Tue, 21 Oct 2014 12:38:57 -0400 Subject: Pex import problems Message-ID: Hi all, I'm trying to use Pex (http://pex.readthedocs.org/en/latest/index.html) to include requests in a little script to ping a server from a machine that doesn't come with pip (or much of anything, really) installed. I'm running into problems outputting a pex file that depends on a local script. I've got a command-line file, `client.py`, that can be called with a few command-line options. I can run `pex -r requests -o client.pex -- client.py`, but when I try `./client.pex -h` I get an error about "no such file or directory: '-h'". Ok, next attempt: `pex -r requests -o client.pex -e client` --> "ImportError: No module named client". I dug around in the code a bit, and from what I can tell, `-e FOO` boils down to `__import__(FOO)`, which I can do, both from the interpreter and from a test script. So what am I missing? The only other option I can think of would be: `pex -r requests -o client.pex` & then write a script that calls `client.py` from the pex environment (i.e., `./client.pex client.py -h` or whatever), and bundle the pex file, `client.py`, and the script together. But that seems like a misuse of the tool, at best. Alternatively/additionally: is there any mailing list/help source for pex? It seems like a great project, but I've not been able to find many resources out there, which is why I'm turning to you guys. (Why not just install pip/requests on the target machine? Because this is part of an effort to automate provisioning of a bunch of machines.) (Why not use pants? Because literally all we need is requests, and that seems like overkill.) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rosuav at gmail.com Tue Oct 21 13:36:38 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 04:36:38 +1100 Subject: Problem with Android Build In-Reply-To: References: Message-ID: On Wed, Oct 22, 2014 at 2:32 AM, Cyd Haselton wrote: > Hello, > If I have a problem with building Python on an Android device, would > this be the list to post it to, or should I post it to python-help or > python-dev? Hi! Start here. If we can't help, python-dev might be the next place to ask, but this is the best first option. ChrisA From ned at nedbatchelder.com Tue Oct 21 14:23:22 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Tue, 21 Oct 2014 14:23:22 -0400 Subject: string processing - some problems whenever I have to parse a more complex string In-Reply-To: <2637a169-46a9-4787-8267-ac0775449e7e@googlegroups.com> References: <2637a169-46a9-4787-8267-ac0775449e7e@googlegroups.com> Message-ID: On 10/21/14 10:32 AM, CWr wrote: > Is there any implementation like C++ StringPiece class? Or something like the following behavior: > > >>>> >>>s = StringSlice('abcdef') >>>> >>>s > StringSlice('abcdef') at xxx >>>> >>>s[0] > 'a' >>>> >>>s.chop(1) # chop the first item >>>> >>>s[0] # 'b' is the new first item > 'b' >>>> >>>s[:2] > 'bc' >>>> >>>s.chop(-1) # chop the last item >>>> >>>s[-1] > 'e' >>>> >>>s[1:] > 'cde' >>>> >>>while s[0] != 'e': > s.chop(1) >>>> >>>s[0] > 'e' >>>> >>>s.startswith('e') > True >>>> >>>s.isdigit() > False You could certainly implement a StringSlice object that worked like this. Store the string, the start and end indexes. Override __getitem__ to adjust indexes and slice endpoints, implement chop() to change the start or end indexes. Implementing the string operations would get messy, likely you would materialize the sliced string to make them work. -- Ned Batchelder, http://nedbatchelder.com From chaselton at gmail.com Tue Oct 21 14:12:58 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Tue, 21 Oct 2014 13:12:58 -0500 Subject: Problem with Android Build In-Reply-To: References: Message-ID: On Tue, Oct 21, 2014 at 12:36 PM, Chris Angelico wrote: > On Wed, Oct 22, 2014 at 2:32 AM, Cyd Haselton wrote: >> Hello, >> If I have a problem with building Python on an Android device, would >> this be the list to post it to, or should I post it to python-help or >> python-dev? > > Hi! > > Start here. If we can't help, python-dev might be the next place to > ask, but this is the best first option. > > ChrisA > -- > https://mail.python.org/mailman/listinfo/python-list Thanks! I'm building Python v2.7.8 on my Android device in a fakechroot environment with GCC 4.8.0 and make fails with the following error Could not import runpy module Running the Makefile command (minus the LD_LIBRARY_PATH prepend) produces the same error, but running the same command minus the -S returns a File "..Lib/os.py", line 117, in raise ImportError, 'no os specific module found' I've configured with ./configure --prefix=/usr/python --build=arm-linux-androideabi --host=arm-linux-androideabi --target=arm-linux-androideabi --enable-shared and ./configure --prefix=/usr/python with the same results. The two post-configure makefile edits I've added are: LDFLAGS= -Wl,--allow-shlib-undefined which allows make to continue past an 'undefined reference to sincos' and RUNSHARED= LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/Python/src which prevents the fakechroot environment from breaking I've also commented out the initpwd references in config.c...as Android doesn't do passwords per se. Any help would be appreciated! From ryanshuell at gmail.com Tue Oct 21 17:44:13 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Tue, 21 Oct 2014 14:44:13 -0700 (PDT) Subject: No Error; No Output...Nothing Message-ID: Hey everyone, I'm trying to run this code. import os import pickle #import urllib2 from urllib.request import urlopen #import cookielib import http.cookiejar import re import time import numpy as np #import pylab as pl # symbol - USDEUR=X - problem that the server sometimes returns 0.0 def getSpotPrice(symbol): numberOfAttempts = 0 while numberOfAttempts < 10: url = 'http://download.finance.yahoo.com/d/quotes.csv?s='+symbol+'&f=l1&e=.cs' fxrate_pure = urllib2.urlopen(url).read() fxrate = fxrate_pure.strip() if fxrate != "0.00": return fxrate else: numberOfAttempts += 1 time.sleep(1) raise Exception("Unable to obtain market data from Yahoo! ... wrong ticker???") # symbol = the yahoo ticker; the expected tickers of the components contain alphanumerical characters or dot or hyphen; if the yahoo format changes, nothing is returned def getConstituentsOfAnIndexFromYahoo(symbol): url = 'http://finance.yahoo.com/q/cp?s=%s' % symbol p = re.compile(' and ,
') components = [] pageIndex = 0 finished = False while not finished: if pageIndex == 0: actualUrl = url else: actualUrl = url + "&c=" + str(pageIndex) pageResults = p.findall(urllib2.urlopen(actualUrl).read()) if len(pageResults) == 0: finished = True else: components.extend(pageResults) pageIndex+=1 return components # prices = data[:,6] or prices = data[:, title.index("Adj Close")], pl.num2date(data[:,1]) back dates # syntax http://ichart.yahoo.com/table.csv?s={Yahoo.Symbol.[isin]}&a={Von.M-1}&b={Von.T}&c={Von.J}&d={Bis.M}&e={Bis.T}&f={Bis. J}&g=d&y=0&z=jdsu&ignore=.csv def getNumpyHistoricalTimeseries(symbol,fromDate, toDate): f = urllib2.urlopen('http://ichart.yahoo.com/table.csv?a='+ str(fromDate.month -1) +'&c='+ str(fromDate.year) +'&b=' + str(fromDate.day) + '&e='+ str(toDate.day) + '&d='+ str(toDate.month-1) +'&g=d&f=' + str(toDate.year) + '&s=' + symbol + '&ignore=.csv') header = f.readline().strip().split(",") #return np.loadtxt(f, dtype=np.float, delimiter=",", converters={0: pl.datestr2num}) I commented out the import pylab as pl because I couldn't get the matplotlib.pylab import working. So, anyway, I hit F5, and it seems to run, but it doesn't really do anything. Isn't this either supposed to be downloading data from the web, or throwing an error so I can troubleshoot, and try to figure out what's going on? It's hard to troubleshoot, when you don't get any error. Does this work for others? Thanks. From rosuav at gmail.com Tue Oct 21 17:49:15 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 08:49:15 +1100 Subject: No Error; No Output...Nothing In-Reply-To: References: Message-ID: On Wed, Oct 22, 2014 at 8:44 AM, ryguy7272 wrote: > So, anyway, I hit F5, and it seems to run, but it doesn't really do anything. It defines a few functions, but nothing ever calls them, so you won't see much out of it :) Try adding some code at the bottom that actually calls one of your functions, providing constants for whatever parameters it needs. ChrisA From ckaynor at zindagigames.com Tue Oct 21 17:49:30 2014 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Tue, 21 Oct 2014 14:49:30 -0700 Subject: No Error; No Output...Nothing In-Reply-To: References: Message-ID: On Tue, Oct 21, 2014 at 2:44 PM, ryguy7272 wrote: > I commented out the import pylab as pl because I couldn't get the > matplotlib.pylab import working. So, anyway, I hit F5, and it seems to > run, but it doesn't really do anything. Isn't this either supposed to be > downloading data from the web, or throwing an error so I can troubleshoot, > and try to figure out what's going on? It's hard to troubleshoot, when you > don't get any error. Does this work for others? No where in the code are any of the functions being called, so unless your "F5" is bound to something that will call some functions, I would not expect it to do anything. Chris -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Oct 21 18:03:41 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 21 Oct 2014 18:03:41 -0400 Subject: string processing - some problems whenever I have to parse a more complex string In-Reply-To: <2637a169-46a9-4787-8267-ac0775449e7e@googlegroups.com> References: <2637a169-46a9-4787-8267-ac0775449e7e@googlegroups.com> Message-ID: On 10/21/2014 10:32 AM, CWr wrote: > > Hello together, > > currently I have to parse a string in an atomic way. Normally - in this case too - I have a counter variable to keep the current position inside the string. So far, I think this is the most flexible solution to do some lookaround's inside the string if necessary. Subroutines will be feed by the underlying data and the current position. A subroutine returns a tuple of the new position and the result. But I would like process subroutines with the same flexibillity (slicing/lookaround) but without returning the new position every again. > > Is there any implementation like C++ StringPiece class? I am going to guess that this is a string view class that encapsulates a piece of an underlying class. Otherwise there is no point. A view class depends on a primary, independently accessible class for its data. There are two main categories. A subview gives the primary class interface to a part of the primary data. Numpy had array subviews an I presume you are talking about string subviews here. An altview class gives an alternative interface to the primary data. Dict views are examples. If the primary object is mutable, one reason to use a view instead of a copy is to keep the data for two objects synchronized. This does not apply to strings. Another reason is to save memory space. The downside is that the primary data cannot be erased until *both* objects are deleted. Moreover, if the primary data is small or the subview data is a small fraction of the primary data, the memory saving is small. So small subviews that persist after the primary object may end up costing more memory than they save. This is one reason Python does not have string subview. The numpy array view use case is large subarrays of large arrays that have to persist through a calculation anyway. Another reason Python lack sequence subviews is that the extra data needed for a contiguous slice are only the start and stop indexes. These can easily be manipulated directly without wrapping them in a class. And anyone who does want a method interface can easily create a class to their liking. To answer your question, I tried https://pypi.python.org/pypi?%3Aaction=search&term=string+view&submit=search and did not find anything. 'view' matches the generic use of 'view', as well as 'views', 'viewed', 'viewer', 'review', and 'preview'. The third answer here https://stackoverflow.com/questions/10085568/slices-to-immutable-strings-by-reference-and-not-copy has a StringView class that could be modifed to work on 3.x by removing the unneeded use of buffer. > Or something like the following behavior: >>>> s = StringSlice('abcdef') s = 'abcdef' a, b = 0, len(s) # s start, s end >>>> s > StringSlice('abcdef') at xxx >>>> s[0] s[a] > 'a' >>>> s.chop(1) # chop the first item >>>> s[0] # 'b' is the new first item a += 1 s[a] > 'b' >>>> s[:2] s[a:a+2] > 'bc' >>>> s.chop(-1) # chop the last item >>>> s[-1] b -= 1 s[b-1] > 'e' >>>> s[1:] s[a+1:b] > 'cde' >>>> while s[0] != 'e': > s.chop(1) >>>> s[0] while s[a] != 'e': a += 1 s[a] > 'e' >>>> s.startswith('e') s[a:b].startswith('e') > True >>>> s.isdigit() s[a:b].isdigit() > False > > Subroutines could chop the number of processed items internally if no error occours. > > Another possibillty will be to chop the current item manually. But I don't know how efficient this is in case of large strings. > >>>> while string: > c = string[0] > # process it ... > string = string[1:] This is extremely bad as it replaces the O(n) processing (below) with O(n*n) processing. In general, the right way to linearly process any iterable is for item in iterable: process(c) or sometimes for index, item in enumerate(iterable): process(index, item) or even, for sequences, (but not when the first option above suffices) for index in range(len(sequence)): process(index, sequence) -- Terry Jan Reedy From mmr15 at case.edu Tue Oct 21 17:58:18 2014 From: mmr15 at case.edu (Matthew Ruffalo) Date: Tue, 21 Oct 2014 17:58:18 -0400 Subject: No Error; No Output...Nothing In-Reply-To: References: Message-ID: <5446D6FA.6000103@case.edu> On 10/21/2014 05:44 PM, ryguy7272 wrote: > Hey everyone, I'm trying to run this code. > > ... > > I commented out the import pylab as pl because I couldn't get the matplotlib.pylab import working. So, anyway, I hit F5, and it seems to run, but it doesn't really do anything. Isn't this either supposed to be downloading data from the web, or throwing an error so I can troubleshoot, and try to figure out what's going on? It's hard to troubleshoot, when you don't get any error. Does this work for others? > > Thanks. No, it isn't supposed to be downloading data from the web. You have defined a few functions but you're not actually calling any of them. The script terminates successfully with no output, since there's nothing for it to do after executing your imports and function definitions. Additionally, your attempted use of 'urllib2' inside getConstituentsOfAnIndexFromYahoo will fail. Your import of that module is commented out, since (from your imports) you're presumably using Python 3 and a module with that name no longer exists. Since you have 'from urllib.request import urlopen', you can use the 'urlopen' module without any fully-qualified name. The relevant line in your getConstituentsOfAnIndexFromYahoo function should be 'pageResults = p.findall(urlopen(...'. MMR... From ryanshuell at gmail.com Tue Oct 21 18:15:56 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Tue, 21 Oct 2014 15:15:56 -0700 (PDT) Subject: No Error; No Output...Nothing In-Reply-To: References: Message-ID: On Tuesday, October 21, 2014 5:44:33 PM UTC-4, ryguy7272 wrote: > Hey everyone, I'm trying to run this code. > > > > import os > > import pickle > > #import urllib2 > > from urllib.request import urlopen > > #import cookielib > > import http.cookiejar > > import re > > import time > > import numpy as np > > #import pylab as pl > > > > # symbol - USDEUR=X - problem that the server sometimes returns 0.0 > > def getSpotPrice(symbol): > > numberOfAttempts = 0 > > while numberOfAttempts < 10: > > url = 'http://download.finance.yahoo.com/d/quotes.csv?s='+symbol+'&f=l1&e=.cs' > > fxrate_pure = urllib2.urlopen(url).read() > > fxrate = fxrate_pure.strip() > > if fxrate != "0.00": > > return fxrate > > else: > > numberOfAttempts += 1 > > time.sleep(1) > > raise Exception("Unable to obtain market data from Yahoo! ... wrong ticker???") > > > > # symbol = the yahoo ticker; the expected tickers of the components contain alphanumerical characters or dot or hyphen; if the yahoo format changes, nothing is returned > > def getConstituentsOfAnIndexFromYahoo(symbol): > > url = 'http://finance.yahoo.com/q/cp?s=%s' % symbol > > p = re.compile('') > > components = [] > > pageIndex = 0 > > finished = False > > while not finished: > > if pageIndex == 0: > > actualUrl = url > > else: > > actualUrl = url + "&c=" + str(pageIndex) > > pageResults = p.findall(urllib2.urlopen(actualUrl).read()) > > if len(pageResults) == 0: > > finished = True > > else: > > components.extend(pageResults) > > pageIndex+=1 > > return components > > > > # prices = data[:,6] or prices = data[:, title.index("Adj Close")], pl.num2date(data[:,1]) back dates > > # syntax http://ichart.yahoo.com/table.csv?s={Yahoo.Symbol.[isin]}&a={Von.M-1}&b={Von.T}&c={Von.J}&d={Bis.M}&e={Bis.T}&f={Bis. J}&g=d&y=0&z=jdsu&ignore=.csv > > def getNumpyHistoricalTimeseries(symbol,fromDate, toDate): > > f = urllib2.urlopen('http://ichart.yahoo.com/table.csv?a='+ str(fromDate.month -1) +'&c='+ str(fromDate.year) +'&b=' + str(fromDate.day) + '&e='+ str(toDate.day) + '&d='+ str(toDate.month-1) +'&g=d&f=' + str(toDate.year) + '&s=' + symbol + '&ignore=.csv') > > header = f.readline().strip().split(",") > > #return np.loadtxt(f, dtype=np.float, delimiter=",", converters={0: pl.datestr2num}) > > > > I commented out the import pylab as pl because I couldn't get the matplotlib.pylab import working. So, anyway, I hit F5, and it seems to run, but it doesn't really do anything. Isn't this either supposed to be downloading data from the web, or throwing an error so I can troubleshoot, and try to figure out what's going on? It's hard to troubleshoot, when you don't get any error. Does this work for others? > > > > Thanks. OK. Thanks everyone! From breamoreboy at yahoo.co.uk Tue Oct 21 18:41:09 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 21 Oct 2014 23:41:09 +0100 Subject: No Error; No Output...Nothing In-Reply-To: References: Message-ID: On 21/10/2014 23:15, ryguy7272 wrote: > > OK. Thanks everyone! > I'm pleased to see that you have answers. In return would you please access this list via https://mail.python.org/mailman/listinfo/python-list or read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing and single line paragraphs, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From drsalists at gmail.com Tue Oct 21 19:16:33 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 21 Oct 2014 16:16:33 -0700 Subject: Flush stdin In-Reply-To: <87h9yyf318.fsf@elektro.pacujo.net> References: <87a94rgxi5.fsf@elektro.pacujo.net> <87mw8qfhza.fsf@elektro.pacujo.net> <87h9yyf318.fsf@elektro.pacujo.net> Message-ID: On Mon, Oct 20, 2014 at 9:41 PM, Marko Rauhamaa wrote: > Dan Stromberg : > >> Often with TCP protocols, line buffered is preferred to character >> buffered, > > Terminal devices support line buffering on write. Yes, though that's not the only place it's useful. > Line buffering on read is an illusion created by higher-level libraries. > The low-level read function reads in blocks of bytes. Actually, doesn't line buffering sometimes exist inside an OS kernel? stty/termios/termio/sgtty relate here, for *ix examples. Supporting code: http://stromberg.dnsalias.org/~strombrg/ttype/ It turns on character-at-a-time I/O in the tty driver via a variety of methods for portability. I wrote it in C before I took an interest in Python. Also, here's some supporting documentation: http://man7.org/linux/man-pages/man3/stdout.3.html - excerpt: Indeed, normally terminal input is line buffered in the kernel. But even if line buffering (or even character buffering) were never in the kernel, calling it an illusion is perhaps going a little far. It's useful sometimes, irrespective of where it comes from. "Illusion" has a bit of an undeserved pejorative connotation. >> Also, it's a straightforward way of framing your data, to avoid >> getting messed up by Nagle or fragmentation. > > Nagle affects the communication between the peer OS kernels and isn't > directly related to anything the application does. Actually, Nagle can cause two or more small packets to be merged, which is something an application must be able to deal with, because they could show up in the receiving application as one or more (but anyway: fewer) merged recv()'s. That's one reason why something like http://stromberg.dnsalias.org/~strombrg/bufsock.html can be helpful. > Also, Nagle doesn't > play any role with pipes. Yes, but pipes aren't the only thing involved in the OP's question. You "simplified" the problem down to pipes, but that doesn't really capture the complete essence of the matter. Nagle is one of the reasons. >>> ======================================================================== >>> $ bash ./test.sh | strace python3 ./test.py >>> ... >>> read(0, "x", 4096) = 1 >>> read(0, "x", 4096) = 1 >>> read(0, "x", 4096) = 1 >>> read(0, "x", 4096) = 1 >>> read(0, "x", 4096) = 1 >>> fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 3), ...}) = 0 >>> mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, >>> 0) = 0x7f3143bab000 >>> write(1, "120\n", 4120 >>> ) = 4 >>> ... >> ======================================================================== >> >> This is tremendously inefficient. It demands a context switch for >> every character. > > Inefficiency isn't an issue when you generate one byte a second. Of course, but who's doing one byte per second? You and I in our tests, and perhaps some application developers with remarkably undemanding I/O. That doesn't really mean we should _recommend_ a series of os.read(0, 1)'s. > If data > were generated at a brisker pace, "read(0, ..., 4096)" could get more > bytes at a time. Notice that even if the Python code requests 5 bytes, > CPython requests up to 4096 bytes in a single read. Not if you use os.read(0, 1), for example, which was what you appeared to be recommending. os.read(0, 1) (when on a pipe) makes a call into kernel space via a context switch, once for each os.read(0, 1). I guess I should add that when you do an os.read(0, 1), and see it show up in strace, strace is showing kernel<->userspace interactions, not library stuff, and not stuff in an application that sits above libraries. ltrace shows some of the library stuff, but probably not all of it - I haven't studied ltrace as much as I have strace. Just wondering: Are we helping the OP? From drsalists at gmail.com Tue Oct 21 19:21:01 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 21 Oct 2014 16:21:01 -0700 Subject: Struggling with python-daemon and subprocess module to work together In-Reply-To: References: Message-ID: On Mon, Oct 20, 2014 at 2:16 AM, Praveen Kumar wrote: > I am writing a very basic server side application[0] which get data > from a client and create a virtual machine using provided data and > also tells client about what's going on during *virt-install* command > execution. Previously this basic server is executed using *openvt* but > I thought it would be nice to have a daemon process for it and used > python-daemon. > > Issue I am facing is after some time server will stop sending data to > client which suppose to happen in #120 and get error message "Cannot > run interactive console without a controlling TTY" . I am not able to > figure out issue is occurred due to module or I missed something > during daemon initialization. I believe you either want a pty, to make your interactive application believe it's on a tty, or a redesign. Here's some Python pty code: http://stromberg.dnsalias.org/~strombrg/pypty/ I imagine pexpect might help too, though I tend to favor going directly to a pty. HTH From ben+python at benfinney.id.au Tue Oct 21 20:04:39 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 22 Oct 2014 11:04:39 +1100 Subject: Struggling with python-daemon and subprocess module to work together References: Message-ID: <85tx2x3r6w.fsf@benfinney.id.au> Praveen Kumar writes: > Previously this basic server is executed using *openvt* but I thought > it would be nice to have a daemon process for it and used > python-daemon. An important difference is that a daemon process has no controlling terminal, by definition. > Issue I am facing is after some time server will stop sending data to > client which suppose to happen in #120 and get error message "Cannot > run interactive console without a controlling TTY" . So, if the code you're running inside that daemon process needs access to a terminal, you have at least two options: * If the code really needs to talk on an interactive terminal, fake it with a pseudoterminal, and keep that pseudoterminal (its file handle) open. * If, as is probably the case, the code doesn't actually need to talk on an interactive terminal, cut that part of the code out entirely and the rest will run fine inside the daemon. -- \ ?I may disagree with what you say, but I will defend to the | `\ death your right to mis-attribute this quote to Voltaire.? | _o__) ?Avram Grumer, rec.arts.sf.written, 2000-05-30 | Ben Finney From cs at zip.com.au Tue Oct 21 19:46:56 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 22 Oct 2014 10:46:56 +1100 Subject: Flush stdin In-Reply-To: References: Message-ID: <20141021234656.GA51424@cskk.homeip.net> On 21Oct2014 16:16, Dan Stromberg wrote: [...snip...] >>> This is tremendously inefficient. It demands a context switch for >>> every character. >> >> Inefficiency isn't an issue when you generate one byte a second. > >Of course, but who's doing one byte per second? You and I in our >tests, and perhaps some application developers with remarkably >undemanding I/O. That doesn't really mean we should _recommend_ a >series of os.read(0, 1)'s. Indeed not. But there is one glaring exception: the shell's read builtin. Because it can be interspersed in a script between other input-consuming commands, it _must_ read no more than one line, and therefore is has to read in increments of 1 character. Of course, that says nothing about the upstream write() granularity. I now return y'all to your regularly sheduled nit picking. Cheers, Cameron Simpson If it ain't broken, keep playing with it. From steve+comp.lang.python at pearwood.info Tue Oct 21 21:44:54 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Wed, 22 Oct 2014 12:44:54 +1100 Subject: When to use assert References: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> Message-ID: <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com> Anton wrote: > I use ORM and often need to write a function that either takes an id of > the record or already loaded model object. So I end up writing a piece of > code like below: > > def do_something(instance): > if isinstance(instance_or_id, int): > instance = Model.get(instance) > assert isinstance(instance, Model) > # Code that assumes that instance is an object of type Model > > do_somthing is not a part of public library, though it is a public > function, which can and intended to be used by other programmers; and > assert should never happen if a client uses the function as planned. I think you mean the assert should never fail. That seems like a reasonable use for assert, with a proviso below. It's behaving like a checked comment or a post-condition test: asserting that Model.get returns a Model instance. But, the idea of *requiring* Model.get to return a Model instance may be inadvisable. It goes against duck-typing, and it prevents Model from making some kinds of implementation changes that might break your post-condition that get() always returns an instance. For example, it might return a proxy object instead, and then your assert will fail. > I > wonder if this use-case is controversial to this part: > >> Many people use asserts as a quick and easy way to raise an exception if >> an argument is given the wrong value. But this is wrong, dangerously >> wrong, for two reasons. The first is that AssertionError is usually the >> wrong error to give when testing function arguments. You wouldn't write >> code like this: >> >> if not isinstance(x, int): >> raise AssertionError("not an int") >> >> you'd raise TypeError instead. "assert" raises the wrong sort of >> exception. No, because the nature of the exception depends on the intent of the test and the audience who is expected to see it. In an ideal world, AssertionError should never be seen by the end user, or the developer calling your code (assuming that she obeys the documented requirements of your code). A failed assert should be considered an internal error, which the user never sees. Since the failure: "Model.get has stopped returning Model instances" is likely to be an internal problem ("oops, I broke the get() method, better fix that") rather than an expected error, using assert is okay. What would *not* be okay is something like this: def do_something(instance_or_id): if isinstance(instance_or_id, int): instance = Model.get(instance_or_id) assert isinstance(instance, Model) # Code that assumes that instance is an object of type Model since that fails with (for example) do_something(None): either the assert is not checked at all, and there will be some mysterious failure deep inside your code, or the caller will see AssertionError instead of TypeError, violating user expectations and good design that type errors should raise TypeError. A better way to write this might be to have Model.get() responsible for the error checking, and then just delegate to it: class Model: def get(self, obj): if isinstance(obj, Model): return obj elif isinstance(obj, int): model = Model("do something here") return model raise TypeError('expected an int ID or a Model instance') def do_something(instance_or_id): instance = Model.get(instance_or_id) assert isinstance(instance, Model) # Code that assumes that instance is an object of type Model That means that the logic for what is acceptable as a Model is all in one place, namely the Model.get method, and callers don't need to care about the pre-condition "argument is a Model or an integer ID", they only need to care about the post-condition "result of get() is a Model". -- Steven From rosuav at gmail.com Tue Oct 21 21:53:46 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 12:53:46 +1100 Subject: When to use assert In-Reply-To: <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com> References: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Oct 22, 2014 at 12:44 PM, Steven D'Aprano wrote: > def do_something(instance_or_id): > instance = Model.get(instance_or_id) > assert isinstance(instance, Model) > # Code that assumes that instance is an object of type Model > > > That means that the logic for what is acceptable as a Model is all in one > place, namely the Model.get method, and callers don't need to care about > the pre-condition "argument is a Model or an integer ID", they only need to > care about the post-condition "result of get() is a Model". And at that point, the assertion is redundant, on par with: a = len(seq) assert isinstance(a, int) because you shouldn't have to assert what's part of a function's guarantee. ChrisA From nobody at nowhere.invalid Tue Oct 21 22:49:43 2014 From: nobody at nowhere.invalid (Nobody) Date: Wed, 22 Oct 2014 03:49:43 +0100 Subject: Flush stdin References: Message-ID: On Sat, 18 Oct 2014 18:42:00 -0700, Dan Stromberg wrote: > On Sat, Oct 18, 2014 at 6:34 PM, Dan Stromberg wrote: >>> Once the "nc" process actually write()s the data to its standard >>> output (i.e. desriptor 1, not the "stdout" FILE*) >> I'm not sure why you're excluding stdout, but even if nc is using >> filedes 1 instead of FILE * stdout, isn't it kind of irrelevant? > > On further reflection, isn't it stdio that does the varied buffering, > and filedes 1 that's always unbuffered? IOW, the OP might wish nc was > using 1, but it probably can't be given what they're seeing. Yes. stdio does buffering. Writing to stdout stores data in a buffer; that data should eventually be written to descriptor 1, although perhaps not until immediately prior to termination. Which is probably the cause of the OP's problem. If it is, using a pseudo-tty would probably fix it. At startup, stdin and stdout are line-buffered if they are associated with a tty and fully-buffered otherwise (file, pipe, ...); stderr is unbuffered. At least, this is the case on Unix and Windows. The exact requirements of the C standard are: As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device. From drsalists at gmail.com Tue Oct 21 23:11:34 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 21 Oct 2014 20:11:34 -0700 Subject: Flush stdin In-Reply-To: References: Message-ID: On Tue, Oct 21, 2014 at 7:49 PM, Nobody wrote: > On Sat, 18 Oct 2014 18:42:00 -0700, Dan Stromberg wrote: > >> On Sat, Oct 18, 2014 at 6:34 PM, Dan Stromberg wrote: >>>> Once the "nc" process actually write()s the data to its standard >>>> output (i.e. desriptor 1, not the "stdout" FILE*) >>> I'm not sure why you're excluding stdout, but even if nc is using >>> filedes 1 instead of FILE * stdout, isn't it kind of irrelevant? >> >> On further reflection, isn't it stdio that does the varied buffering, >> and filedes 1 that's always unbuffered? IOW, the OP might wish nc was >> using 1, but it probably can't be given what they're seeing. > > Yes. stdio does buffering. Writing to stdout stores data in a buffer; that > data should eventually be written to descriptor 1, although perhaps not > until immediately prior to termination. > > Which is probably the cause of the OP's problem. Huh. And here I thought I demonstrated elsewhere in this thread, that the buffering between nc and python didn't appear to be the problem. 'found it, here it is again: If I run the following in one tty: nc -l localhost 9000 | /tmp/z ...where /tmp/z has just: #!/usr/bin/python3 import sys for line in sys.stdin.buffer: print(line) And then run the following in another tty on the same computer: while read line; do echo $line; sleep 1; done < /etc/passwd | nc localhost 9000 ...then everything acts line buffered, or perhaps even character buffered (the two are pretty indistinguishable in this test). What I see is my /etc/passwd file popping out of the nc -l side, one line at a time, each line one second apart. I suppose this suggests that it's the client that's sending TCP data that is buffering. That, or we're using two different versions of netcat (there are at least two available). From pkpearson at nowhere.invalid Wed Oct 22 00:57:23 2014 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 22 Oct 2014 04:57:23 GMT Subject: Matplotlib: getting a figure to show without plt.show() Message-ID: I'm using Matplotlib to present a "control" window with clickable buttons, and to plot things in another window when you click buttons, in the style of the code below. I'm ashamed of the stinky way I use "first" to call plt.show the first time data are plotted but then to call fig.canvas.draw for subsequent data plots. Can someone tell me the right way? If I call plt.show every time, then after about 40 plots I get "RuntimeError: maximum recursion depth exceeded while calling a Python object", which makes sense because I'm getting one layer deeper in callbacks with every plot (plt.show doesn't return). But if I call fig.canvas.draw every time, the window for the data plot never appears on my screen. Thanks for any suggestions. ############################## import matplotlib.pyplot as plt from matplotlib.widgets import Button def callback(event): global n, first fig = plt.figure(2) fig.clear() plt.plot([0,1],[0,n]) n += 1 # (Pretending something changes from one plot to the next.) if first: first = False plt.show() else: fig.canvas.draw() global n, first n = 0 first = True fig = plt.figure(1) quit_button = Button(plt.axes([.1,.3,.4,.2]), "Quit") quit_button.on_clicked(lambda x: plt.close("all")) plot_button = Button(plt.axes([.1,.1,.4,.2]), "Plot") plot_button.on_clicked(callback) plt.show() ############################## -- To email me, substitute nowhere->runbox, invalid->com. From marko at pacujo.net Wed Oct 22 01:38:24 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 22 Oct 2014 08:38:24 +0300 Subject: Flush stdin References: <87a94rgxi5.fsf@elektro.pacujo.net> <87mw8qfhza.fsf@elektro.pacujo.net> <87h9yyf318.fsf@elektro.pacujo.net> Message-ID: <871tq0fyun.fsf@elektro.pacujo.net> Dan Stromberg : > On Mon, Oct 20, 2014 at 9:41 PM, Marko Rauhamaa wrote: >> Nagle affects the communication between the peer OS kernels and isn't >> directly related to anything the application does. > > Actually, Nagle can cause two or more small packets to be merged, > which is something an application must be able to deal with, because > they could show up in the receiving application as one or more (but > anyway: fewer) merged recv()'s. Packets have barely anything to do with TCP sockets since they provide an octet stream abstraction. > Of course, but who's doing one byte per second? You and I in our > tests, and perhaps some application developers with remarkably > undemanding I/O. That doesn't really mean we should _recommend_ a > series of os.read(0, 1)'s. No, here's my statement: if you need to process input as soon as it becomes available, you can't use sys.stdin. Instead, you need to use os.read(). You typically supply os.read() with a buffer of a kilobyte or more. Key is, os.read() returns right away if fewer bytes are available. Marko From rosuav at gmail.com Wed Oct 22 02:23:15 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 17:23:15 +1100 Subject: Flush stdin In-Reply-To: <871tq0fyun.fsf@elektro.pacujo.net> References: <87a94rgxi5.fsf@elektro.pacujo.net> <87mw8qfhza.fsf@elektro.pacujo.net> <87h9yyf318.fsf@elektro.pacujo.net> <871tq0fyun.fsf@elektro.pacujo.net> Message-ID: On Wed, Oct 22, 2014 at 4:38 PM, Marko Rauhamaa wrote: > Dan Stromberg : > >> On Mon, Oct 20, 2014 at 9:41 PM, Marko Rauhamaa wrote: >>> Nagle affects the communication between the peer OS kernels and isn't >>> directly related to anything the application does. >> >> Actually, Nagle can cause two or more small packets to be merged, >> which is something an application must be able to deal with, because >> they could show up in the receiving application as one or more (but >> anyway: fewer) merged recv()'s. > > Packets have barely anything to do with TCP sockets since they provide > an octet stream abstraction. TCP does abstract over the individual packets, but they are still important. >> Of course, but who's doing one byte per second? You and I in our >> tests, and perhaps some application developers with remarkably >> undemanding I/O. That doesn't really mean we should _recommend_ a >> series of os.read(0, 1)'s. > > No, here's my statement: if you need to process input as soon as it > becomes available, you can't use sys.stdin. Instead, you need to use > os.read(). > > You typically supply os.read() with a buffer of a kilobyte or more. Key > is, os.read() returns right away if fewer bytes are available. Then your statement is false. Maybe it's not *efficient* if you always use sys.stdin.read(1), but you certainly can do it. It's not that you *need to* use something else. ChrisA From nomail at invalid.com Wed Oct 22 04:27:34 2014 From: nomail at invalid.com (ast) Date: Wed, 22 Oct 2014 10:27:34 +0200 Subject: (-1)**1000 Message-ID: <54476a77$0$21664$426a74cc@news.free.fr> Hello If i am writing (-1)**1000 on a python program, will the interpreter do (-1)*(-1)*...*(-1) or something clever ? In fact i have (-1)**N with N an integer potentially big. I do some tests that suggest that Python is clever thx From nomail at invalid.com Wed Oct 22 04:29:43 2014 From: nomail at invalid.com (ast) Date: Wed, 22 Oct 2014 10:29:43 +0200 Subject: (test) ? a:b Message-ID: <54476af8$0$21651$426a74cc@news.free.fr> Hello Is there in Python something like: j = (j >= 10) ? 3 : j+1; as in C language ? thx From jeanmichel at sequans.com Wed Oct 22 04:32:36 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 22 Oct 2014 10:32:36 +0200 (CEST) Subject: (test) ? a:b In-Reply-To: <54476af8$0$21651$426a74cc@news.free.fr> Message-ID: <696241753.686980.1413966756501.JavaMail.root@sequans.com> ----- Original Message ----- > From: "ast" > To: python-list at python.org > Sent: Wednesday, 22 October, 2014 10:29:43 AM > Subject: (test) ? a:b > > Hello > > Is there in Python something like: > > j = (j >= 10) ? 3 : j+1; > > as in C language ? > > thx j = 3 if j >=10 else j+1 Cheers JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From jeanmichel at sequans.com Wed Oct 22 04:39:04 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 22 Oct 2014 10:39:04 +0200 (CEST) Subject: (-1)**1000 In-Reply-To: <54476a77$0$21664$426a74cc@news.free.fr> Message-ID: <1959912644.694932.1413967144528.JavaMail.root@sequans.com> ----- Original Message ----- > From: "ast" > To: python-list at python.org > Sent: Wednesday, 22 October, 2014 10:27:34 AM > Subject: (-1)**1000 > > Hello > > If i am writing (-1)**1000 on a python program, will the > interpreter do (-1)*(-1)*...*(-1) or something clever ? > > In fact i have (-1)**N with N an integer potentially big. > > I do some tests that suggest that Python is clever > > thx Python will yield the correct results. That is the most clever thing to do. If you really worried about execution speed (I assume that what your question implies), Python may not be the language you need. However, know that there are these modules "numpy" and "scipy" which are used by the scientific community which provide a python interface (it's a python module) but most of the heavy lifting is done in C (you can embed C in python code). For instance http://docs.scipy.org/doc/numpy/reference/generated/numpy.power.html Use this module if speed is what you're looking for. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From rosuav at gmail.com Wed Oct 22 04:54:16 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 19:54:16 +1100 Subject: (-1)**1000 In-Reply-To: <54476a77$0$21664$426a74cc@news.free.fr> References: <54476a77$0$21664$426a74cc@news.free.fr> Message-ID: On Wed, Oct 22, 2014 at 7:27 PM, ast wrote: > If i am writing (-1)**1000 on a python program, will the > interpreter do (-1)*(-1)*...*(-1) or something clever ? > > In fact i have (-1)**N with N an integer potentially big. Exponentiation is far more efficient than the naive implementation of iterated multiplication. Any modern programming language on any modern CPU architecture should be able to handle this kind of thing. But even the naive approach is likely to be fast enough. >>> x=1 >>> for i in range(1000000): x*=-1 I had to go as far as a million iterations before this, implemented purely in Python with absolutely no optimization, demonstrated a visible pause (of about a quarter second) on my not-exactly-new Windows laptop. My Linux desktop, with a rather hotter CPU, has no trouble with a million, so I'd have to go higher to get a pause out of it. And actually, about half of that time is spent in the loop - replacing the assignment with "pass" still leaves half the iteration time. Poor performance is a crime. Python is innocent until proven guilty. And the burden of proof is seldom met. ChrisA From buscacio at gmail.com Wed Oct 22 05:05:25 2014 From: buscacio at gmail.com (buscacio at gmail.com) Date: Wed, 22 Oct 2014 02:05:25 -0700 (PDT) Subject: (test) ? a:b In-Reply-To: <54476af8$0$21651$426a74cc@news.free.fr> References: <54476af8$0$21651$426a74cc@news.free.fr> Message-ID: <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast escreveu: > Hello > > > > Is there in Python something like: > > > > j = (j >= 10) ? 3 : j+1; > > > > as in C language ? > > > > thx without not: j = [j+1, 3][j>=10] with not: j = [3, j+1][not (j>=10)] From __peter__ at web.de Wed Oct 22 05:13:54 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Oct 2014 11:13:54 +0200 Subject: (-1)**1000 References: <54476a77$0$21664$426a74cc@news.free.fr> Message-ID: ast wrote: > If i am writing (-1)**1000 on a python program, will the > interpreter do (-1)*(-1)*...*(-1) or something clever ? > > In fact i have (-1)**N with N an integer potentially big. > > I do some tests that suggest that Python is clever Let's see: $ python3 Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import dis >>> def f(): ... return (-1)**1000 ... >>> dis.dis(f) 2 0 LOAD_CONST 4 (1) 3 RETURN_VALUE So yes, CPython replaces the expression (-1)**1000 with its value during compilation. From rosuav at gmail.com Wed Oct 22 05:15:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 20:15:55 +1100 Subject: (test) ? a:b In-Reply-To: <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: On Wed, Oct 22, 2014 at 8:05 PM, wrote: > Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast escreveu: >> Hello >> >> >> >> Is there in Python something like: >> >> >> >> j = (j >= 10) ? 3 : j+1; >> >> >> >> as in C language ? >> >> >> >> thx > > without not: > j = [j+1, 3][j>=10] > with not: > j = [3, j+1][not (j>=10)] There's a distinct semantic difference there, though. Compare these: /* C */ int x = (y != 0) ? 65536/y : 0; # Python x = 65536/y if y else 0 # Python, your way x = [0, 65536/y][y!=0] Do you see where the problem is? Plus, subscripting a literal list is far less readable than the ternary operator. Also: Please can you avoid Google Groups, or if you must use it, please at least clean up the excessive blank lines before you post. I've left them so you can see what we have to cope with. Thanks! ChrisA From breamoreboy at yahoo.co.uk Wed Oct 22 05:16:07 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 22 Oct 2014 10:16:07 +0100 Subject: (test) ? a:b In-Reply-To: <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: On 22/10/2014 10:05, buscacio at gmail.com wrote: > Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast escreveu: >> Hello >> >> >> >> Is there in Python something like: >> >> >> >> j = (j >= 10) ? 3 : j+1; >> >> >> >> as in C language ? >> >> >> >> thx > > without not: > j = [j+1, 3][j>=10] > with not: > j = [3, j+1][not (j>=10)] > The death penalty should be reintroduced into the UK for two crimes, writing code like the above and using google groups. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From nomail at invalid.com Wed Oct 22 05:14:20 2014 From: nomail at invalid.com (ast) Date: Wed, 22 Oct 2014 11:14:20 +0200 Subject: (test) ? a:b In-Reply-To: <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: <544775ca$0$2146$426a74cc@news.free.fr> a ?crit dans le message de news:7839376e-fc27-4299-ae63-4ddf17ef9a8a at googlegroups.com... > Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast escreveu: >> Hello >> >> >> >> Is there in Python something like: >> >> >> >> j = (j >= 10) ? 3 : j+1; >> >> >> >> as in C language ? >> >> >> >> thx > > without not: > j = [j+1, 3][j>=10] > with not: > j = [3, j+1][not (j>=10)] > Oh it's a trick ! thx From nomail at invalid.com Wed Oct 22 05:27:06 2014 From: nomail at invalid.com (ast) Date: Wed, 22 Oct 2014 11:27:06 +0200 Subject: (-1)**1000 In-Reply-To: References: <54476a77$0$21664$426a74cc@news.free.fr> Message-ID: <5447786d$0$12750$426a74cc@news.free.fr> "Chris Angelico" a ?crit dans le message de news:mailman.15058.1413968065.18130.python-list at python.org... > On Wed, Oct 22, 2014 at 7:27 PM, ast wrote: >> If i am writing (-1)**1000 on a python program, will the >> interpreter do (-1)*(-1)*...*(-1) or something clever ? >> >> In fact i have (-1)**N with N an integer potentially big. > > Exponentiation is far more efficient than the naive implementation of > iterated multiplication. In the very particular case of (-1)**N, I belive that Python check the odd or even parity of N and provides the result accordingly. I tried: >>> (-1)**1000000000000000000000000000000000 1 >>> (-1)**1000000000000000000000000000000001 -1 and it is instantaneous From rosuav at gmail.com Wed Oct 22 05:27:33 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 20:27:33 +1100 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: On Wed, Oct 22, 2014 at 8:16 PM, Mark Lawrence wrote: >> without not: >> j = [j+1, 3][j>=10] >> with not: >> j = [3, j+1][not (j>=10)] >> > > The death penalty should be reintroduced into the UK for two crimes, writing > code like the above and using google groups. No no no. Code like that doesn't deserve death, just community service. I've seen much MUCH worse... where multiple conditional expressions get combined arithmetically, and then the result used somewhere... I also may have been guilty of same, myself, though I'm going to plead the internet's equivalent of the Fifth Amendment to the US Constitution and not incriminate myself by showing the code... ChrisA From __peter__ at web.de Wed Oct 22 06:29:45 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Oct 2014 12:29:45 +0200 Subject: (-1)**1000 References: <54476a77$0$21664$426a74cc@news.free.fr> <5447786d$0$12750$426a74cc@news.free.fr> Message-ID: ast wrote: > > "Chris Angelico" a ?crit dans le message de > news:mailman.15058.1413968065.18130.python-list at python.org... >> On Wed, Oct 22, 2014 at 7:27 PM, ast wrote: >>> If i am writing (-1)**1000 on a python program, will the >>> interpreter do (-1)*(-1)*...*(-1) or something clever ? >>> >>> In fact i have (-1)**N with N an integer potentially big. >> >> Exponentiation is far more efficient than the naive implementation of >> iterated multiplication. > > In the very particular case of (-1)**N, I belive that Python check > the odd or even parity of N and provides the result accordingly. > > I tried: >>>> (-1)**1000000000000000000000000000000000 > 1 >>>> (-1)**1000000000000000000000000000000001 > -1 > > and it is instantaneous Not instantaneous once you defeat the peephole optimizer by introducing a variable: $ python3 -m timeit '(-1)**10000000000000000000000000000000001' 10000000 loops, best of 3: 0.0356 usec per loop $ python3 -m timeit -s'a = 10000000000000000000000000000000001' '(-1)**a' 100000 loops, best of 3: 3.23 usec per loop When you increase the exponent you might discern a pattern: $ python3 -m timeit -s 'a = 10**10' '(-1)**a' 1000000 loops, best of 3: 1.42 usec per loop $ python3 -m timeit -s 'a = 10**100' '(-1)**a' 100000 loops, best of 3: 11.6 usec per loop $ python3 -m timeit -s 'a = 10**1000' '(-1)**a' 10000 loops, best of 3: 101 usec per loop $ python3 -m timeit -s 'a = 10**10000' '(-1)**a' 1000 loops, best of 3: 992 usec per loop That looks like log(a) while a parity check takes constant time: $ python3 -m timeit -s 'a = 10**10' 'a & 1' 10000000 loops, best of 3: 0.124 usec per loop $ python3 -m timeit -s 'a = 10**100' 'a & 1' 10000000 loops, best of 3: 0.124 usec per loop $ python3 -m timeit -s 'a = 10**1000' 'a & 1' 10000000 loops, best of 3: 0.122 usec per loop From __peter__ at web.de Wed Oct 22 06:38:02 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Oct 2014 12:38:02 +0200 Subject: Matplotlib: getting a figure to show without plt.show() References: Message-ID: Peter Pearson wrote: > I'm using Matplotlib to present a "control" window with clickable > buttons, and to plot things in another window when you click buttons, > in the style of the code below. I'm ashamed of the stinky way I > use "first" to call plt.show the first time data are plotted but then > to call fig.canvas.draw for subsequent data plots. > def callback(event): > global n, first > fig = plt.figure(2) > fig.clear() > plt.plot([0,1],[0,n]) > n += 1 # (Pretending something changes from one plot to the next.) > if first: > first = False > plt.show() > else: > fig.canvas.draw() > Can someone tell me the right way? I don't see what's wrong with doing something different the first time around. > If I call plt.show every time, then after about 40 plots I get > "RuntimeError: maximum recursion depth exceeded while calling a Python > object", which makes sense because I'm getting one layer deeper in > callbacks with every plot (plt.show doesn't return). But if I call > fig.canvas.draw every time, the window for the data plot never appears > on my screen. If your backend uses tkinter, then the problem may be that plt.show() starts a new mainloop. Over here this causes the script to hang on termination. Through try-and-error I came up with import matplotlib.pyplot as plt from matplotlib.widgets import Button def callback(event): global n, fig2 if fig2 is None: fig2 = plt.figure(2) fig2.clear() fig2.gca().plot([0, .5, 1], [0, 1/n, 1]) fig2.show() n += 1 n = 1 fig2 = None plt.figure(1) quit_button = Button(plt.axes([.1, .3, .4, .2]), "Quit") quit_button.on_clicked(lambda x: plt.close("all")) plot_button = Button(plt.axes([.1, .1, .4, .2]), "Plot") plot_button.on_clicked(callback) plt.show() If you don't mind that the second window shows up immediately you can modify that to import matplotlib.pyplot as plt from matplotlib.widgets import Button def callback(event): global n fig2.clear() fig2.gca().plot([0, .5, 1], [0, 1/n, 1]) fig2.show() n += 1 n = 1 plt.figure(1) quit_button = Button(plt.axes([.1, .3, .4, .2]), "Quit") quit_button.on_clicked(lambda x: plt.close("all")) plot_button = Button(plt.axes([.1, .1, .4, .2]), "Plot") plot_button.on_clicked(callback) fig2 = plt.figure(2) plt.show() and thus avoid the special case. As I'm not an expert for matplotlib you might also post your question on the matplotlib mailing list. From motoom at xs4all.nl Wed Oct 22 06:38:56 2014 From: motoom at xs4all.nl (Michiel Overtoom) Date: Wed, 22 Oct 2014 12:38:56 +0200 Subject: (-1)**1000 In-Reply-To: References: <54476a77$0$21664$426a74cc@news.free.fr> <5447786d$0$12750$426a74cc@news.free.fr> Message-ID: <091815A9-38E8-4F34-AB03-F9402551DF9F@xs4all.nl> On Oct 22, 2014, at 12:29, Peter Otten wrote: > That looks like log(a) while a parity check takes constant time: > $ python3 -m timeit -s 'a = 10**10' 'a & 1' Do you mean 'parity' as in http://en.wikipedia.org/wiki/Parity_bit ? Because a parity bit denotes whether the *number* of '1' bits is even or odd, not the value of the least significant bit. Greetings, -- "You can't actually make computers run faster, you can only make them do less." - RiderOfGiraffes From python.list at tim.thechases.com Wed Oct 22 06:43:02 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 22 Oct 2014 05:43:02 -0500 Subject: (-1)**1000 In-Reply-To: References: <54476a77$0$21664$426a74cc@news.free.fr> <5447786d$0$12750$426a74cc@news.free.fr> Message-ID: <20141022054302.6daea15b@bigbox.christie.dr> On 2014-10-22 12:29, Peter Otten wrote: > That looks like log(a) while a parity check takes constant time: > > $ python3 -m timeit -s 'a = 10**10' 'a & 1' > 10000000 loops, best of 3: 0.124 usec per loop > $ python3 -m timeit -s 'a = 10**100' 'a & 1' > 10000000 loops, best of 3: 0.124 usec per loop > $ python3 -m timeit -s 'a = 10**1000' 'a & 1' > 10000000 loops, best of 3: 0.122 usec per loop Just for the record, this is a one-bit even/odd check (which is useful & fast in this sign-of-large-exponent case), not a parity check (which typically counts the number of "1" bits, adds the parity bit, and asserts the result is even) -tkc From marko at pacujo.net Wed Oct 22 06:57:28 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 22 Oct 2014 13:57:28 +0300 Subject: Flush stdin References: <87a94rgxi5.fsf@elektro.pacujo.net> <87mw8qfhza.fsf@elektro.pacujo.net> <87h9yyf318.fsf@elektro.pacujo.net> Message-ID: <87y4s8wew7.fsf@elektro.pacujo.net> Dan Stromberg : > On Mon, Oct 20, 2014 at 9:41 PM, Marko Rauhamaa wrote: >> Terminal devices support line buffering on write. > Yes, though that's not the only place it's useful. > >> Line buffering on read is an illusion created by higher-level libraries. >> The low-level read function reads in blocks of bytes. > > Actually, doesn't line buffering sometimes exist inside an OS kernel? > stty/termios/termio/sgtty relate here, for *ix examples. Supporting > code: http://stromberg.dnsalias.org/~strombrg/ttype/ It turns on > character-at-a-time I/O in the tty driver via a variety of methods for > portability. I wrote it in C before I took an interest in Python. I was being sloppy in my TTY terminology. A TTY device is running inside the kernel and thus "writes" by copying bytes from its kernel buffer into the user space when the user space process calls read(2). Marko From __peter__ at web.de Wed Oct 22 07:02:09 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 22 Oct 2014 13:02:09 +0200 Subject: (-1)**1000 References: <54476a77$0$21664$426a74cc@news.free.fr> <5447786d$0$12750$426a74cc@news.free.fr> <091815A9-38E8-4F34-AB03-F9402551DF9F@xs4all.nl> Message-ID: Michiel Overtoom wrote: > > On Oct 22, 2014, at 12:29, Peter Otten wrote: > >> That looks like log(a) while a parity check takes constant time: >> $ python3 -m timeit -s 'a = 10**10' 'a & 1' > > > Do you mean 'parity' as in http://en.wikipedia.org/wiki/Parity_bit ? > Because a parity bit denotes whether the *number* of '1' bits is even or > odd, not the value of the least significant bit. No, I meant the lsb. The OP introduced the term 'parity'; not sure if that was erroneous, too, or if there is an angle to the problem that escapes me. From ned at nedbatchelder.com Wed Oct 22 07:30:40 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Wed, 22 Oct 2014 07:30:40 -0400 Subject: (test) ? a:b In-Reply-To: <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: On 10/22/14 5:05 AM, buscacio at gmail.com wrote: > Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast escreveu: >> Hello >> >> >> >> Is there in Python something like: >> >> >> >> j = (j >= 10) ? 3 : j+1; >> >> >> >> as in C language ? >> >> >> >> thx > > without not: > j = [j+1, 3][j>=10] > with not: > j = [3, j+1][not (j>=10)] > Why on earth would you recommend this outdated hack, when there's a true conditional operator? j = 3 if j >= 10 else j+1 Of course, many people feel like the conditional operator isn't worth the squished-up unreadability, but if someone asks for a conditional operator, at least show them one! -- Ned Batchelder, http://nedbatchelder.com From wxjmfauth at gmail.com Wed Oct 22 07:35:59 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Wed, 22 Oct 2014 04:35:59 -0700 (PDT) Subject: (-1)**1000 In-Reply-To: References: <54476a77$0$21664$426a74cc@news.free.fr> Message-ID: <6629338b-2e89-4b38-a139-1d56d6c80a77@googlegroups.com> Le mercredi 22 octobre 2014 10:54:51 UTC+2, Chris Angelico a ?crit : > > > > Poor performance is a crime. Python is innocent until proven guilty. > And the burden of proof is seldom met. > > >>> timeit.repeat("('abc'*1000 +'z')[:-1]") [1.4107052484530875, 1.3924774653606349, 1.3934069318508087] >>> timeit.repeat("('abc'*1000 +'EURO')[:-1]") [5.427585698976522, 5.39270195514851, 5.40894516974776] >>> Not only this disastrous (and systematic) behaviour is explainable, I have no problem to explain this to those who wish to listen. jmf From diyaraik at gmail.com Wed Oct 22 07:36:47 2014 From: diyaraik at gmail.com (diyaraik at gmail.com) Date: Wed, 22 Oct 2014 04:36:47 -0700 (PDT) Subject: 403 forbidden error Message-ID: <82d4292e-10de-4d47-882e-bab75777fbfe@googlegroups.com> Hai, Could anyone please help me to resolve 403 forbidden error while logging into an application. Following is the error details: Traceback (most recent call last): File "./example6.py", line 18, in response = urllib2.urlopen(req) File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen return _opener.open(url, data, timeout) File "/usr/lib/python2.7/urllib2.py", line 406, in open response = meth(req, response) File "/usr/lib/python2.7/urllib2.py", line 519, in http_response 'http', request, response, code, msg, hdrs) File "/usr/lib/python2.7/urllib2.py", line 444, in error return self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain result = func(*args) File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 403: FORBIDDEN Sorry if the question is not relevant as im new to python. Regards, Diya From breamoreboy at yahoo.co.uk Wed Oct 22 07:41:49 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 22 Oct 2014 12:41:49 +0100 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: On 22/10/2014 10:27, Chris Angelico wrote: > On Wed, Oct 22, 2014 at 8:16 PM, Mark Lawrence wrote: >>> without not: >>> j = [j+1, 3][j>=10] >>> with not: >>> j = [3, j+1][not (j>=10)] >>> >> >> The death penalty should be reintroduced into the UK for two crimes, writing >> code like the above and using google groups. > > No no no. Code like that doesn't deserve death, just community > service. I've seen much MUCH worse... where multiple conditional > expressions get combined arithmetically, and then the result used > somewhere... I also may have been guilty of same, myself, though I'm > going to plead the internet's equivalent of the Fifth Amendment to the > US Constitution and not incriminate myself by showing the code... > > ChrisA > Perhaps you're correct. Is there anything worse than looking at a dreadful piece of code that makes no sense at all and knowing that you'd written it six months earlier? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From marko at pacujo.net Wed Oct 22 07:41:58 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 22 Oct 2014 14:41:58 +0300 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: <87siigwcu1.fsf@elektro.pacujo.net> Ned Batchelder : > Why on earth would you recommend this outdated hack, when there's a > true conditional operator? [...] if someone asks for a conditional > operator, at least show them one! No good deed goes unpunished. Marko From breamoreboy at yahoo.co.uk Wed Oct 22 07:45:03 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 22 Oct 2014 12:45:03 +0100 Subject: (test) ? a:b In-Reply-To: <544775ca$0$2146$426a74cc@news.free.fr> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <544775ca$0$2146$426a74cc@news.free.fr> Message-ID: On 22/10/2014 10:14, ast wrote: > > a ?crit dans le message de > news:7839376e-fc27-4299-ae63-4ddf17ef9a8a at googlegroups.com... >> Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast escreveu: >>> Hello >>> >>> >>> >>> Is there in Python something like: >>> >>> >>> >>> j = (j >= 10) ? 3 : j+1; >>> >>> >>> >>> as in C language ? >>> >>> >>> >>> thx >> >> without not: >> j = [j+1, 3][j>=10] >> with not: >> j = [3, j+1][not (j>=10)] >> > > Oh it's a trick ! > thx IMHO it's just dreadful. Why people insist on messing around like this I really don't know, it just drives me nuts. Also would you please access this list via https://mail.python.org/mailman/listinfo/python-list or read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double line spacing and single line paragraphs, thanks. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From novozhiloffvadim at gmail.com Wed Oct 22 08:12:08 2014 From: novozhiloffvadim at gmail.com (novozhiloffvadim at gmail.com) Date: Wed, 22 Oct 2014 05:12:08 -0700 (PDT) Subject: Problems with selenium 2 and python 3.4.1 Message-ID: Hi all, i have a little problem. I have a simple automation to fill login form fields. Actually, it passes good, but there's the problem. I need to see actual output in my console after the script filled fields, like "Logged in successfully" or "Username not found". I tried many stuff, but nothing worked this way, my last try was while loop and it works great, but only when I have positive result. I wrote a second condition, but when I type incorrect data, it drives me crazy to see all these errors in my console. So here's the code and part of output, any help or thoughts would be appreciated. from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException baseurl = "http://www.somesite/login" email = input("Type an email: ") password = input("Type a password: ") xpaths = { 'loginBox' : "//input[@id='session_email']", 'passwordBox' : "//input[@id='session_password']", 'submitButton' : "//input[@class='ufs-but']", 'success' : "//div[@class='flash-message success']", 'error' : "//span[@class='form_error']" } mydriver = webdriver.Firefox() mydriver.get(baseurl) mydriver.find_element_by_xpath(xpaths['loginBox']).send_keys(email) mydriver.find_element_by_xpath(xpaths['passwordBox']).send_keys(password) mydriver.find_element_by_xpath(xpaths['submitButton']).click() while mydriver.find_element_by_xpath(xpaths['success']): print("Success") if mydriver.find_element_by_xpath(xpaths['error']): print("No") And there's what I got when I try to interrupt an error: File "ab.py", line 32, in while mydriver.find_element_by_xpath(xpaths['success']): File "/usr/local/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/webdriver/remote/webdriver.py", line 230, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "/usr/local/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/webdriver/remote/webdriver.py", line 662, in find_element {'using': by, 'value': value})['value'] File "/usr/local/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/webdriver/remote/webdriver.py", line 173, in execute self.error_handler.check_response(response) File "/usr/local/lib/python3.4/site-packages/selenium-2.43.0-py3.4.egg/selenium/webdriver/remote/errorhandler.py", line 166, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: 'Unable to locate element: {"method":"xpath","selector":"//div[@class=\'flash-message success\']"}' ; Stacktrace: at FirefoxDriver.prototype.findElementInternal_ (file:///tmp/tmpjax8kj1u/extensions/fxdriver at googlecode.com/components/driver-component.js:9618:26) at FirefoxDriver.prototype.findElement (file:///tmp/tmpjax8kj1u/extensions/fxdriver at googlecode.com/components/driver-component.js:9627:3) at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpjax8kj1u/extensions/fxdriver at googlecode.com/components/command-processor.js:11612:16) at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpjax8kj1u/extensions/fxdriver at googlecode.com/components/command-processor.js:11617:7) at DelayedCommand.prototype.execute/< (file:///tmp/tmpjax8kj1u/extensions/fxdriver at googlecode.com/components/command-processor.js:11559:5) As I said, successfull result ain't a problem. Hope to get any help. From rosuav at gmail.com Wed Oct 22 08:43:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 22 Oct 2014 23:43:29 +1100 Subject: 403 forbidden error In-Reply-To: <82d4292e-10de-4d47-882e-bab75777fbfe@googlegroups.com> References: <82d4292e-10de-4d47-882e-bab75777fbfe@googlegroups.com> Message-ID: On Wed, Oct 22, 2014 at 10:36 PM, wrote: > Could anyone please help me to resolve 403 forbidden error while logging into an application. That comes down tot he server you're talking to. Maybe your username/password is wrong, or maybe you need to send back a cookie, or something. If you do some web searches, you should be able to find some info about HTTP; the better you understand the protocol, the more you'll understand of what urllib2 is saying. ChrisA From rustompmody at gmail.com Wed Oct 22 09:16:10 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 22 Oct 2014 06:16:10 -0700 (PDT) Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> On Wednesday, October 22, 2014 5:01:08 PM UTC+5:30, Ned Batchelder wrote: > On 10/22/14 5:05 AM, buscacio wrote: > > Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast escreveu: > >> Hello > >> Is there in Python something like: > >> j = (j >= 10) ? 3 : j+1; > >> as in C language ? > >> thx > > without not: > > j = [j+1, 3][j>=10] > > with not: > > j = [3, j+1][not (j>=10)] > Why on earth would you recommend this outdated hack, when there's a true > conditional operator? To learn a bit about the interchangeability of control and data structures? [Just playing devil's advocate] Doesn't change the fact that as a practice it should not be done From ian.g.kelly at gmail.com Wed Oct 22 10:23:50 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 22 Oct 2014 08:23:50 -0600 Subject: (-1)**1000 In-Reply-To: References: <54476a77$0$21664$426a74cc@news.free.fr> <5447786d$0$12750$426a74cc@news.free.fr> <091815A9-38E8-4F34-AB03-F9402551DF9F@xs4all.nl> Message-ID: On Wed, Oct 22, 2014 at 5:02 AM, Peter Otten <__peter__ at web.de> wrote: > Michiel Overtoom wrote: > >> >> On Oct 22, 2014, at 12:29, Peter Otten wrote: >> >>> That looks like log(a) while a parity check takes constant time: >>> $ python3 -m timeit -s 'a = 10**10' 'a & 1' >> >> >> Do you mean 'parity' as in http://en.wikipedia.org/wiki/Parity_bit ? >> Because a parity bit denotes whether the *number* of '1' bits is even or >> odd, not the value of the least significant bit. > > No, I meant the lsb. The OP introduced the term 'parity'; not sure if that > was erroneous, too, or if there is an angle to the problem that escapes me. Since the OP just wrote "parity", not "parity bit", I would assume they meant as in http://en.wikipedia.org/wiki/Parity_(mathematics) From ian.g.kelly at gmail.com Wed Oct 22 10:29:13 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 22 Oct 2014 08:29:13 -0600 Subject: (-1)**1000 In-Reply-To: <20141022054302.6daea15b@bigbox.christie.dr> References: <54476a77$0$21664$426a74cc@news.free.fr> <5447786d$0$12750$426a74cc@news.free.fr> <20141022054302.6daea15b@bigbox.christie.dr> Message-ID: On Wed, Oct 22, 2014 at 4:43 AM, Tim Chase wrote: > On 2014-10-22 12:29, Peter Otten wrote: >> That looks like log(a) while a parity check takes constant time: >> >> $ python3 -m timeit -s 'a = 10**10' 'a & 1' >> 10000000 loops, best of 3: 0.124 usec per loop >> $ python3 -m timeit -s 'a = 10**100' 'a & 1' >> 10000000 loops, best of 3: 0.124 usec per loop >> $ python3 -m timeit -s 'a = 10**1000' 'a & 1' >> 10000000 loops, best of 3: 0.122 usec per loop > > Just for the record, this is a one-bit even/odd check Which is just a verbose way of writing "parity check", even if that phrase is usually used in another context. From random832 at fastmail.us Wed Oct 22 11:01:05 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Wed, 22 Oct 2014 11:01:05 -0400 Subject: Flush stdin In-Reply-To: References: <87a94rgxi5.fsf@elektro.pacujo.net> <87mw8qfhza.fsf@elektro.pacujo.net> <87h9yyf318.fsf@elektro.pacujo.net> Message-ID: <1413990065.999305.182031041.04A9A27F@webmail.messagingengine.com> On Tue, Oct 21, 2014, at 19:16, Dan Stromberg wrote: > Actually, doesn't line buffering sometimes exist inside an OS kernel? > stty/termios/termio/sgtty relate here, for *ix examples. Supporting > code: http://stromberg.dnsalias.org/~strombrg/ttype/ It turns on > character-at-a-time I/O in the tty driver via a variety of methods for > portability. I wrote it in C before I took an interest in Python. Yes, and 90% of the time, when someone says they want to "flush stdin", what they really want to do is go to the next line after they've sloppily read part of the line they're on (and the behavior they are seeing that they object to is that their next read function reads the rest of the current line). The appropriate course of action in these cases is to actually read to the next newline and discard the data, not to do any kind of flush. From ned at nedbatchelder.com Wed Oct 22 11:01:28 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Wed, 22 Oct 2014 11:01:28 -0400 Subject: (-1)**1000 In-Reply-To: <5447786d$0$12750$426a74cc@news.free.fr> References: <54476a77$0$21664$426a74cc@news.free.fr> <5447786d$0$12750$426a74cc@news.free.fr> Message-ID: On 10/22/14 5:27 AM, ast wrote: > > "Chris Angelico" a ?crit dans le message de > news:mailman.15058.1413968065.18130.python-list at python.org... >> On Wed, Oct 22, 2014 at 7:27 PM, ast wrote: >>> If i am writing (-1)**1000 on a python program, will the >>> interpreter do (-1)*(-1)*...*(-1) or something clever ? >>> >>> In fact i have (-1)**N with N an integer potentially big. >> >> Exponentiation is far more efficient than the naive implementation of >> iterated multiplication. > > In the very particular case of (-1)**N, I belive that Python check > the odd or even parity of N and provides the result accordingly. > > I tried: >>>> (-1)**1000000000000000000000000000000000 > 1 >>>> (-1)**1000000000000000000000000000000001 > -1 > > and it is instantaneous > > Keep in mind that actually calculating the exponentiation wouldn't do 1000000000000000000000000000000000 multiplications anyway: the clever way to do integer powers is by squaring based on the binary representation of the exponent. It's explained here: http://stackoverflow.com/a/101613/14343 So even if Python is actually calculating the value, it's only doing 75 multiplications or so. -- Ned Batchelder, http://nedbatchelder.com From alister.nospam.ware at ntlworld.com Wed Oct 22 11:12:36 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Wed, 22 Oct 2014 15:12:36 GMT Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: On Wed, 22 Oct 2014 12:41:49 +0100, Mark Lawrence wrote: > On 22/10/2014 10:27, Chris Angelico wrote: >> On Wed, Oct 22, 2014 at 8:16 PM, Mark Lawrence >> wrote: >>>> without not: >>>> j = [j+1, 3][j>=10] >>>> with not: >>>> j = [3, j+1][not (j>=10)] >>>> >>>> >>> The death penalty should be reintroduced into the UK for two crimes, >>> writing code like the above and using google groups. >> >> No no no. Code like that doesn't deserve death, just community service. >> I've seen much MUCH worse... where multiple conditional expressions get >> combined arithmetically, and then the result used somewhere... I also >> may have been guilty of same, myself, though I'm going to plead the >> internet's equivalent of the Fifth Amendment to the US Constitution and >> not incriminate myself by showing the code... >> >> ChrisA >> >> > Perhaps you're correct. Is there anything worse than looking at a > dreadful piece of code that makes no sense at all and knowing that you'd > written it six months earlier? looking a a dreadful piece of unreadable & unfathomable code & knowing you wrote it only Yesterday ;-) -- Chamberlain's Laws: (1) The big guys always win. (2) Everything tastes more or less like chicken. From rosuav at gmail.com Wed Oct 22 11:18:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 23 Oct 2014 02:18:42 +1100 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: On Thu, Oct 23, 2014 at 2:12 AM, alister wrote: >> Perhaps you're correct. Is there anything worse than looking at a >> dreadful piece of code that makes no sense at all and knowing that you'd >> written it six months earlier? > > looking a a dreadful piece of unreadable & unfathomable code & knowing > you wrote it only Yesterday ;-) Sounds like you have some experience with Perl... ChrisA From alister.nospam.ware at ntlworld.com Wed Oct 22 11:24:41 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Wed, 22 Oct 2014 15:24:41 GMT Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: On Thu, 23 Oct 2014 02:18:42 +1100, Chris Angelico wrote: > On Thu, Oct 23, 2014 at 2:12 AM, alister > wrote: >>> Perhaps you're correct. Is there anything worse than looking at a >>> dreadful piece of code that makes no sense at all and knowing that >>> you'd written it six months earlier? >> >> looking a a dreadful piece of unreadable & unfathomable code & knowing >> you wrote it only Yesterday ;-) > > Sounds like you have some experience with Perl... > > ChrisA Never met the girl I deny everything. Actual no experience in perl & my professional programming experience is limited to 8 bit assembler (68XX & 8051) 30 years ago. c & c++ were too low level for my liking so I started looking at python for fun on my Linux box's and was blown away by its smoothness. -- On the other hand, life can be an endless parade of TRANSSEXUAL QUILTING BEES aboard a cruise ship to DISNEYWORLD if only we let it!! From marko at pacujo.net Wed Oct 22 11:28:43 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 22 Oct 2014 18:28:43 +0300 Subject: Flush stdin References: <87a94rgxi5.fsf@elektro.pacujo.net> <87mw8qfhza.fsf@elektro.pacujo.net> <87h9yyf318.fsf@elektro.pacujo.net> Message-ID: <87tx2wdsyc.fsf@elektro.pacujo.net> random832 at fastmail.us: > Yes, and 90% of the time, when someone says they want to "flush > stdin", what they really want to do is go to the next line after > they've sloppily read part of the line they're on (and the behavior > they are seeing that they object to is that their next read function > reads the rest of the current line). The appropriate course of action > in these cases is to actually read to the next newline and discard the > data, not to do any kind of flush. I'm not sure I have seen that. However, somewhat analogously, there are linux text utilities that read a number of lines and leave the input intact. Since you can't really effectively read lines, the utilities routinely read past the designated endpoint and then seek back to the end of the line. For example, consider this script: seq 20000 >test.dat { head -n 5 >/dev/null head -n 5 } /dev/null head -n 5 } I get: 1861 1862 1863 1864 because you can't seek back a pipe. The first "head" command has greedily read in the first 1860 lines and the second one continues where the first one left off. Marko From steve+comp.lang.python at pearwood.info Wed Oct 22 11:49:31 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 23 Oct 2014 02:49:31 +1100 Subject: When to use assert References: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5447d20c$0$12997$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Wed, Oct 22, 2014 at 12:44 PM, Steven D'Aprano > wrote: >> def do_something(instance_or_id): >> instance = Model.get(instance_or_id) >> assert isinstance(instance, Model) >> # Code that assumes that instance is an object of type Model >> >> >> That means that the logic for what is acceptable as a Model is all in one >> place, namely the Model.get method, and callers don't need to care about >> the pre-condition "argument is a Model or an integer ID", they only need >> to care about the post-condition "result of get() is a Model". > > And at that point, the assertion is redundant, on par with: > > a = len(seq) > assert isinstance(a, int) > > because you shouldn't have to assert what's part of a function's > guarantee. That depends on how well you trust the function, how paranoid you are, and whether you wish to include a checked comment, among other considerations. I'd prefer to write the above than: a = len(seq) # At this point, a is an int. because comments inside code that aren't checked are technically known as "lies" . Ha ha only serious. I wouldn't write such a comment for len() since I would expect anyone reading the code to know what len() does, but the same doesn't necessarily apply for every function call I make. Checking the post-condition of a built-in like len() is too paranoid for my tastes, as len() enforces the rule that __len__() methods return a non-negative integer, and there are millions of lines of Python code around the world calling len(). Somebody surely have noticed by now if len() violated that post-condition. But for a function from my own code base, where I might only have dozens of users (oh to have that many!) and fewer unit tests than perhaps I ought to, I might not be quite so confident that the assertion was redundant. To err is human, and so there are occasions when it is appropriate to trust but verify. As I wrote: This is why assert can be divisive. Since we can vary in our confidence about the correctness of code, one person's useful assertion may be another person's useless runtime test. http://import-that.dreamwidth.org/676.html -- Steven From a24061 at ducksburg.com Wed Oct 22 11:51:06 2014 From: a24061 at ducksburg.com (Adam Funk) Date: Wed, 22 Oct 2014 16:51:06 +0100 Subject: Permissions on files installed by pip? References: Message-ID: On 2014-10-17, Jean-Michel Pichavant wrote: > ----- Original Message ----- >> From: "Adam Funk" >> To: python-list at python.org >> Sent: Thursday, 16 October, 2014 9:29:46 PM >> Subject: Permissions on files installed by pip? >> >> I've been using the python-nltk package on Ubuntu, but I need ntlk >> 3.0 >> now. I used 'sudo aptitude purge python-nltk' to get rid of my >> existing installation, & followed instructions on the nltk website >> [1] >> starting at step 4 (since I already have python-pip & python-numpy >> packages installed). >> >> $ sudo pip install -U >> >> I couldn't get it to work, until I realized that the permissions & >> ownership on /usr/local/lib/python2.7/dist-packages were 'drwx--S--- >> root staff'. A 'chmod -R a+rX' on that directory seems to have fixed >> it. Is it normal for sudo pip install to set the permissions that >> way, or did I do something wrong? > > On debian wheezy: > > ls -al /usr/local/lib/python2.7/dist-packages > > drwxrwsr-x 5 root staff 4.0K Jun 30 15:16 ./ > > I'm not sure pip is responsible for this anyway, so my money goes on "you did something wrong" :) Probably something to do with the way I have sudo set up then. Thanks. -- Everybody says sex is obscene. The only true obscenity is war. --- Henry Miller From rosuav at gmail.com Wed Oct 22 12:01:17 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 23 Oct 2014 03:01:17 +1100 Subject: When to use assert In-Reply-To: <5447d20c$0$12997$c3e8da3$5496439d@news.astraweb.com> References: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com> <5447d20c$0$12997$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Oct 23, 2014 at 2:49 AM, Steven D'Aprano wrote: > Chris Angelico wrote: > >> And at that point, the assertion is redundant, on par with: >> >> a = len(seq) >> assert isinstance(a, int) >> >> because you shouldn't have to assert what's part of a function's >> guarantee. > > That depends on how well you trust the function, how paranoid you are, and > whether you wish to include a checked comment, among other considerations. > I'd prefer to write the above than: > > a = len(seq) > # At this point, a is an int. > > because comments inside code that aren't checked are technically known > as "lies" . Ha ha only serious. > ... > Checking the post-condition of a built-in like len() is too paranoid for my > tastes... > > As I wrote: > > This is why assert can be divisive. Since we can vary in our > confidence about the correctness of code, one person's useful > assertion may be another person's useless runtime test. I agree that the assert is preferable to the comment. But maybe my level of paranoia is just lower than most people's, as I wouldn't bother checking the post-conditions of pretty much anything. Do you put these assertions every time you call the function? Every time you're depending on its return value? At what point should you stop writing Python code and start using a language with a lot more boilerplate and checking (I believe Haskell fits that, though I'm not overly familiar with the language)? This is the job of a test suite. You don't pepper your code with assertions to the effect that "I just pushed something onto my queue, it should now have this item in it"; you create a test case for it, and verify your function there. In the rest of the code, you trust that your test suite passes, and don't waste time with assertions. Or is that insufficiently paranoid? ChrisA From drsalists at gmail.com Wed Oct 22 12:09:31 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Wed, 22 Oct 2014 09:09:31 -0700 Subject: (test) ? a:b In-Reply-To: <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: On Wed, Oct 22, 2014 at 2:05 AM, wrote: > Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast escreveu: >> Hello >> >> >> >> Is there in Python something like: >> >> >> >> j = (j >= 10) ? 3 : j+1; >> >> >> >> as in C language ? >> >> >> >> thx > > without not: > j = [j+1, 3][j>=10] > with not: > j = [3, j+1][not (j>=10)] This is not very readable, and eagerly evaluates the two list values. A proper ternary operator will not evaluate the unused candidate-result. This matters a little for performance, but matters more if one or both of the candidate results have side-effects. It's better to use "j = 3 if j >= 10 else j + 1". What you've suggested here was one of the ternary operator workarounds before a true ternary operator was introduced in 2.5. I don't use Python's ternary operator much though - I tend to find if+else more clear, and it shows up well in a debugger. The ternary operator tends to lead to long one-liners (especially if nested!), which are usually best avoided. I'd even go so far as to say that most uses of a ternary operator probably should be a small function. It's slower, but it lends itself to DRY and abstraction better. From drsalists at gmail.com Wed Oct 22 12:18:24 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Wed, 22 Oct 2014 09:18:24 -0700 Subject: When to use assert In-Reply-To: References: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com> <5447d20c$0$12997$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Wed, Oct 22, 2014 at 9:01 AM, Chris Angelico wrote: > On Thu, Oct 23, 2014 at 2:49 AM, Steven D'Aprano > wrote: >> Chris Angelico wrote: > I agree that the assert is preferable to the comment. But maybe my > level of paranoia is just lower than most people's, as I wouldn't > bother checking the post-conditions of pretty much anything. Do you > put these assertions every time you call the function? Every time > you're depending on its return value? At what point should you stop > writing Python code and start using a language with a lot more > boilerplate and checking (I believe Haskell fits that, though I'm not > overly familiar with the language)? I like to use assertions and "if cond: raise ValueError('foo')" a lot. I think Eiffel may be the poster-child for a language with pre-conditions, post-conditions and assertions. I think you're in good company - a lot of developers don't use assertions much. I like assertions, because they tend to stop bugs pretty quickly. If you have 3 functions, one calling another calling another, assertions in each can keep you from having to backtrack among them when debugging, instead going directly to the problem's source. > This is the job of a test suite. Test suites are great, and I can't really question your reliance on them. I love having lots of automated tests. But for the reason I described above, I still like having lots of assertions. > You don't pepper your code with > assertions to the effect that "I just pushed something onto my queue, > it should now have this item in it"; you create a test case for it, > and verify your function there. In the rest of the code, you trust > that your test suite passes, and don't waste time with assertions. I wouldn't test that a value was added to a queue immediately after adding it. That's excessive, and may even require an abstraction violation. But if, for example, I have a string with 3 known-good values, I'll if/elif/elif/else, and make the else raise an AssertionError. The assertion should never fire, but if the code changes, it could, and if there's a typo somewhere, it could then too. > Or is that insufficiently paranoid? With good tests, you're probably fine. From steve+comp.lang.python at pearwood.info Wed Oct 22 12:28:48 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 23 Oct 2014 03:28:48 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: <5447db41$0$13000$c3e8da3$5496439d@news.astraweb.com> Ned Batchelder wrote: > On 10/22/14 5:05 AM, buscacio at gmail.com wrote: >> without not: >> j = [j+1, 3][j>=10] >> with not: >> j = [3, j+1][not (j>=10)] >> > > Why on earth would you recommend this outdated hack, when there's a true > conditional operator? > > j = 3 if j >= 10 else j+1 I think that's a bit harsh. Especially since this appears to have been Buscacio's first post here. Hopefully not his(?) last post! The old (b, a)[condition] idiom is not outdated for anyone supporting Python 2.4, and I wouldn't call it a hack. Indexing into a sequence with a bool is basic to Python's semantics: True and False are ints equal to 1 and 0 respectively. It's also a technique easily extensible to more than two values: '01TX'[n % 4] is in my opinion more readable than: i = n % 4 '0' if i == 0 else '1' if i == 1 else 'T' if i == 3 else 'X' > Of course, many people feel like the conditional operator isn't worth > the squished-up unreadability, but if someone asks for a conditional > operator, at least show them one! The advantage of the `x if cond else y` operator is that it is a short-cutting operator, it doesn't evaluate either x or y unless needed. But for many cases that's not important, and in those cases I won't say I prefer the old (y, x)[cond] idiom, but neither do I dislike it. -- Steven From juan0christian at gmail.com Wed Oct 22 12:38:12 2014 From: juan0christian at gmail.com (Juan Christian) Date: Wed, 22 Oct 2014 14:38:12 -0200 Subject: Python 3.4.1 and blitzdb issue In-Reply-To: References: Message-ID: Oh yes, and here is what the call to the API returns: {"adult":false,"also_known_as":["George Walton Lucas Jr. "],"biography":"Arguably the most important film innovator in the history of the medium, George Lucas continually \"pushed the envelope\" of filmmaking technology since his early days as a student at U.S.C. Considered a wunderkind by his contemporaries, he had a much harder time communicating his vision to studio executives, whose meddling managed to compromise each of his first three feature directing efforts in some way. The monumental success of \"Star Wars\" (1977) ushered in the era of the \"summer blockbuster,\" which, despite the later popularity of low budget independent films, was still the prevailing mentality powering the Hollywood engine.\n\nThough he set the tone and established the expectations which influenced studios to devote the bulk of their resources to films designed to blast off into hyperspace for spectacular profits, it was doubtful that a film as revolutionary as \"Star Wars\" was in its day could get made in the later blockbuster assembly line climate of the new millennium.","birthday":"1944-05-14","deathday":"","homepage":"","id":1,"imdb_id":"nm0000184","name":"George Lucas","place_of_birth":"Modesto - California - USA","popularity":2.185575,"profile_path":"/rJ1zvSeZfge0mHtLnzJn4Mkw18S.jpg"} On Wed, Oct 22, 2014 at 2:34 PM, Juan Christian wrote: > Testing code: > > CODE --------------------- > > #!/usr/bin/env > > import requests > from blitzdb import Document, FileBackend > > > API_URL = 'http://api.themoviedb.org/3' > API_KEY = 'ddf3xxxxxxxx0289' > > > class Actor(Document): > pass > > > def get_actor(_id): > r = requests.get('{}/person/{}?api_key={}'.format(API_URL, str(_id), > API_KEY)) > return r.json() > > > actor_1 = Actor(get_actor(1)) > actor_2 = Actor(get_actor(2)) > > backend = FileBackend("db.blitz") > actor_1.save(backend) > actor_2.save(backend) > > print(backend.get(Actor,{'imdb_id' : 'nm0000184'})) > print('\n') > print(backend.get(Actor,{'imdb_id' : 'nm0000434'})) > > > OUTPUT --------------------- > > Warning: cjson could not be imported, CJsonSerializer will not be > available. > Traceback (most recent call last): > File ".\uff.py", line 27, in > print(backend.get(Actor,{'imdb_id' : 'nm0000184'})) > File "C:\Python34\lib\site-packages\blitzdb\backends\file\backend.py", > line 456, in get > raise cls.DoesNotExist > blitzdb.document.DoesNotExist: DoesNotExist(Actor) > > > QUESTION --------------------- > > Why the output says that Actor doesn't exists when I already added it here > 'actor_1.save(backend)' and 'actor_2.save(backend)' > -------------- next part -------------- An HTML attachment was scrubbed... URL: From pkpearson at nowhere.invalid Wed Oct 22 12:38:17 2014 From: pkpearson at nowhere.invalid (Peter Pearson) Date: 22 Oct 2014 16:38:17 GMT Subject: Matplotlib: getting a figure to show without plt.show() References: Message-ID: On Wed, 22 Oct 2014 12:38:02 +0200, Peter Otten wrote: > Peter Pearson wrote: [snip] >> def callback(event): >> global n, first >> fig = plt.figure(2) >> fig.clear() >> plt.plot([0,1],[0,n]) >> n += 1 # (Pretending something changes from one plot to the next.) >> if first: >> first = False >> plt.show() >> else: >> fig.canvas.draw() >> >> Can someone tell me the right way? [snip] > def callback(event): > global n, fig2 > > if fig2 is None: > fig2 = plt.figure(2) > > fig2.clear() > fig2.gca().plot([0, .5, 1], [0, 1/n, 1]) > fig2.show() Thank you for pointing out two useful things: * I like fig2.gca().plot better than plt.plot, since it makes it clear that I'm talking about fig2 and not some other part of the vast and inscrutable plt kingdom. * fig2.show is different from plt.show, and in fact this solves my problem exactly, since fig2.show returns immediately. By the way, I will dispense with your "if fig2 is None" test. In real life, I say something like fig2 = plt.figure("Packet Sizes"). If a figure named "Packet Sizes" doesn't exist, plt.figure creates it, otherwise it returns a pointer to the existing figure -- *and* it titles the figure's window with "Packet Sizes" rather than "2". [snip] > As I'm not an expert for matplotlib you might also post your question on the > matplotlib mailing list. Sound advice. Next time. Thanks again. -- To email me, substitute nowhere->runbox, invalid->com. From rosuav at gmail.com Wed Oct 22 12:40:53 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 23 Oct 2014 03:40:53 +1100 Subject: (test) ? a:b In-Reply-To: <5447db41$0$13000$c3e8da3$5496439d@news.astraweb.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <5447db41$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, Oct 23, 2014 at 3:28 AM, Steven D'Aprano wrote: > It's also a technique easily extensible to more than two > values: > > '01TX'[n % 4] > > is in my opinion more readable than: > > i = n % 4 > '0' if i == 0 else '1' if i == 1 else 'T' if i == 3 else 'X' That's true when it's fundamentally arithmetic. But part of that readability difference is the redundancy in the second one. What if it weren't so redundant? 'Negative' if x < 0 else 'Low' if x < 10 else 'Mid' if x < 20 else 'High' You can't easily turn that into a dict lookup, nor indexing. It's either a chained if/elif tree or nested if/else expressions, which come to the same thing. So I'd say all the techniques have their advantages and disadvantages. The most important thing to note is where they differ in semantics, like the short-circuiting of if/else. ChrisA From juan0christian at gmail.com Wed Oct 22 12:34:20 2014 From: juan0christian at gmail.com (Juan Christian) Date: Wed, 22 Oct 2014 14:34:20 -0200 Subject: Python 3.4.1 and blitzdb issue Message-ID: Testing code: CODE --------------------- #!/usr/bin/env import requests from blitzdb import Document, FileBackend API_URL = 'http://api.themoviedb.org/3' API_KEY = 'ddf3xxxxxxxx0289' class Actor(Document): pass def get_actor(_id): r = requests.get('{}/person/{}?api_key={}'.format(API_URL, str(_id), API_KEY)) return r.json() actor_1 = Actor(get_actor(1)) actor_2 = Actor(get_actor(2)) backend = FileBackend("db.blitz") actor_1.save(backend) actor_2.save(backend) print(backend.get(Actor,{'imdb_id' : 'nm0000184'})) print('\n') print(backend.get(Actor,{'imdb_id' : 'nm0000434'})) OUTPUT --------------------- Warning: cjson could not be imported, CJsonSerializer will not be available. Traceback (most recent call last): File ".\uff.py", line 27, in print(backend.get(Actor,{'imdb_id' : 'nm0000184'})) File "C:\Python34\lib\site-packages\blitzdb\backends\file\backend.py", line 456, in get raise cls.DoesNotExist blitzdb.document.DoesNotExist: DoesNotExist(Actor) QUESTION --------------------- Why the output says that Actor doesn't exists when I already added it here 'actor_1.save(backend)' and 'actor_2.save(backend)' -------------- next part -------------- An HTML attachment was scrubbed... URL: From stephane at wirtel.be Wed Oct 22 12:45:55 2014 From: stephane at wirtel.be (=?utf-8?q?St=C3=A9phane?= Wirtel) Date: Wed, 22 Oct 2014 18:45:55 +0200 Subject: Python 3.4.1 and blitzdb issue In-Reply-To: References: Message-ID: <02D417B2-C402-4D61-A722-343ABDAA78E7@wirtel.be> Maybe ask on the project on github. Andreas is a good guy and will reply asap. On 22 Oct 2014, at 18:34, Juan Christian wrote: > Testing code: > > CODE --------------------- > > #!/usr/bin/env > > import requests > from blitzdb import Document, FileBackend > > > API_URL = 'http://api.themoviedb.org/3' > API_KEY = 'ddf3xxxxxxxx0289' > > > class Actor(Document): > pass > > > def get_actor(_id): > r = requests.get('{}/person/{}?api_key={}'.format(API_URL, str(_id), > API_KEY)) > return r.json() > > > actor_1 = Actor(get_actor(1)) > actor_2 = Actor(get_actor(2)) > > backend = FileBackend("db.blitz") > actor_1.save(backend) > actor_2.save(backend) > > print(backend.get(Actor,{'imdb_id' : 'nm0000184'})) > print('\n') > print(backend.get(Actor,{'imdb_id' : 'nm0000434'})) > > > OUTPUT --------------------- > > Warning: cjson could not be imported, CJsonSerializer will not be > available. > Traceback (most recent call last): > File ".\uff.py", line 27, in > print(backend.get(Actor,{'imdb_id' : 'nm0000184'})) > File "C:\Python34\lib\site-packages\blitzdb\backends\file\backend.py", > line 456, in get > raise cls.DoesNotExist > blitzdb.document.DoesNotExist: DoesNotExist(Actor) > > > QUESTION --------------------- > > Why the output says that Actor doesn't exists when I already added it > here > 'actor_1.save(backend)' and 'actor_2.save(backend)' > -- > https://mail.python.org/mailman/listinfo/python-list -- St?phane Wirtel - http://wirtel.be - @matrixise From tjreedy at udel.edu Wed Oct 22 13:15:22 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 22 Oct 2014 13:15:22 -0400 Subject: (-1)**1000 In-Reply-To: <54476a77$0$21664$426a74cc@news.free.fr> References: <54476a77$0$21664$426a74cc@news.free.fr> Message-ID: On 10/22/2014 4:27 AM, ast wrote: > Hello > > If i am writing (-1)**1000 on a python program, will the > interpreter do (-1)*(-1)*...*(-1) or something clever ? The answer depends on the implementation. > In fact i have (-1)**N with N an integer potentially big. > > I do some tests that suggest that Python is clever You probably mean "CPython is clever". Other implementations may or may not have the same optimizations. -- Terry Jan Reedy From torriem at gmail.com Wed Oct 22 13:16:48 2014 From: torriem at gmail.com (Michael Torrie) Date: Wed, 22 Oct 2014 11:16:48 -0600 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <544775ca$0$2146$426a74cc@news.free.fr> Message-ID: <5447E680.3030100@gmail.com> On 10/22/2014 05:45 AM, Mark Lawrence wrote: >>> without not: >>> j = [j+1, 3][j>=10] >>> with not: >>> j = [3, j+1][not (j>=10)] >>> >> >> Oh it's a trick ! >> thx > > IMHO it's just dreadful. Why people insist on messing around like this > I really don't know, it just drives me nuts. This actually was the standard idiom used by many python programs before Python 2.5. But I agree. Don't do this anymore! Python has a ternary if expression. Also the ternary if expression does, I believe short-circuit logic, so the non-chosen path is not calculated. This hack does not. Could lead to interesting bugs depending on your assumptions. From alister.nospam.ware at ntlworld.com Wed Oct 22 14:03:57 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Wed, 22 Oct 2014 18:03:57 GMT Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <5447db41$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 23 Oct 2014 03:28:48 +1100, Steven D'Aprano wrote: >> Why on earth would you recommend this outdated hack, when there's a >> true conditional operator? >> >> j = 3 if j >= 10 else j+1 > > I think that's a bit harsh. Especially since this appears to have been > Buscacio's first post here. Hopefully not his(?) last post! > > The old (b, a)[condition] idiom is not outdated for anyone supporting > Python 2.4, and I wouldn't call it a hack. Indexing into a sequence with > a bool is basic to Python's semantics: True and False are ints equal to > 1 and 0 respectively. It's also a technique easily extensible to more > than two values: > > '01TX'[n % 4] > > is in my opinion more readable than: > > i = n % 4 '0' if i == 0 else '1' if i == 1 else 'T' if i == 3 else > 'X' chained ternary operations are evil no mater what style or language they are written in as they rapidly become confusing & unreadable "Readability counts" in my opinion they are better written as nested if statements -- Ambiguity: Telling the truth when you don't mean to. From bc at freeuk.com Wed Oct 22 14:08:40 2014 From: bc at freeuk.com (BartC) Date: Wed, 22 Oct 2014 19:08:40 +0100 Subject: (test) ? a:b In-Reply-To: <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> Message-ID: "Rustom Mody" wrote in message news:7d2ea3c1-504e-4f5c-8338-501b1483df38 at googlegroups.com... > On Wednesday, October 22, 2014 5:01:08 PM UTC+5:30, Ned Batchelder wrote: >> On 10/22/14 5:05 AM, buscacio wrote: >> > Em quarta-feira, 22 de outubro de 2014 06h29min55s UTC-2, ast >> > escreveu: >> >> Hello >> >> Is there in Python something like: >> >> j = (j >= 10) ? 3 : j+1; >> >> as in C language ? >> >> thx >> > without not: >> > j = [j+1, 3][j>=10] >> > with not: >> > j = [3, j+1][not (j>=10)] > >> Why on earth would you recommend this outdated hack, when there's a true >> conditional operator? > > > To learn a bit about the interchangeability of control and data > structures? > > [Just playing devil's advocate] But it doesn't do the same thing. Comparing: x = cond ? f() : g(); # C version with x = [f(), g()] [cond] the latter evaluates both f() and g() instead of just one. Apart from being inefficient, it can have unintended side-effects. -- Bartc From mmr15 at case.edu Wed Oct 22 14:27:00 2014 From: mmr15 at case.edu (Matthew Ruffalo) Date: Wed, 22 Oct 2014 14:27:00 -0400 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <5447db41$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5447F6F4.7080607@case.edu> On 10/22/2014 12:40 PM, Chris Angelico wrote: > That's true when it's fundamentally arithmetic. But part of that > readability difference is the redundancy in the second one. What if it > weren't so redundant? > > 'Negative' if x < 0 else 'Low' if x < 10 else 'Mid' if x < 20 else 'High' > > You can't easily turn that into a dict lookup, nor indexing. It's > either a chained if/elif tree or nested if/else expressions, which > come to the same thing. No, you can't turn that into a dict lookup, but this is one of the canonical use cases for the bisect module: >>> from bisect import bisect >>> breakpoints = [0, 10, 20] >>> labels = ['Negative', 'Low', 'Mid', 'High'] >>> values = [-5, 5, 15, 25] >>> [labels[bisect(breakpoints, value)] for value in values] ['Negative', 'Low', 'Mid', 'High'] It's also worth noting that using bisect is O(log(n)) instead of O(n), but if you're going to hit a point where the asymptotic behavior matters I'm sure you will have long since abandoned a manually-written if/elif chain. MMR... From rosuav at gmail.com Wed Oct 22 14:30:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 23 Oct 2014 05:30:01 +1100 Subject: (test) ? a:b In-Reply-To: <5447F6F4.7080607@case.edu> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <5447db41$0$13000$c3e8da3$5496439d@news.astraweb.com> <5447F6F4.7080607@case.edu> Message-ID: On Thu, Oct 23, 2014 at 5:27 AM, Matthew Ruffalo wrote: > On 10/22/2014 12:40 PM, Chris Angelico wrote: >> That's true when it's fundamentally arithmetic. But part of that >> readability difference is the redundancy in the second one. What if it >> weren't so redundant? >> >> 'Negative' if x < 0 else 'Low' if x < 10 else 'Mid' if x < 20 else 'High' >> >> You can't easily turn that into a dict lookup, nor indexing. It's >> either a chained if/elif tree or nested if/else expressions, which >> come to the same thing. > No, you can't turn that into a dict lookup, but this is one of the > canonical use cases for the bisect module: > >>>> from bisect import bisect >>>> breakpoints = [0, 10, 20] >>>> labels = ['Negative', 'Low', 'Mid', 'High'] >>>> values = [-5, 5, 15, 25] >>>> [labels[bisect(breakpoints, value)] for value in values] > ['Negative', 'Low', 'Mid', 'High'] > > It's also worth noting that using bisect is O(log(n)) instead of O(n), > but if you're going to hit a point where the asymptotic behavior matters > I'm sure you will have long since abandoned a manually-written if/elif > chain. Indeed. If the performance is making any difference, something's gone wrong. I'm seeing that as not significantly clearer than the chained if/else statement or expression: you need a list of breakpoints and a list of results, which need to be kept in sync. But there's probably no ideal solution to this. ChrisA From luc2 at nospam.invalid Wed Oct 22 14:43:14 2014 From: luc2 at nospam.invalid (luc2) Date: 22 Oct 2014 18:43:14 GMT Subject: setuptools + data_files = 2 Message-ID: <5447fac2$0$2384$426a74cc@news.free.fr> hello, would you know how to make data_files work in setuptools ? i can't figure out how to put datas in the generated .tar.gz $ find . ./hello ./hello/__init__.py ./share ./share/test_file.txt ./setup.py $ cat ./hello/__init__.py def hello(): print( 'hello' ) $ cat ./share/test_file.txt this is a test $ cat ./hello/setup.py from setuptools import setup, find_packages setup( name = "Hello", version = "0.1", packages = find_packages(), data_files = [ ( 'share', ['share/test_file.txt'] ) ] ) $ python setup.py sdist $ tar tvf dist/Hello-0.1.tar.gz | grep test_file.txt $ echo "no test_file.txt :-(" From ned at nedbatchelder.com Wed Oct 22 16:11:45 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Wed, 22 Oct 2014 16:11:45 -0400 Subject: (test) ? a:b In-Reply-To: <5447db41$0$13000$c3e8da3$5496439d@news.astraweb.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <5447db41$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/22/14 12:28 PM, Steven D'Aprano wrote: > Ned Batchelder wrote: > >> On 10/22/14 5:05 AM, buscacio at gmail.com wrote: > >>> without not: >>> j = [j+1, 3][j>=10] >>> with not: >>> j = [3, j+1][not (j>=10)] >>> >> >> Why on earth would you recommend this outdated hack, when there's a true >> conditional operator? >> >> j = 3 if j >= 10 else j+1 > > I think that's a bit harsh. Especially since this appears to have been > Buscacio's first post here. Hopefully not his(?) last post! You are right, it sounds a bit harsh. Sorry. -- Ned Batchelder, http://nedbatchelder.com From Seymore4Head at Hotmail.invalid Wed Oct 22 16:30:37 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 16:30:37 -0400 Subject: I am out of trial and error again Lists Message-ID: def nametonumber(name): lst=[""] for x,y in enumerate (name): lst=lst.append(y) print (lst) return (lst) a=["1-800-getcharter"] print (nametonumber(a))#18004382427837 The syntax for when to use a () and when to use [] still throws me a curve. For now, I am trying to end up with a list that has each character in "a" as a single item. I get: None None From joel.goldstick at gmail.com Wed Oct 22 16:57:00 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Wed, 22 Oct 2014 16:57:00 -0400 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On Wed, Oct 22, 2014 at 4:30 PM, Seymore4Head wrote: > def nametonumber(name): > lst=[""] > for x,y in enumerate (name): > lst=lst.append(y) > print (lst) > return (lst) > a=["1-800-getcharter"] > print (nametonumber(a))#18004382427837 > > > The syntax for when to use a () and when to use [] still throws me a > curve. () is tuples which are immutable which means that the items can't be changed. [] is list which means that each item can be changed. Tuples are useful because they can be used as keys in dictionaries and are guarantied not to change. Lists are useful because they can be updated. What you are doing confuses me. You don't use x, which is the enumerated value. FIrst lst should be lst = [] . You don't need to set the first element in the list to an empty string. You just want to establish that you have an empty list called lst Second, you don't need lst = lst.append(y) because you can just say lst.append(y). This will append the y value to the end of the list. As to converting letters to the corresponding numbers on a phone keypad, you don't show you code here for that > > For now, I am trying to end up with a list that has each character in > "a" as a single item. > > I get: > None > None > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From Seymore4Head at Hotmail.invalid Wed Oct 22 17:04:00 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 17:04:00 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Wed, 22 Oct 2014 16:57:00 -0400, Joel Goldstick wrote: >On Wed, Oct 22, 2014 at 4:30 PM, Seymore4Head > wrote: >> def nametonumber(name): >> lst=[""] >> for x,y in enumerate (name): >> lst=lst.append(y) >> print (lst) >> return (lst) >> a=["1-800-getcharter"] >> print (nametonumber(a))#18004382427837 >> >> >> The syntax for when to use a () and when to use [] still throws me a >> curve. >() is tuples which are immutable which means that the items can't be >changed. [] is list which means that each item can be changed. >Tuples are useful because they can be used as keys in dictionaries and >are guarantied not to change. Lists are useful because they can be >updated. > >What you are doing confuses me. You don't use x, which is the enumerated value. > >FIrst lst should be lst = [] . You don't need to set the first >element in the list to an empty string. You just want to establish >that you have an empty list called lst >Second, you don't need lst = lst.append(y) because you can just say >lst.append(y). This will append the y value to the end of the list. >As to converting letters to the corresponding numbers on a phone >keypad, you don't show you code here for that >> >> For now, I am trying to end up with a list that has each character in >> "a" as a single item. >> >> I get: >> None >> None >> -- >> https://mail.python.org/mailman/listinfo/python-list The lst=lst.append(y) Was the mistake I never could see. I am using enumerate just for practice. To me that is just as easy as typing len(something) and it seems more flexible. and.......the reason I don't show the code for the conversions is that I haven't got that far yet. :) Thank you From breamoreboy at yahoo.co.uk Wed Oct 22 17:28:04 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 22 Oct 2014 22:28:04 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 22/10/2014 21:57, Joel Goldstick wrote: > On Wed, Oct 22, 2014 at 4:30 PM, Seymore4Head > wrote: >> def nametonumber(name): >> lst=[""] >> for x,y in enumerate (name): >> lst=lst.append(y) >> print (lst) >> return (lst) >> a=["1-800-getcharter"] >> print (nametonumber(a))#18004382427837 >> >> >> The syntax for when to use a () and when to use [] still throws me a >> curve. > () is tuples which are immutable which means that the items can't be > changed. [] is list which means that each item can be changed. > Tuples are useful because they can be used as keys in dictionaries and > are guarantied not to change. Lists are useful because they can be > updated. > This is wrong, commas define tuples. type mytest.py a = 1, 2 print(type(a)) c:\Users\Mark\MyPython>mytest.py -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From sohcahtoa82 at gmail.com Wed Oct 22 17:35:18 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Wed, 22 Oct 2014 14:35:18 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: <32d4b0d0-2293-4f2b-bbe3-04d76affd795@googlegroups.com> On Wednesday, October 22, 2014 2:06:35 PM UTC-7, Seymore4Head wrote: > On Wed, 22 Oct 2014 16:57:00 -0400, Joel Goldstick > wrote: > > >On Wed, Oct 22, 2014 at 4:30 PM, Seymore4Head > > wrote: > >> def nametonumber(name): > >> lst=[""] > >> for x,y in enumerate (name): > >> lst=lst.append(y) > >> print (lst) > >> return (lst) > >> a=["1-800-getcharter"] > >> print (nametonumber(a))#18004382427837 > >> > >> > >> The syntax for when to use a () and when to use [] still throws me a > >> curve. > >() is tuples which are immutable which means that the items can't be > >changed. [] is list which means that each item can be changed. > >Tuples are useful because they can be used as keys in dictionaries and > >are guarantied not to change. Lists are useful because they can be > >updated. > > > >What you are doing confuses me. You don't use x, which is the enumerated value. > > > >FIrst lst should be lst = [] . You don't need to set the first > >element in the list to an empty string. You just want to establish > >that you have an empty list called lst > >Second, you don't need lst = lst.append(y) because you can just say > >lst.append(y). This will append the y value to the end of the list. > >As to converting letters to the corresponding numbers on a phone > >keypad, you don't show you code here for that > >> > >> For now, I am trying to end up with a list that has each character in > >> "a" as a single item. > >> > >> I get: > >> None > >> None > >> -- > >> https://mail.python.org/mailman/listinfo/python-list > > The lst=lst.append(y) > Was the mistake I never could see. > > I am using enumerate just for practice. To me that is just as easy as > typing len(something) and it seems more flexible. > > and.......the reason I don't show the code for the conversions is that > I haven't got that far yet. :) > > Thank you I'm still confused as to why you're using enumerate. Using it when you don't need to for "practice" just seems strange. You don't even need to use len(something) in your case. You should just be using 'for y in name:' if you don't need that x. Enumerate is essentially just a shortcut to zipping a range based on the length. For example... for x, y in enumerate(name): is equivalent to: for x, y in zip(range(len(name)), name): And both are pointless if you're not using the x. Also, is there a reason why you're defining 'a' to be a list with a single string value, rather than just defining it as a string? It seems like you should probably just have: a = "1-800-getcharter" From Seymore4Head at Hotmail.invalid Wed Oct 22 17:38:11 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 17:38:11 -0400 Subject: I am out of trial and error again Lists References: <32d4b0d0-2293-4f2b-bbe3-04d76affd795@googlegroups.com> Message-ID: On Wed, 22 Oct 2014 14:35:18 -0700 (PDT), sohcahtoa82 at gmail.com wrote: >On Wednesday, October 22, 2014 2:06:35 PM UTC-7, Seymore4Head wrote: >> On Wed, 22 Oct 2014 16:57:00 -0400, Joel Goldstick >> wrote: >> >> >On Wed, Oct 22, 2014 at 4:30 PM, Seymore4Head >> > wrote: >> >> def nametonumber(name): >> >> lst=[""] >> >> for x,y in enumerate (name): >> >> lst=lst.append(y) >> >> print (lst) >> >> return (lst) >> >> a=["1-800-getcharter"] >> >> print (nametonumber(a))#18004382427837 >> >> >> >> >> >> The syntax for when to use a () and when to use [] still throws me a >> >> curve. >> >() is tuples which are immutable which means that the items can't be >> >changed. [] is list which means that each item can be changed. >> >Tuples are useful because they can be used as keys in dictionaries and >> >are guarantied not to change. Lists are useful because they can be >> >updated. >> > >> >What you are doing confuses me. You don't use x, which is the enumerated value. >> > >> >FIrst lst should be lst = [] . You don't need to set the first >> >element in the list to an empty string. You just want to establish >> >that you have an empty list called lst >> >Second, you don't need lst = lst.append(y) because you can just say >> >lst.append(y). This will append the y value to the end of the list. >> >As to converting letters to the corresponding numbers on a phone >> >keypad, you don't show you code here for that >> >> >> >> For now, I am trying to end up with a list that has each character in >> >> "a" as a single item. >> >> >> >> I get: >> >> None >> >> None >> >> -- >> >> https://mail.python.org/mailman/listinfo/python-list >> >> The lst=lst.append(y) >> Was the mistake I never could see. >> >> I am using enumerate just for practice. To me that is just as easy as >> typing len(something) and it seems more flexible. >> >> and.......the reason I don't show the code for the conversions is that >> I haven't got that far yet. :) >> >> Thank you > >I'm still confused as to why you're using enumerate. Using it when you don't need to for "practice" just seems strange. You don't even need to use len(something) in your case. You should just be using 'for y in name:' if you don't need that x. Enumerate is essentially just a shortcut to zipping a range based on the length. For example... > >for x, y in enumerate(name): > >is equivalent to: > >for x, y in zip(range(len(name)), name): > >And both are pointless if you're not using the x. > >Also, is there a reason why you're defining 'a' to be a list with a single string value, rather than just defining it as a string? It seems like you should probably just have: > >a = "1-800-getcharter" The lst=lst part was throwing an error I didn't understand. That was the only reason I added brackets around the 'a'. I was getting in to trial and error stuff. Mostly error. From Seymore4Head at Hotmail.invalid Wed Oct 22 18:30:17 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 18:30:17 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: One more question. if y in str(range(10) Why doesn't that work. I commented it out and just did it "long hand" def nametonumber(name): lst=[] nx=[] for x in (name): lst.append(x) for y in (lst): #if y in str(range(10)): if y in "1234567890": nx.append(y) if y in " -()": nx.append(y) if y in "abc": nx.append("2") if y in "def": nx.append("3") if y in "ghi": nx.append("4") if y in "jkl": nx.append("5") if y in "mno": nx.append("6") if y in "pqrs": nx.append("7") if y in "tuv": nx.append("8") if y in "wxyz": nx.append("9") number="".join(str(e) for e in nx) return (number) a="1-800-getcharter" print (nametonumber(a))#1800 438 2427 837 a="1-800-leo laporte" print (nametonumber(a)) a="1 800 callaprogrammer" print (nametonumber(a)) From Seymore4Head at Hotmail.invalid Wed Oct 22 18:32:02 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 18:32:02 -0400 Subject: I am out of trial and error again Lists References: Message-ID: BTW I know I didn't check for Caps yet. On Wed, 22 Oct 2014 18:30:17 -0400, Seymore4Head wrote: >On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head > wrote: > >One more question. >if y in str(range(10) >Why doesn't that work. >I commented it out and just did it "long hand" > >def nametonumber(name): > lst=[] > nx=[] > for x in (name): > lst.append(x) > for y in (lst): > #if y in str(range(10)): > if y in "1234567890": > nx.append(y) > if y in " -()": > nx.append(y) > if y in "abc": > nx.append("2") > if y in "def": > nx.append("3") > if y in "ghi": > nx.append("4") > if y in "jkl": > nx.append("5") > if y in "mno": > nx.append("6") > if y in "pqrs": > nx.append("7") > if y in "tuv": > nx.append("8") > if y in "wxyz": > nx.append("9") > number="".join(str(e) for e in nx) > return (number) >a="1-800-getcharter" >print (nametonumber(a))#1800 438 2427 837 >a="1-800-leo laporte" >print (nametonumber(a)) >a="1 800 callaprogrammer" >print (nametonumber(a)) From denismfmcmahon at gmail.com Wed Oct 22 18:43:14 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Wed, 22 Oct 2014 22:43:14 +0000 (UTC) Subject: I am out of trial and error again Lists References: Message-ID: On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: > def nametonumber(name): > lst=[""] > for x,y in enumerate (name): > lst=lst.append(y) > print (lst) > return (lst) > a=["1-800-getcharter"] > print (nametonumber(a))#18004382427837 > > > The syntax for when to use a () and when to use [] still throws me a > curve. > > For now, I am trying to end up with a list that has each character in > "a" as a single item. > > I get: > None None First of all, an empty list is created with: emptylist = [] whereas x = [""] creates a list containing one element, that element being an empty string. Not the same thing! Did you try stepping through your code line by line in the interpreter to see what happened at each step? note that append is a method of a list object, it has no return value, the original list is modified in place. >>> l = ["a","b","c"] # declare a list >>> l.append( "d" ) # use the append method >>> l # show the list ['a', 'b', 'c', 'd'] So your line: lst = lst.append(y) should be: lst.append(y) Finally, did you really intend to pass a single element list into the function, or did you intend to pass a string into the function? There is a difference between: a=["1-800-getcharter"] which creates a single element list, the one element is the string "1-800- getcharter", and: a="1-800-getcharter" which creates a string variable with the value "1-800-getcharter" when you pass a list containing a string to your function, enumerate will look at each list element, so if your list contains one string, enumerate will return the pair 0, the_string, so the string gets appended to your empty list as a single item. The code I think you wanted to write is as follows: def nametonumber(name): lst=[] for x,y in enumerate(name): lst.append(y) return lst a="1-800-getcharter" print ( nametonumber(a) ) I suggests that you study very carefully the differences between this and your original code until you understand the reason and effect of every difference, as only by doing so will you discover the misconceptions which you seem to be operating under, and until you can get some of those straightened out, you're not going to make a lot of progress. Try running the original code and my suggested alternative line by line in the interpreter, and examining the state of relevant variables after each line of execution. Here's a code file with both your original code and my modified code with comprehensive print statements inserted for debugging. By referencing the debugging statements back to the code, you should be able to determine exactly where in your original code the value of "none" comes from. ### code starts print ( "original code" ) def nametonumber(name): print ("a) name =", name) lst=[""] print ( "b) lst = ", lst ) for x,y in enumerate (name): print ( "c) x = ", x, "; y = ", y, "; lst = ", lst ) lst=lst.append(y) print ( "d) lst = ", lst ) print (lst) return (lst) a=["1-800-getcharter"] print ( "e) a = ", a ) print (nametonumber(a)) print ( "modified code" ) def nametonumber2(name): print ("f) name =", name) lst=[] print ( "g) lst = ", lst ) for x,y in enumerate(name): print ( "h) x = ", x, "; y = ", y, "; lst = ", lst ) lst.append(y) print ( "i) lst = ", lst ) return lst a="1-800-getcharter" print ( "j) a = ", a ) print ( nametonumber2(a) ) ### code ends If you run the above code exactly as it is, you should see in the output how the enumeration reacts according to the different data it is given to enumerate, and also where lst is assigned the value none. As I said above, getting your head round why this is happening is essential, and I really do suggest that you slow down and try and understand these basic concepts, because at the moment it seems you are striving to attempt more and more complicated things without understanding the basics upon which they are constructed, and like many other similar newsgroups, it's been my experience in the past that there is limited tolerance here for people who repeatedly make the same basic errors without learning from them. -- Denis McMahon, denismfmcmahon at gmail.com From breamoreboy at yahoo.co.uk Wed Oct 22 18:55:57 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 22 Oct 2014 23:55:57 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 22/10/2014 23:30, Seymore4Head wrote: > On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head > wrote: > > One more question. > if y in str(range(10) > Why doesn't that work. Invalid syntax, it should obviously be:- if y in str(range(10)): OTOH if you've simply mistyped above what did you expect to happen and what actually happened? Give us the actual code that you ran and the full traceback. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From python at mrabarnett.plus.com Wed Oct 22 19:09:54 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 23 Oct 2014 00:09:54 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: <54483942.2090602@mrabarnett.plus.com> On 2014-10-22 23:30, Seymore4Head wrote: > On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head > wrote: > > One more question. > if y in str(range(10) > Why doesn't that work. In what way doesn't it work? If you want to know what it returns, print it out. > I commented it out and just did it "long hand" > > def nametonumber(name): > lst=[] > nx=[] > for x in (name): You don't need to put the parens around name... > lst.append(x) > for y in (lst): ...or around lst. You're iterating over a string, putting its characters into a list, and then iterating over that list. You're doing more work than you need to! > #if y in str(range(10)): > if y in "1234567890": > nx.append(y) > if y in " -()": > nx.append(y) > if y in "abc": > nx.append("2") > if y in "def": > nx.append("3") > if y in "ghi": > nx.append("4") > if y in "jkl": > nx.append("5") > if y in "mno": > nx.append("6") > if y in "pqrs": > nx.append("7") > if y in "tuv": > nx.append("8") > if y in "wxyz": > nx.append("9") > number="".join(str(e) for e in nx) The list nx already contains strings, so you don't need str here. > return (number) You don't need the parens here either. > a="1-800-getcharter" > print (nametonumber(a))#1800 438 2427 837 > a="1-800-leo laporte" > print (nametonumber(a)) > a="1 800 callaprogrammer" > print (nametonumber(a)) > From chaselton at gmail.com Wed Oct 22 19:02:20 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Wed, 22 Oct 2014 18:02:20 -0500 Subject: Problem with Android Build [SOLVED] Message-ID: On Tue, Oct 21, 2014 at 1:57 PM, Chris Angelico wrote: > On Wed, Oct 22, 2014 at 5:53 AM, Cyd Haselton wrote: > > I forgot to add...I also removed and/or commented out lines referencing > > Modules/pwdmodule.o. > > Sounds like the normal sort of work involved in porting to a new > platform. I've done a few of those kinds of jobs - ported Pike to > OS/2, and to MinGW (there is an official Pike for Windows, but I > wanted to use MinGW rather than MSVC), and there's a lot of fiddling > around to be done! > > ChrisA > This problem is fixed. I'd previously removed Makefile commands to build posixmodule.o because of an undeclared reference to I_PUSH. After picking through the source and history, I added them back in and instead added an #ifndef __ANDROID__ around the function that used I_PUSH. Ran a make clean...then make, and the newly built python was able to find sysconfig and build pybuilddir.txt Running into a different error, which I will post separate from this one. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Seymore4Head at Hotmail.invalid Wed Oct 22 19:11:51 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 19:11:51 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Wed, 22 Oct 2014 22:43:14 +0000 (UTC), Denis McMahon wrote: >On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: > >> def nametonumber(name): >> lst=[""] >> for x,y in enumerate (name): >> lst=lst.append(y) >> print (lst) >> return (lst) >> a=["1-800-getcharter"] >> print (nametonumber(a))#18004382427837 >> >> >> The syntax for when to use a () and when to use [] still throws me a >> curve. >> >> For now, I am trying to end up with a list that has each character in >> "a" as a single item. >> >> I get: >> None None > >First of all, an empty list is created with: > >emptylist = [] > >whereas > >x = [""] > >creates a list containing one element, that element being an empty >string. Not the same thing! > >Did you try stepping through your code line by line in the interpreter to >see what happened at each step? > >note that append is a method of a list object, it has no return value, >the original list is modified in place. > >>>> l = ["a","b","c"] # declare a list >>>> l.append( "d" ) # use the append method >>>> l # show the list >['a', 'b', 'c', 'd'] > >So your line: > >lst = lst.append(y) > >should be: > >lst.append(y) > >Finally, did you really intend to pass a single element list into the >function, or did you intend to pass a string into the function? > Those string errors were desperate attempts to fix the "append" error I didn't understand. >There is a difference between: > >a=["1-800-getcharter"] > >which creates a single element list, the one element is the string "1-800- >getcharter", and: > >a="1-800-getcharter" > >which creates a string variable with the value "1-800-getcharter" > >when you pass a list containing a string to your function, enumerate will >look at each list element, so if your list contains one string, enumerate >will return the pair 0, the_string, so the string gets appended to your >empty list as a single item. > >The code I think you wanted to write is as follows: > >def nametonumber(name): > lst=[] > for x,y in enumerate(name): > lst.append(y) > return lst > >a="1-800-getcharter" >print ( nametonumber(a) ) > >I suggests that you study very carefully the differences between this and >your original code until you understand the reason and effect of every >difference, as only by doing so will you discover the misconceptions >which you seem to be operating under, and until you can get some of those >straightened out, you're not going to make a lot of progress. > >Try running the original code and my suggested alternative line by line >in the interpreter, and examining the state of relevant variables after >each line of execution. > >Here's a code file with both your original code and my modified code with >comprehensive print statements inserted for debugging. By referencing the >debugging statements back to the code, you should be able to determine >exactly where in your original code the value of "none" comes from. > >### code starts > >print ( "original code" ) > >def nametonumber(name): > print ("a) name =", name) > lst=[""] > print ( "b) lst = ", lst ) > for x,y in enumerate (name): > print ( "c) x = ", x, "; y = ", y, "; lst = ", lst ) > lst=lst.append(y) > print ( "d) lst = ", lst ) > print (lst) > return (lst) > >a=["1-800-getcharter"] >print ( "e) a = ", a ) >print (nametonumber(a)) > >print ( "modified code" ) > >def nametonumber2(name): > print ("f) name =", name) > lst=[] > print ( "g) lst = ", lst ) > for x,y in enumerate(name): > print ( "h) x = ", x, "; y = ", y, "; lst = ", lst ) > lst.append(y) > print ( "i) lst = ", lst ) > return lst > >a="1-800-getcharter" >print ( "j) a = ", a ) >print ( nametonumber2(a) ) > >### code ends > >If you run the above code exactly as it is, you should see in the output >how the enumeration reacts according to the different data it is given to >enumerate, and also where lst is assigned the value none. > >As I said above, getting your head round why this is happening is >essential, and I really do suggest that you slow down and try and >understand these basic concepts, because at the moment it seems you are >striving to attempt more and more complicated things without >understanding the basics upon which they are constructed, and like many >other similar newsgroups, it's been my experience in the past that there >is limited tolerance here for people who repeatedly make the same basic >errors without learning from them. Thanks a lot for all your suggestions. I haven't learned to use the interpreter yet. I do plan on learning to use it. The problem with that at the moment is that I have enrolled in an online computer class. They use Codeskulptor. Codeskulptor code is not compatible to standard Python. When I finish the class I do plan on using Python 3 and will learn the Python 3 stuff. Codeskulptor has a Viz mode. I have tried using it, but so far it is still pretty confusing. I will try to use it more. I have saved your message and will crack the interpreter on it soon. My trouble is trying to search for practice problems that are not too hard yet. Thanks again From Seymore4Head at Hotmail.invalid Wed Oct 22 19:26:12 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 19:26:12 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Wed, 22 Oct 2014 23:55:57 +0100, Mark Lawrence wrote: >On 22/10/2014 23:30, Seymore4Head wrote: >> On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head >> wrote: >> >> One more question. >> if y in str(range(10) >> Why doesn't that work. > >Invalid syntax, it should obviously be:- > >if y in str(range(10)): > >OTOH if you've simply mistyped above what did you expect to happen and >what actually happened? Give us the actual code that you ran and the >full traceback. I don't get an error. It just doesn't print the numbers correctly. http://imgur.com/a/2loQV You can click on the images and make them larger. Thanks From breamoreboy at yahoo.co.uk Wed Oct 22 19:44:01 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 23 Oct 2014 00:44:01 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 23/10/2014 00:26, Seymore4Head wrote: > On Wed, 22 Oct 2014 23:55:57 +0100, Mark Lawrence > wrote: > >> On 22/10/2014 23:30, Seymore4Head wrote: >>> On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head >>> wrote: >>> >>> One more question. >>> if y in str(range(10) >>> Why doesn't that work. >> >> Invalid syntax, it should obviously be:- >> >> if y in str(range(10)): >> >> OTOH if you've simply mistyped above what did you expect to happen and >> what actually happened? Give us the actual code that you ran and the >> full traceback. > > I don't get an error. It just doesn't print the numbers correctly. > http://imgur.com/a/2loQV > You can click on the images and make them larger. > Thanks > I suggest you try str(range(10)) from the interactive prompt and see exactly what you get, as it's nothing like what you expect :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ben+python at benfinney.id.au Wed Oct 22 19:59:39 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 23 Oct 2014 10:59:39 +1100 Subject: The =?utf-8?B?4oCcdHJpYWxz4oCd?= in =?utf-8?Q?=E2=80=9Ctrial?= and =?utf-8?Q?error=E2=80=9D?= should be as simple as possible (was: I am out of trial and error again Lists) References: Message-ID: <85k33r4pw4.fsf_-_@benfinney.id.au> Seymore4Head writes: > Those string errors were desperate attempts to fix the "append" error > I didn't understand. It's normal when learning to get one's code into a mess. But, when trying to trouble-shoot, please adopt the habit of *simplifying* the examples, to better understand them. At the least, when presenting code here for asking questions, ensure you've make a simple-as-possible example showing the problem. In other words: rip out any complicated parts to see if they're relevant; if the same problem happens, that part wasn't relevant to the example, and you should omit it when presenting it here. You'll find that this will get you more sensible answers, As a bonus, it will often lead to you understanding the problem enough to solve it! -- \ ?At my lemonade stand I used to give the first glass away free | `\ and charge five dollars for the second glass. The refill | _o__) contained the antidote.? ?Emo Philips | Ben Finney From Seymore4Head at Hotmail.invalid Wed Oct 22 20:02:35 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 20:02:35 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Thu, 23 Oct 2014 00:44:01 +0100, Mark Lawrence wrote: >On 23/10/2014 00:26, Seymore4Head wrote: >> On Wed, 22 Oct 2014 23:55:57 +0100, Mark Lawrence >> wrote: >> >>> On 22/10/2014 23:30, Seymore4Head wrote: >>>> On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head >>>> wrote: >>>> >>>> One more question. >>>> if y in str(range(10) >>>> Why doesn't that work. >>> >>> Invalid syntax, it should obviously be:- >>> >>> if y in str(range(10)): >>> >>> OTOH if you've simply mistyped above what did you expect to happen and >>> what actually happened? Give us the actual code that you ran and the >>> full traceback. >> >> I don't get an error. It just doesn't print the numbers correctly. >> http://imgur.com/a/2loQV >> You can click on the images and make them larger. >> Thanks >> > >I suggest you try str(range(10)) from the interactive prompt and see >exactly what you get, as it's nothing like what you expect :) I see that now. So there may not be a short hand solution. Thanks From steve+comp.lang.python at pearwood.info Wed Oct 22 20:05:08 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 23 Oct 2014 11:05:08 +1100 Subject: I am out of trial and error again Lists References: Message-ID: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> Seymore4Head wrote: > Those string errors were desperate attempts to fix the "append" error > I didn't understand. Ah, the good ol' "make random changes to the code until the error goes away" technique. You know that it never works, right? Start by *reading the error message*, assuming you're getting an error message. I'm the first person to admit that Python's error messages are not always as clear as they should be, especially syntax errors, but still there is a lot of information that can be gleamed from most error messages. Take this attempt to use append: py> mylist.append(23) Traceback (most recent call last): File "", line 1, in NameError: name 'mylist' is not defined That tells me that I have forgotten to define a variable mylist. So I fix that: py> mylist = 23 py> mylist.append(23) Traceback (most recent call last): File "", line 1, in AttributeError: 'int' object has no attribute 'append' That tells me that I can't append to a int. After googling for "Python append" I learn that I can append to a list, so I try again: py> mylist = [] py> mylist.append(23) py> print(mylist) [23] Success! If you are familiar with other programming languages, it might help to think of append() as being like a procedure in Pascal, for example. You call append() with an argument, but don't expect a return result. Technically, *all* functions and methods in Python return something, even if just the special value None, which can lead to "Gotchas!" like this one: py> mylist = mylist.append(42) # Don't do this! py> print(mylist) # I expect [23, 42] but get None instead. None Oops. One of the small annoyances of Python is that there is no way to tell ahead of time, except by reading the documentation, whether something is a proper function that returns a useful value, or a procedure-like function that returns None. That's just something you have to learn. The interactive interpreter is your friend. Learn to experiment at the interactive interpreter -- you do know how to do that, don't you? If not, ask. At the interactive interpreter, if a function or method returns a value, it will be printed, *except for None*. So a function that doesn't print anything might be procedure-like, and one which does print something might not be: py> mylist = [1, 5, 2, 6, 4, 3] py> sorted(mylist) # proper function returns a value [1, 2, 3, 4, 5, 6] py> mylist.sort() # procedure-like function returns None py> print(mylist) # and modifies the list in place [1, 2, 3, 4, 5, 6] -- Steven From Seymore4Head at Hotmail.invalid Wed Oct 22 20:10:16 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 20:10:16 -0400 Subject: I am out of trial and error again Lists References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Thu, 23 Oct 2014 11:05:08 +1100, Steven D'Aprano wrote: >Seymore4Head wrote: > >> Those string errors were desperate attempts to fix the "append" error >> I didn't understand. > >Ah, the good ol' "make random changes to the code until the error goes away" >technique. You know that it never works, right? > >Start by *reading the error message*, assuming you're getting an error >message. I'm the first person to admit that Python's error messages are not >always as clear as they should be, especially syntax errors, but still >there is a lot of information that can be gleamed from most error messages. >Take this attempt to use append: > >py> mylist.append(23) >Traceback (most recent call last): > File "", line 1, in >NameError: name 'mylist' is not defined > >That tells me that I have forgotten to define a variable mylist. So I fix >that: > >py> mylist = 23 >py> mylist.append(23) >Traceback (most recent call last): > File "", line 1, in >AttributeError: 'int' object has no attribute 'append' > > >That tells me that I can't append to a int. After googling for "Python >append" I learn that I can append to a list, so I try again: > >py> mylist = [] >py> mylist.append(23) >py> print(mylist) >[23] > > >Success! > >If you are familiar with other programming languages, it might help to think >of append() as being like a procedure in Pascal, for example. You call >append() with an argument, but don't expect a return result. > >Technically, *all* functions and methods in Python return something, even if >just the special value None, which can lead to "Gotchas!" like this one: > >py> mylist = mylist.append(42) # Don't do this! >py> print(mylist) # I expect [23, 42] but get None instead. >None > >Oops. One of the small annoyances of Python is that there is no way to tell >ahead of time, except by reading the documentation, whether something is a >proper function that returns a useful value, or a procedure-like function >that returns None. That's just something you have to learn. > >The interactive interpreter is your friend. Learn to experiment at the >interactive interpreter -- you do know how to do that, don't you? If not, >ask. At the interactive interpreter, if a function or method returns a >value, it will be printed, *except for None*. So a function that doesn't >print anything might be procedure-like, and one which does print something >might not be: > >py> mylist = [1, 5, 2, 6, 4, 3] >py> sorted(mylist) # proper function returns a value >[1, 2, 3, 4, 5, 6] >py> mylist.sort() # procedure-like function returns None >py> print(mylist) # and modifies the list in place >[1, 2, 3, 4, 5, 6] I am going to get around to learning the interpreter soon. Thanks From visphatesjava at gmail.com Wed Oct 22 20:33:02 2014 From: visphatesjava at gmail.com (johannes falcone) Date: Wed, 22 Oct 2014 17:33:02 -0700 (PDT) Subject: the ressurection of ZOPE for web domination? bluebream and caveman the answer? Message-ID: <6627577b-5f4f-4f20-88b0-a41f63c12ebc@googlegroups.com> i loved the rant about how zope would have all these features, and then some other python framework would come on with like 1 and act like its the bomb, and zope was like we been doing that and more for X years those who dont study zope are doomed to repeat it!!! is zope scoffing at drupal? botle? pyramid ? From steve+comp.lang.python at pearwood.info Wed Oct 22 20:44:20 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 23 Oct 2014 11:44:20 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <544775ca$0$2146$426a74cc@news.free.fr> Message-ID: <54484f66$0$13011$c3e8da3$5496439d@news.astraweb.com> Michael Torrie wrote: > On 10/22/2014 05:45 AM, Mark Lawrence wrote: >>>> without not: >>>> j = [j+1, 3][j>=10] >>>> with not: >>>> j = [3, j+1][not (j>=10)] >>>> >>> >>> Oh it's a trick ! >>> thx >> >> IMHO it's just dreadful. Why people insist on messing around like this >> I really don't know, it just drives me nuts. > > This actually was the standard idiom used by many python programs before > Python 2.5. But I agree. Don't do this anymore! Python has a ternary > if expression. Also the ternary if expression does, I believe > short-circuit logic, so the non-chosen path is not calculated. This > hack does not. Could lead to interesting bugs depending on your > assumptions. Working code doesn't suddenly become non-working code just because Python adds a second way to do something. The standard idiom (value_if_false, value_if_true)[condition] worked from (at least) Python 1.5 to Python 2.4, and it continues to work today. There's nothing wrong with it: it does what it does, nothing more, nothing less, and the only hashish part of this is that bools *are* ints, with True == 1 and False == 0. That was heavily debated back in 2.3 or thereabouts when bools were first introduced, and the decision made then wasn't reverted in Python 3, so you can take it as By Design and not a fluke of history. I think it is fair to say that Guido likes it that bools are ints. The older idiom isn't *exactly* the same as the ternary if operator, since that short-circuits, but for many purposes short-circuiting is not important or needed. If you don't need short-circuiting, or you dislike the order of `value_if_true if condition else value_if_false`, or you need to support Python 2.4 or older, or *simply because you like it*, there is nothing wrong with using the older `sequence[flag]` idiom. (It amuses me that not that many years ago the general attitude here was that ternary if was an abomination that no right-thinking person should ever use because the order of terms isn't identical to C, and now the attitude seems to be that anyone *not* using ternary if is a heretic who deserves to be set on fire :-) -- Steven From python at mrabarnett.plus.com Wed Oct 22 21:29:43 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 23 Oct 2014 02:29:43 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: <54485A07.2080606@mrabarnett.plus.com> On 2014-10-23 01:02, Seymore4Head wrote: > On Thu, 23 Oct 2014 00:44:01 +0100, Mark Lawrence > wrote: > >>On 23/10/2014 00:26, Seymore4Head wrote: >>> On Wed, 22 Oct 2014 23:55:57 +0100, Mark Lawrence >>> wrote: >>> >>>> On 22/10/2014 23:30, Seymore4Head wrote: >>>>> On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head >>>>> wrote: >>>>> >>>>> One more question. >>>>> if y in str(range(10) >>>>> Why doesn't that work. >>>> >>>> Invalid syntax, it should obviously be:- >>>> >>>> if y in str(range(10)): >>>> >>>> OTOH if you've simply mistyped above what did you expect to happen and >>>> what actually happened? Give us the actual code that you ran and the >>>> full traceback. >>> >>> I don't get an error. It just doesn't print the numbers correctly. >>> http://imgur.com/a/2loQV >>> You can click on the images and make them larger. >>> Thanks >>> >> >>I suggest you try str(range(10)) from the interactive prompt and see >>exactly what you get, as it's nothing like what you expect :) > > I see that now. So there may not be a short hand solution. > range(10) will yield the integers 0-9. You can iterate over them, turning each into a string, and then join them together: ''.join(str(n) for n in range(10)) From python at mrabarnett.plus.com Wed Oct 22 21:31:57 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 23 Oct 2014 02:31:57 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <54485A8D.9020308@mrabarnett.plus.com> On 2014-10-23 01:10, Seymore4Head wrote: > On Thu, 23 Oct 2014 11:05:08 +1100, Steven D'Aprano > wrote: > >>Seymore4Head wrote: >> >>> Those string errors were desperate attempts to fix the "append" error >>> I didn't understand. >> >>Ah, the good ol' "make random changes to the code until the error goes away" >>technique. You know that it never works, right? >> >>Start by *reading the error message*, assuming you're getting an error >>message. I'm the first person to admit that Python's error messages are not >>always as clear as they should be, especially syntax errors, but still >>there is a lot of information that can be gleamed from most error messages. >>Take this attempt to use append: >> >>py> mylist.append(23) >>Traceback (most recent call last): >> File "", line 1, in >>NameError: name 'mylist' is not defined >> >>That tells me that I have forgotten to define a variable mylist. So I fix >>that: >> >>py> mylist = 23 >>py> mylist.append(23) >>Traceback (most recent call last): >> File "", line 1, in >>AttributeError: 'int' object has no attribute 'append' >> >> >>That tells me that I can't append to a int. After googling for "Python >>append" I learn that I can append to a list, so I try again: >> >>py> mylist = [] >>py> mylist.append(23) >>py> print(mylist) >>[23] >> >> >>Success! >> >>If you are familiar with other programming languages, it might help to think >>of append() as being like a procedure in Pascal, for example. You call >>append() with an argument, but don't expect a return result. >> >>Technically, *all* functions and methods in Python return something, even if >>just the special value None, which can lead to "Gotchas!" like this one: >> >>py> mylist = mylist.append(42) # Don't do this! >>py> print(mylist) # I expect [23, 42] but get None instead. >>None >> >>Oops. One of the small annoyances of Python is that there is no way to tell >>ahead of time, except by reading the documentation, whether something is a >>proper function that returns a useful value, or a procedure-like function >>that returns None. That's just something you have to learn. >> >>The interactive interpreter is your friend. Learn to experiment at the >>interactive interpreter -- you do know how to do that, don't you? If not, >>ask. At the interactive interpreter, if a function or method returns a >>value, it will be printed, *except for None*. So a function that doesn't >>print anything might be procedure-like, and one which does print something >>might not be: >> >>py> mylist = [1, 5, 2, 6, 4, 3] >>py> sorted(mylist) # proper function returns a value >>[1, 2, 3, 4, 5, 6] >>py> mylist.sort() # procedure-like function returns None >>py> print(mylist) # and modifies the list in place >>[1, 2, 3, 4, 5, 6] > > I am going to get around to learning the interpreter soon. > Why wait? You're trying to learn the language _now_, and checking things interactively will help you. From wuwei23 at gmail.com Wed Oct 22 21:37:27 2014 From: wuwei23 at gmail.com (alex23) Date: Thu, 23 Oct 2014 11:37:27 +1000 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 23/10/2014 10:02 AM, Seymore4Head wrote: > On Thu, 23 Oct 2014 00:44:01 +0100, Mark Lawrence > wrote: >>>>> One more question. >>>>> if y in str(range(10) >>>>> Why doesn't that work. >> I suggest you try str(range(10)) from the interactive prompt and see >> exactly what you get, as it's nothing like what you expect :) > > I see that now. So there may not be a short hand solution. There are two 'short hand solutions' to do what you want here: import string if y in string.digits: .... Or even simpler: if y.isdigit(): ... From Seymore4Head at Hotmail.invalid Wed Oct 22 21:35:19 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 21:35:19 -0400 Subject: I am out of trial and error again Lists References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> On Thu, 23 Oct 2014 02:31:57 +0100, MRAB wrote: >On 2014-10-23 01:10, Seymore4Head wrote: >> On Thu, 23 Oct 2014 11:05:08 +1100, Steven D'Aprano >> wrote: >> >>>Seymore4Head wrote: >>> >>>> Those string errors were desperate attempts to fix the "append" error >>>> I didn't understand. >>> >>>Ah, the good ol' "make random changes to the code until the error goes away" >>>technique. You know that it never works, right? >>> >>>Start by *reading the error message*, assuming you're getting an error >>>message. I'm the first person to admit that Python's error messages are not >>>always as clear as they should be, especially syntax errors, but still >>>there is a lot of information that can be gleamed from most error messages. >>>Take this attempt to use append: >>> >>>py> mylist.append(23) >>>Traceback (most recent call last): >>> File "", line 1, in >>>NameError: name 'mylist' is not defined >>> >>>That tells me that I have forgotten to define a variable mylist. So I fix >>>that: >>> >>>py> mylist = 23 >>>py> mylist.append(23) >>>Traceback (most recent call last): >>> File "", line 1, in >>>AttributeError: 'int' object has no attribute 'append' >>> >>> >>>That tells me that I can't append to a int. After googling for "Python >>>append" I learn that I can append to a list, so I try again: >>> >>>py> mylist = [] >>>py> mylist.append(23) >>>py> print(mylist) >>>[23] >>> >>> >>>Success! >>> >>>If you are familiar with other programming languages, it might help to think >>>of append() as being like a procedure in Pascal, for example. You call >>>append() with an argument, but don't expect a return result. >>> >>>Technically, *all* functions and methods in Python return something, even if >>>just the special value None, which can lead to "Gotchas!" like this one: >>> >>>py> mylist = mylist.append(42) # Don't do this! >>>py> print(mylist) # I expect [23, 42] but get None instead. >>>None >>> >>>Oops. One of the small annoyances of Python is that there is no way to tell >>>ahead of time, except by reading the documentation, whether something is a >>>proper function that returns a useful value, or a procedure-like function >>>that returns None. That's just something you have to learn. >>> >>>The interactive interpreter is your friend. Learn to experiment at the >>>interactive interpreter -- you do know how to do that, don't you? If not, >>>ask. At the interactive interpreter, if a function or method returns a >>>value, it will be printed, *except for None*. So a function that doesn't >>>print anything might be procedure-like, and one which does print something >>>might not be: >>> >>>py> mylist = [1, 5, 2, 6, 4, 3] >>>py> sorted(mylist) # proper function returns a value >>>[1, 2, 3, 4, 5, 6] >>>py> mylist.sort() # procedure-like function returns None >>>py> print(mylist) # and modifies the list in place >>>[1, 2, 3, 4, 5, 6] >> >> I am going to get around to learning the interpreter soon. >> >Why wait? > >You're trying to learn the language _now_, and checking things >interactively will help you. Because most of the practice I am getting is not using Python. I use Codeskulptor. OK.........Now is as good a time as ever. Thanks From Seymore4Head at Hotmail.invalid Wed Oct 22 21:52:46 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 21:52:46 -0400 Subject: I am out of trial and error again Lists References: Message-ID: <7rng4a9pcq6u9oke37gsi0lvsttbtd0mkc@4ax.com> On Thu, 23 Oct 2014 11:37:27 +1000, alex23 wrote: >On 23/10/2014 10:02 AM, Seymore4Head wrote: >> On Thu, 23 Oct 2014 00:44:01 +0100, Mark Lawrence >> wrote: >>>>>> One more question. >>>>>> if y in str(range(10) >>>>>> Why doesn't that work. >>> I suggest you try str(range(10)) from the interactive prompt and see >>> exactly what you get, as it's nothing like what you expect :) >> >> I see that now. So there may not be a short hand solution. > >There are two 'short hand solutions' to do what you want here: > > import string > > if y in string.digits: > .... > >Or even simpler: > > if y.isdigit(): > ... Thanks From Seymore4Head at Hotmail.invalid Wed Oct 22 21:57:57 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 21:57:57 -0400 Subject: I am out of trial and error again Lists References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> Message-ID: On Wed, 22 Oct 2014 21:35:19 -0400, Seymore4Head wrote: >On Thu, 23 Oct 2014 02:31:57 +0100, MRAB >wrote: > >>On 2014-10-23 01:10, Seymore4Head wrote: >>> On Thu, 23 Oct 2014 11:05:08 +1100, Steven D'Aprano >>> wrote: >>> >>>>Seymore4Head wrote: >>>> >>>>> Those string errors were desperate attempts to fix the "append" error >>>>> I didn't understand. >>>> >>>>Ah, the good ol' "make random changes to the code until the error goes away" >>>>technique. You know that it never works, right? >>>> >>>>Start by *reading the error message*, assuming you're getting an error >>>>message. I'm the first person to admit that Python's error messages are not >>>>always as clear as they should be, especially syntax errors, but still >>>>there is a lot of information that can be gleamed from most error messages. >>>>Take this attempt to use append: >>>> >>>>py> mylist.append(23) >>>>Traceback (most recent call last): >>>> File "", line 1, in >>>>NameError: name 'mylist' is not defined >>>> >>>>That tells me that I have forgotten to define a variable mylist. So I fix >>>>that: >>>> >>>>py> mylist = 23 >>>>py> mylist.append(23) >>>>Traceback (most recent call last): >>>> File "", line 1, in >>>>AttributeError: 'int' object has no attribute 'append' >>>> >>>> >>>>That tells me that I can't append to a int. After googling for "Python >>>>append" I learn that I can append to a list, so I try again: >>>> >>>>py> mylist = [] >>>>py> mylist.append(23) >>>>py> print(mylist) >>>>[23] >>>> >>>> >>>>Success! >>>> >>>>If you are familiar with other programming languages, it might help to think >>>>of append() as being like a procedure in Pascal, for example. You call >>>>append() with an argument, but don't expect a return result. >>>> >>>>Technically, *all* functions and methods in Python return something, even if >>>>just the special value None, which can lead to "Gotchas!" like this one: >>>> >>>>py> mylist = mylist.append(42) # Don't do this! >>>>py> print(mylist) # I expect [23, 42] but get None instead. >>>>None >>>> >>>>Oops. One of the small annoyances of Python is that there is no way to tell >>>>ahead of time, except by reading the documentation, whether something is a >>>>proper function that returns a useful value, or a procedure-like function >>>>that returns None. That's just something you have to learn. >>>> >>>>The interactive interpreter is your friend. Learn to experiment at the >>>>interactive interpreter -- you do know how to do that, don't you? If not, >>>>ask. At the interactive interpreter, if a function or method returns a >>>>value, it will be printed, *except for None*. So a function that doesn't >>>>print anything might be procedure-like, and one which does print something >>>>might not be: >>>> >>>>py> mylist = [1, 5, 2, 6, 4, 3] >>>>py> sorted(mylist) # proper function returns a value >>>>[1, 2, 3, 4, 5, 6] >>>>py> mylist.sort() # procedure-like function returns None >>>>py> print(mylist) # and modifies the list in place >>>>[1, 2, 3, 4, 5, 6] >>> >>> I am going to get around to learning the interpreter soon. >>> >>Why wait? >> >>You're trying to learn the language _now_, and checking things >>interactively will help you. > >Because most of the practice I am getting is not using Python. I use >Codeskulptor. > >OK.........Now is as good a time as ever. > >Thanks Now I remember why...........nothing happens http://i.imgur.com/MIRpqzY.jpg If I click on the shell window, I can get the grayed options to show up for one turn. I hit step and everything goes gray again. http://i.imgur.com/NtMdmU1.jpg Not a very fruitful exercise. :( From orgnut at yahoo.com Wed Oct 22 22:58:24 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Wed, 22 Oct 2014 19:58:24 -0700 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 10/22/2014 05:02 PM, Seymore4Head wrote: > On Thu, 23 Oct 2014 00:44:01 +0100, Mark Lawrence > wrote: (This is in reference to the line: if y in str(range(10)):) >> I suggest you try str(range(10)) from the interactive prompt and see >> exactly what you get, as it's nothing like what you expect :) > > I see that now. So there may not be a short hand solution. > Yes there is. That statement would work in Py2 as-is, but in Py3 it needs to be changed to: if y in list(range(10)): This give you a list not a string, but that's actually what you want here. If you _really_ want a string, use join(): "".join(list(range(10))) ------ Also, from another post: ------- > Thanks a lot for all your suggestions. I haven't learned to use the > interpreter yet. I do plan on learning to use it. You are making yourself work several hundred times harder if you don't learn to use the interactive mode! > The problem with that at the moment is that I have enrolled in an > online computer class. They use Codeskulptor. > Codeskulptor code is not compatible to standard Python. I would be GREATLY bothered by the fact that it is not standard Python -- it sounds like a poor course. You also seems to imply that you are only using those on-line tools and don't have a real Python installed on your own system. If so, that is an extremely bad choice. And if so, stop everything until you do install it NOW (definitely Python 3). Then you can play with things on your own system IN THE INTERACTIVE MODE!!! That's when you will start actually learning. -=- Larry -=- From Seymore4Head at Hotmail.invalid Wed Oct 22 23:05:32 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Wed, 22 Oct 2014 23:05:32 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Wed, 22 Oct 2014 19:58:24 -0700, Larry Hudson wrote: >On 10/22/2014 05:02 PM, Seymore4Head wrote: >> On Thu, 23 Oct 2014 00:44:01 +0100, Mark Lawrence >> wrote: > > (This is in reference to the line: if y in str(range(10)):) > >>> I suggest you try str(range(10)) from the interactive prompt and see >>> exactly what you get, as it's nothing like what you expect :) >> >> I see that now. So there may not be a short hand solution. >> > >Yes there is. > >That statement would work in Py2 as-is, but in Py3 it needs to be changed to: > >if y in list(range(10)): > >This give you a list not a string, but that's actually what you want here. If you _really_ want >a string, use join(): "".join(list(range(10))) > >------ Also, from another post: ------- > > > Thanks a lot for all your suggestions. I haven't learned to use the > > interpreter yet. I do plan on learning to use it. > >You are making yourself work several hundred times harder if you don't learn to use the >interactive mode! > > > The problem with that at the moment is that I have enrolled in an > > online computer class. They use Codeskulptor. > > Codeskulptor code is not compatible to standard Python. > >I would be GREATLY bothered by the fact that it is not standard Python -- it sounds like a poor >course. You also seems to imply that you are only using those on-line tools and don't have a >real Python installed on your own system. If so, that is an extremely bad choice. And if so, >stop everything until you do install it NOW (definitely Python 3). Then you can play with >things on your own system IN THE INTERACTIVE MODE!!! That's when you will start actually learning. > > -=- Larry -=- OK Good advice. I already have Py3 installed. Interactive mode is the next item on my do list. Thanks From rustompmody at gmail.com Wed Oct 22 23:16:16 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 22 Oct 2014 20:16:16 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On Thursday, October 23, 2014 8:28:39 AM UTC+5:30, Larry Hudson wrote: > ------ Also, from another post: ------- > > Thanks a lot for all your suggestions. I haven't learned to use the > > interpreter yet. I do plan on learning to use it. > You are making yourself work several hundred times harder if you don't learn to use the > interactive mode! +100 That a noob takes the longest path out of noob-land --- well thats the fun of life! That experienced people are not peremptory enough -- yeah "My way or Highway" is rude but necessary at times -- is unfortunate. From greg.ewing at canterbury.ac.nz Wed Oct 22 23:46:06 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Thu, 23 Oct 2014 16:46:06 +1300 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: Chris Angelico wrote: > I've seen much MUCH worse... where multiple conditional > expressions get combined arithmetically, and then the result used > somewhere... In the days of old-school BASIC it was common to exploit the fact that boolean expressions evaluated to 0 or 1 (or -1, depending on your dialect :) to achieve conditional expressions or other tricks. Probably forgiveable, given that there were no real conditional expressions, and every byte of your 48K or less of RAM was precious... -- Greg From vito.detullio at gmail.com Thu Oct 23 00:55:22 2014 From: vito.detullio at gmail.com (Vito De Tullio) Date: Thu, 23 Oct 2014 06:55:22 +0200 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <7ugg4at56dail7idpd5r3eg7hkgums6r6m@4ax.com> Message-ID: Dennis Lee Bieber wrote: >> x = [f(), g()] [cond] >> >>the latter evaluates both f() and g() instead of just one. Apart from >>being inefficient, it can have unintended side-effects. > > Ah, but what would > > x = [f, g][cond]() > > produce? headache -- By ZeD From tjreedy at udel.edu Thu Oct 23 02:31:15 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 23 Oct 2014 02:31:15 -0400 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 10/22/2014 10:58 PM, Larry Hudson wrote: > This give you a list not a string, but that's actually what you want > here. If you _really_ want a string, use join(): "".join(list(range(10))) Interactive mode makes it really easy to test before posting. >>> "".join(list(range(10))) Traceback (most recent call last): File "", line 1, in "".join(list(range(10))) TypeError: sequence item 0: expected string, int found >>> "".join(str(i) for i in range(10)) '0123456789' -- Terry Jan Reedy From orgnut at yahoo.com Thu Oct 23 03:10:28 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Thu, 23 Oct 2014 00:10:28 -0700 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 10/22/2014 03:30 PM, Seymore4Head wrote: > On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head > wrote: > > One more question. > if y in str(range(10) > Why doesn't that work. > I commented it out and just did it "long hand" > > def nametonumber(name): > lst=[] > nx=[] > for x in (name): > lst.append(x) > for y in (lst): > #if y in str(range(10)): > if y in "1234567890": > nx.append(y) > if y in " -()": > nx.append(y) > if y in "abc": > nx.append("2") > if y in "def": > nx.append("3") > if y in "ghi": > nx.append("4") > if y in "jkl": > nx.append("5") > if y in "mno": > nx.append("6") > if y in "pqrs": > nx.append("7") > if y in "tuv": > nx.append("8") > if y in "wxyz": > nx.append("9") > number="".join(str(e) for e in nx) > return (number) > a="1-800-getcharter" > print (nametonumber(a))#1800 438 2427 837 > a="1-800-leo laporte" > print (nametonumber(a)) > a="1 800 callaprogrammer" > print (nametonumber(a)) > I know you are trying to explore lists here, but I found myself somewhat intrigued with the problem itself, so I wrote a different version. This version does not use lists but only strings. I'm just presenting it as-is to let you try to follow the logic, but if you ask, I'll explain it in detail. It turns your long sequence of if's essentially into a single line -- unfortunately 's' and 'z' have to be handled as special-cases, which turns that single line into a six-line if/elif/else set. You might consider this line 'tricky', but I'll just say it's just looking at the problem from a different viewpoint. BTW, this version accepts upper-case as well as lower-case. isdigit() and isalpha() are standard string methods. #------ Code ---------- def name2number(name): nstr = '' # Phone-number string to return codes = 'abcdefghijklmnopqrtuvwxy' # Note missing s and z for ch in name: if ch in " -()": nstr += ch elif ch.isdigit(): nstr += ch elif ch.isalpha(): ch = ch.lower() # S and Z are special cases if ch == 's': nstr += '7' elif ch == 'z': nstr += '9' else: nstr += str(codes.index(ch) // 3 + 2) return nstr #------- End of Code --------- A possible variation would be to make nstr a list instead of a string, and use .append() instead of the +=, and finally return the string by using join() on the list. Also, the if and first elif in the for could be combined: if ch in " -()" or ch.isdigit(): -=- Larry -=- From breamoreboy at yahoo.co.uk Thu Oct 23 03:20:32 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 23 Oct 2014 08:20:32 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> Message-ID: On 23/10/2014 02:57, Seymore4Head wrote: > On Wed, 22 Oct 2014 21:35:19 -0400, Seymore4Head > wrote: > >> On Thu, 23 Oct 2014 02:31:57 +0100, MRAB >> wrote: >> >>> On 2014-10-23 01:10, Seymore4Head wrote: >>>> On Thu, 23 Oct 2014 11:05:08 +1100, Steven D'Aprano >>>> wrote: >>>> >>>>> Seymore4Head wrote: >>>>> >>>>>> Those string errors were desperate attempts to fix the "append" error >>>>>> I didn't understand. >>>>> >>>>> Ah, the good ol' "make random changes to the code until the error goes away" >>>>> technique. You know that it never works, right? >>>>> >>>>> Start by *reading the error message*, assuming you're getting an error >>>>> message. I'm the first person to admit that Python's error messages are not >>>>> always as clear as they should be, especially syntax errors, but still >>>>> there is a lot of information that can be gleamed from most error messages. >>>>> Take this attempt to use append: >>>>> >>>>> py> mylist.append(23) >>>>> Traceback (most recent call last): >>>>> File "", line 1, in >>>>> NameError: name 'mylist' is not defined >>>>> >>>>> That tells me that I have forgotten to define a variable mylist. So I fix >>>>> that: >>>>> >>>>> py> mylist = 23 >>>>> py> mylist.append(23) >>>>> Traceback (most recent call last): >>>>> File "", line 1, in >>>>> AttributeError: 'int' object has no attribute 'append' >>>>> >>>>> >>>>> That tells me that I can't append to a int. After googling for "Python >>>>> append" I learn that I can append to a list, so I try again: >>>>> >>>>> py> mylist = [] >>>>> py> mylist.append(23) >>>>> py> print(mylist) >>>>> [23] >>>>> >>>>> >>>>> Success! >>>>> >>>>> If you are familiar with other programming languages, it might help to think >>>>> of append() as being like a procedure in Pascal, for example. You call >>>>> append() with an argument, but don't expect a return result. >>>>> >>>>> Technically, *all* functions and methods in Python return something, even if >>>>> just the special value None, which can lead to "Gotchas!" like this one: >>>>> >>>>> py> mylist = mylist.append(42) # Don't do this! >>>>> py> print(mylist) # I expect [23, 42] but get None instead. >>>>> None >>>>> >>>>> Oops. One of the small annoyances of Python is that there is no way to tell >>>>> ahead of time, except by reading the documentation, whether something is a >>>>> proper function that returns a useful value, or a procedure-like function >>>>> that returns None. That's just something you have to learn. >>>>> >>>>> The interactive interpreter is your friend. Learn to experiment at the >>>>> interactive interpreter -- you do know how to do that, don't you? If not, >>>>> ask. At the interactive interpreter, if a function or method returns a >>>>> value, it will be printed, *except for None*. So a function that doesn't >>>>> print anything might be procedure-like, and one which does print something >>>>> might not be: >>>>> >>>>> py> mylist = [1, 5, 2, 6, 4, 3] >>>>> py> sorted(mylist) # proper function returns a value >>>>> [1, 2, 3, 4, 5, 6] >>>>> py> mylist.sort() # procedure-like function returns None >>>>> py> print(mylist) # and modifies the list in place >>>>> [1, 2, 3, 4, 5, 6] >>>> >>>> I am going to get around to learning the interpreter soon. >>>> >>> Why wait? >>> >>> You're trying to learn the language _now_, and checking things >>> interactively will help you. >> >> Because most of the practice I am getting is not using Python. I use >> Codeskulptor. >> >> OK.........Now is as good a time as ever. >> >> Thanks > > Now I remember why...........nothing happens > http://i.imgur.com/MIRpqzY.jpg > > If I click on the shell window, I can get the grayed options to show > up for one turn. > I hit step and everything goes gray again. > > http://i.imgur.com/NtMdmU1.jpg > > Not a very fruitful exercise. :( > If you were to read and digest what is written it would help. You're trying to run IDLE. We're talking the interactive interpreter. If (at least on Windows) you run a command prompt and then type python you should see something like this. Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ian.g.kelly at gmail.com Thu Oct 23 03:56:46 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 23 Oct 2014 01:56:46 -0600 Subject: I am out of trial and error again Lists In-Reply-To: References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> Message-ID: On Thu, Oct 23, 2014 at 1:20 AM, Mark Lawrence wrote: > If you were to read and digest what is written it would help. You're trying > to run IDLE. We're talking the interactive interpreter. IDLE includes the interactive interpreter. > If (at least on > Windows) you run a command prompt and then type python you should see > something like this. > > Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit > (AMD64)] on win32 > Type "help", "copyright", "credits" or "license" for more information. Same thing comes up when I start IDLE, so what's your point? From breamoreboy at yahoo.co.uk Thu Oct 23 04:09:02 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 23 Oct 2014 09:09:02 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> Message-ID: On 23/10/2014 08:56, Ian Kelly wrote: > On Thu, Oct 23, 2014 at 1:20 AM, Mark Lawrence wrote: >> If you were to read and digest what is written it would help. You're trying >> to run IDLE. We're talking the interactive interpreter. > > IDLE includes the interactive interpreter. > >> If (at least on >> Windows) you run a command prompt and then type python you should see >> something like this. >> >> Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit >> (AMD64)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. > > Same thing comes up when I start IDLE, so what's your point? > When you run the interactive interpreter thats all you get. The OP isn't the first person to try things with IDLE not realising you need to have a script loaded to do something. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From denismfmcmahon at gmail.com Thu Oct 23 05:15:16 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 23 Oct 2014 09:15:16 +0000 (UTC) Subject: I am out of trial and error again Lists References: Message-ID: On Wed, 22 Oct 2014 18:30:17 -0400, Seymore4Head wrote: > One more question. > if y in str(range(10) > Why doesn't that work. > I commented it out and just did it "long hand" In the last post I made, I suggested to you the mechanisms of using the python console and using code which prints out variables after every line. Try the following 3 commands at the console: >>> 10 >>> range(10) >>> str(range(10)) 10 is just the number 10 range(10) is a list of 10 integers in the sequence 0 to 9 str(range(10)) is? Please stop the stab in the dark trial and error coding followed by the plaintive "why doesn't it work" wailing, and put some effort into reading and understanding the manuals. If a function doesn't do what you expect with the input you think you've given it, there is invariably one of three causes: a) The input you actually gave it isn't the input you thought you gave it b) You didn't read the description of the function, and it doesn't in fact do what you thought c) Both a and b above -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Thu Oct 23 05:21:44 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 23 Oct 2014 09:21:44 +0000 (UTC) Subject: I am out of trial and error again Lists References: Message-ID: On Wed, 22 Oct 2014 19:11:51 -0400, Seymore4Head wrote: > On Wed, 22 Oct 2014 22:43:14 +0000 (UTC), Denis McMahon > wrote: > >>On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: >> >>> def nametonumber(name): >>> lst=[""] >>> for x,y in enumerate (name): >>> lst=lst.append(y) >>> print (lst) >>> return (lst) >>> a=["1-800-getcharter"] >>> print (nametonumber(a))#18004382427837 >>> >>> >>> The syntax for when to use a () and when to use [] still throws me a >>> curve. >>> >>> For now, I am trying to end up with a list that has each character in >>> "a" as a single item. >>> >>> I get: >>> None None >> >>First of all, an empty list is created with: >> >>emptylist = [] >> >>whereas >> >>x = [""] >> >>creates a list containing one element, that element being an empty >>string. Not the same thing! >> >>Did you try stepping through your code line by line in the interpreter >>to see what happened at each step? >> >>note that append is a method of a list object, it has no return value, >>the original list is modified in place. >> >>>>> l = ["a","b","c"] # declare a list l.append( "d" ) # use the >>>>> append method l # show the list >>['a', 'b', 'c', 'd'] >> >>So your line: >> >>lst = lst.append(y) >> >>should be: >> >>lst.append(y) >> >>Finally, did you really intend to pass a single element list into the >>function, or did you intend to pass a string into the function? >> > Those string errors were desperate attempts to fix the "append" error I > didn't understand. If you don't understand the error, that is the point that you should ask for help, rather than make stab in the dark attempts to fix it and then asking why the solutions don't work. -- Denis McMahon, denismfmcmahon at gmail.com From python at mrabarnett.plus.com Thu Oct 23 06:12:57 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 23 Oct 2014 11:12:57 +0100 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: <5448D4A9.7010200@mrabarnett.plus.com> On 2014-10-23 04:46, Gregory Ewing wrote: > Chris Angelico wrote: >> I've seen much MUCH worse... where multiple conditional >> expressions get combined arithmetically, and then the result used >> somewhere... > > In the days of old-school BASIC it was common to > exploit the fact that boolean expressions evaluated > to 0 or 1 (or -1, depending on your dialect :) to > achieve conditional expressions or other tricks. > > Probably forgiveable, given that there were no real > conditional expressions, and every byte of your 48K > or less of RAM was precious... > 48K? Luxury! From bc at freeuk.com Thu Oct 23 06:50:51 2014 From: bc at freeuk.com (BartC) Date: Thu, 23 Oct 2014 11:50:51 +0100 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> Message-ID: "Dennis Lee Bieber" wrote in message news:mailman.15097.1414022143.18130.python-list at python.org... > On Wed, 22 Oct 2014 19:08:40 +0100, "BartC" declaimed the > following: > >> >>Comparing: >> >> x = cond ? f() : g(); # C version >> >>with >> >> x = [f(), g()] [cond] (Should probably be x = [g(), f()] [cond]) >> >>the latter evaluates both f() and g() instead of just one. Apart from >>being >>inefficient, it can have unintended side-effects. > > Ah, but what would > > x = [f, g][cond]() > > produce? It will select f or g (which should refer to functions), and call one of those depending on cond. That's not a problem. The problem is it will still evaluate both f and g, even if they are simple in this case, and construct a list which is then indexed by cond. (Although in this case a bytecode compiler might be smart enough to avoid constructing the list, it can't do that with my example because the code might depend on both those options being evaluated.) -- Bartc From kw at codebykevin.com Thu Oct 23 09:25:54 2014 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 23 Oct 2014 09:25:54 -0400 Subject: OS X Menubar in Tkinter In-Reply-To: References: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> Message-ID: On 10/21/14, 1:58 AM, Mark Lawrence wrote: > I'm pleased to see that you have an answer. In return would you please > access this list via > https://mail.python.org/mailman/listinfo/python-list or read and action > this https://wiki.python.org/moin/GoogleGroupsPython to prevent us > seeing double line spacing and single line paragraphs, thanks. And admonitions of this type should be taken to comp.misc.propernntpformatting or groups.google.com/propergroupsformatting. They are OT for a list devoted to the Python programming language. I'd rather see flame wars over indenting vs. curly braces than this kind of constant policing of folks who come to us via Google: they greatly increase the noise I have to filter out. -- Kevin Walzer Code by Kevin/Mobile Code by Kevin http://www.codebykevin.com http://www.wtmobilesoftware.com From sffjunkie at gmail.com Thu Oct 23 09:36:37 2014 From: sffjunkie at gmail.com (Simon Kennedy) Date: Thu, 23 Oct 2014 06:36:37 -0700 (PDT) Subject: setuptools + data_files = 2 In-Reply-To: <5447fac2$0$2384$426a74cc@news.free.fr> References: <5447fac2$0$2384$426a74cc@news.free.fr> Message-ID: <7ec70158-2eab-4590-93a6-784ffc8538e4@googlegroups.com> On Wednesday, 22 October 2014 19:43:25 UTC+1, luc2 wrote: > hello, would you know how to make data_files work in setuptools ? > i can't figure out how to put datas in the generated .tar.gz If you're creating an sdist then you'll need to create a MANIFEST.in file in the same folder as setup.py with the following contents include share/test_file.txt If you're creating a bdist (egg or wheel) the parameter name you need is package_data={'share': [share/test_file.txt]}, From rustompmody at gmail.com Thu Oct 23 09:42:43 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 23 Oct 2014 06:42:43 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> Message-ID: On Thursday, October 23, 2014 1:39:32 PM UTC+5:30, Mark Lawrence wrote: > On 23/10/2014 08:56, Ian Kelly wrote: > > On Thu, Oct 23, 2014 at 1:20 AM, Mark Lawrence wrote: > >> If you were to read and digest what is written it would help. You're trying > >> to run IDLE. We're talking the interactive interpreter. > > > > IDLE includes the interactive interpreter. > > > >> If (at least on > >> Windows) you run a command prompt and then type python you should see > >> something like this. > >> > >> Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit > >> (AMD64)] on win32 > >> Type "help", "copyright", "credits" or "license" for more information. > > > > Same thing comes up when I start IDLE, so what's your point? > > > > When you run the interactive interpreter thats all you get. The OP > isn't the first person to try things with IDLE not realising you need to > have a script loaded to do something. If I do (at the shell prompt with an example) $ python3 Python 3.4.2 (default, Oct 8 2014, 10:45:20) [GCC 4.9.1] on linux Type "help", "copyright", "credits" or "license" for more information. >>> 2+3 5 And if I do $ idle3 I get a new window containing Python 3.4.2 (default, Oct 8 2014, 10:45:20) [GCC 4.9.1] on linux Type "copyright", "credits" or "license()" for more information. >>> 2+3 5 so... Still not clear whats your point. idle and python interpreter seem to be mostly the same [As best as I can make out the OP is not using the standalone interpreter nor idle nor (the many options like) python-interpreter-inside-emacs nor ipython nor ... ] From marko at pacujo.net Thu Oct 23 09:44:06 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 23 Oct 2014 16:44:06 +0300 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> Message-ID: <878uk6x5nd.fsf@elektro.pacujo.net> "BartC" : >> Ah, but what would >> >> x = [f, g][cond]() >> >> produce? > > It will select f or g (which should refer to functions), and call one of > those depending on cond. That's not a problem. > > The problem is it will still evaluate both f and g, That's not really the problem. The problem is in readability. However, the "[f, g][cond]()" technique is how pure lambda calculus implements conditional branching so it is interesting in its own right. IOW, you can do "short-circuiting" in purely functional programming: j = j + 1 if j < 10 else 3 <=> j = (lambda: 3, lambda: j + 1)[j < 10]() Marko From Seymore4Head at Hotmail.invalid Thu Oct 23 09:53:48 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 09:53:48 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Thu, 23 Oct 2014 00:10:28 -0700, Larry Hudson wrote: >On 10/22/2014 03:30 PM, Seymore4Head wrote: >> On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head >> wrote: >> >> One more question. >> if y in str(range(10) >> Why doesn't that work. >> I commented it out and just did it "long hand" >> >> def nametonumber(name): >> lst=[] >> nx=[] >> for x in (name): >> lst.append(x) >> for y in (lst): >> #if y in str(range(10)): >> if y in "1234567890": >> nx.append(y) >> if y in " -()": >> nx.append(y) >> if y in "abc": >> nx.append("2") >> if y in "def": >> nx.append("3") >> if y in "ghi": >> nx.append("4") >> if y in "jkl": >> nx.append("5") >> if y in "mno": >> nx.append("6") >> if y in "pqrs": >> nx.append("7") >> if y in "tuv": >> nx.append("8") >> if y in "wxyz": >> nx.append("9") >> number="".join(str(e) for e in nx) >> return (number) >> a="1-800-getcharter" >> print (nametonumber(a))#1800 438 2427 837 >> a="1-800-leo laporte" >> print (nametonumber(a)) >> a="1 800 callaprogrammer" >> print (nametonumber(a)) >> >I know you are trying to explore lists here, but I found myself somewhat intrigued with the >problem itself, so I wrote a different version. This version does not use lists but only >strings. I'm just presenting it as-is to let you try to follow the logic, but if you ask, I'll >explain it in detail. It turns your long sequence of if's essentially into a single line -- >unfortunately 's' and 'z' have to be handled as special-cases, which turns that single line into >a six-line if/elif/else set. You might consider this line 'tricky', but I'll just say it's just >looking at the problem from a different viewpoint. BTW, this version accepts upper-case as well >as lower-case. isdigit() and isalpha() are standard string methods. > >#------ Code ---------- >def name2number(name): > nstr = '' # Phone-number string to return > codes = 'abcdefghijklmnopqrtuvwxy' # Note missing s and z > > for ch in name: > if ch in " -()": > nstr += ch > elif ch.isdigit(): > nstr += ch > elif ch.isalpha(): > ch = ch.lower() > # S and Z are special cases > if ch == 's': > nstr += '7' > elif ch == 'z': > nstr += '9' > else: > nstr += str(codes.index(ch) // 3 + 2) > return nstr >#------- End of Code --------- > >A possible variation would be to make nstr a list instead of a string, and use .append() instead >of the +=, and finally return the string by using join() on the list. Also, the if and first >elif in the for could be combined: if ch in " -()" or ch.isdigit(): > > -=- Larry -=- Sure I will have a look at it. I am always open on better ways to do something. Thanks From Seymore4Head at Hotmail.invalid Thu Oct 23 10:00:38 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 10:00:38 -0400 Subject: I am out of trial and error again Lists References: Message-ID: <9c2i4ahg7pqabg5bl1i5bm67ebia25p406@4ax.com> On Thu, 23 Oct 2014 09:23:29 -0400, Dennis Lee Bieber wrote: >On Thu, 23 Oct 2014 00:10:28 -0700, Larry Hudson > declaimed the following: > > >>I know you are trying to explore lists here, but I found myself somewhat intrigued with the >>problem itself, so I wrote a different version. This version does not use lists but only >>strings. I'm just presenting it as-is to let you try to follow the logic, but if you ask, I'll >>explain it in detail. It turns your long sequence of if's essentially into a single line -- >>unfortunately 's' and 'z' have to be handled as special-cases, which turns that single line into >>a six-line if/elif/else set. You might consider this line 'tricky', but I'll just say it's just >>looking at the problem from a different viewpoint. BTW, this version accepts upper-case as well >>as lower-case. isdigit() and isalpha() are standard string methods. >> > > > > This is another example where changing data structures can simplify >things a lot... > >-=-=-=-=-=-=- >keys = { "a" : "2", "b" : "2", "c" : "2", # 1 is not assigned > "d" : "3", "e" : "3", "f" : "3", > "g" : "4", "h" : "4", "i" : "4", > "j" : "5", "k" : "5", "l" : "5", > "m" : "6", "n" : "6", "o" : "6", > "p" : "7", "q" : "7", "r" : "7", "s" : "7", > "t" : "8", "u" : "8", "v" : "8", > "w" : "9", "x" : "9", "y" : "9", "z" : "9" } > >def textToNumber(inp): > outp = [] > for c in inp.lower(): > outp.append(keys.get(c, c)) > return "".join(outp) > >if __name__ == "__main__": > while True: > #NOTE: Python 2.7! > aNumStr = raw_input("\nEnter Phone Number String: ") > if not aNumStr: break > print "Converted to all numbers: %s" % textToNumber(aNumStr) > I'll have a look at this one too. I haven't used a dictionary yet. Thanks >-=-=-=-=-=-=- >Microsoft Windows [Version 6.1.7601] >Copyright (c) 2009 Microsoft Corporation. All rights reserved. > >C:\Users\Wulfraed\Documents\Python Progs>Phone.py > >Enter Phone Number String: 1-800-getcharter >Converted to all numbers: 1-800-4382427837 > >Enter Phone Number String: 1-800-leo laporte >Converted to all numbers: 1-800-536 5276783 > >Enter Phone Number String: 1 800 callaprogrammer >Converted to all numbers: 1 800 225527764726637 > >Enter Phone Number String: +1(800)Leo-Laporte >Converted to all numbers: +1(800)536-5276783 > >Enter Phone Number String: > >C:\Users\Wulfraed\Documents\Python Progs> From Seymore4Head at Hotmail.invalid Thu Oct 23 10:01:46 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 10:01:46 -0400 Subject: I am out of trial and error again Lists References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> Message-ID: On Thu, 23 Oct 2014 08:20:32 +0100, Mark Lawrence wrote: >On 23/10/2014 02:57, Seymore4Head wrote: >> On Wed, 22 Oct 2014 21:35:19 -0400, Seymore4Head >> wrote: >> >>> On Thu, 23 Oct 2014 02:31:57 +0100, MRAB >>> wrote: >>> >>>> On 2014-10-23 01:10, Seymore4Head wrote: >>>>> On Thu, 23 Oct 2014 11:05:08 +1100, Steven D'Aprano >>>>> wrote: >>>>> >>>>>> Seymore4Head wrote: >>>>>> >>>>>>> Those string errors were desperate attempts to fix the "append" error >>>>>>> I didn't understand. >>>>>> >>>>>> Ah, the good ol' "make random changes to the code until the error goes away" >>>>>> technique. You know that it never works, right? >>>>>> >>>>>> Start by *reading the error message*, assuming you're getting an error >>>>>> message. I'm the first person to admit that Python's error messages are not >>>>>> always as clear as they should be, especially syntax errors, but still >>>>>> there is a lot of information that can be gleamed from most error messages. >>>>>> Take this attempt to use append: >>>>>> >>>>>> py> mylist.append(23) >>>>>> Traceback (most recent call last): >>>>>> File "", line 1, in >>>>>> NameError: name 'mylist' is not defined >>>>>> >>>>>> That tells me that I have forgotten to define a variable mylist. So I fix >>>>>> that: >>>>>> >>>>>> py> mylist = 23 >>>>>> py> mylist.append(23) >>>>>> Traceback (most recent call last): >>>>>> File "", line 1, in >>>>>> AttributeError: 'int' object has no attribute 'append' >>>>>> >>>>>> >>>>>> That tells me that I can't append to a int. After googling for "Python >>>>>> append" I learn that I can append to a list, so I try again: >>>>>> >>>>>> py> mylist = [] >>>>>> py> mylist.append(23) >>>>>> py> print(mylist) >>>>>> [23] >>>>>> >>>>>> >>>>>> Success! >>>>>> >>>>>> If you are familiar with other programming languages, it might help to think >>>>>> of append() as being like a procedure in Pascal, for example. You call >>>>>> append() with an argument, but don't expect a return result. >>>>>> >>>>>> Technically, *all* functions and methods in Python return something, even if >>>>>> just the special value None, which can lead to "Gotchas!" like this one: >>>>>> >>>>>> py> mylist = mylist.append(42) # Don't do this! >>>>>> py> print(mylist) # I expect [23, 42] but get None instead. >>>>>> None >>>>>> >>>>>> Oops. One of the small annoyances of Python is that there is no way to tell >>>>>> ahead of time, except by reading the documentation, whether something is a >>>>>> proper function that returns a useful value, or a procedure-like function >>>>>> that returns None. That's just something you have to learn. >>>>>> >>>>>> The interactive interpreter is your friend. Learn to experiment at the >>>>>> interactive interpreter -- you do know how to do that, don't you? If not, >>>>>> ask. At the interactive interpreter, if a function or method returns a >>>>>> value, it will be printed, *except for None*. So a function that doesn't >>>>>> print anything might be procedure-like, and one which does print something >>>>>> might not be: >>>>>> >>>>>> py> mylist = [1, 5, 2, 6, 4, 3] >>>>>> py> sorted(mylist) # proper function returns a value >>>>>> [1, 2, 3, 4, 5, 6] >>>>>> py> mylist.sort() # procedure-like function returns None >>>>>> py> print(mylist) # and modifies the list in place >>>>>> [1, 2, 3, 4, 5, 6] >>>>> >>>>> I am going to get around to learning the interpreter soon. >>>>> >>>> Why wait? >>>> >>>> You're trying to learn the language _now_, and checking things >>>> interactively will help you. >>> >>> Because most of the practice I am getting is not using Python. I use >>> Codeskulptor. >>> >>> OK.........Now is as good a time as ever. >>> >>> Thanks >> >> Now I remember why...........nothing happens >> http://i.imgur.com/MIRpqzY.jpg >> >> If I click on the shell window, I can get the grayed options to show >> up for one turn. >> I hit step and everything goes gray again. >> >> http://i.imgur.com/NtMdmU1.jpg >> >> Not a very fruitful exercise. :( >> > >If you were to read and digest what is written it would help. You're >trying to run IDLE. We're talking the interactive interpreter. If (at >least on Windows) you run a command prompt and then type python you >should see something like this. > >Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 >bit (AMD64)] on win32 >Type "help", "copyright", "credits" or "license" for more information. OK Thanks From Seymore4Head at Hotmail.invalid Thu Oct 23 10:03:55 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 10:03:55 -0400 Subject: I am out of trial and error again Lists References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> Message-ID: On Thu, 23 Oct 2014 06:42:43 -0700 (PDT), Rustom Mody wrote: >On Thursday, October 23, 2014 1:39:32 PM UTC+5:30, Mark Lawrence wrote: >> On 23/10/2014 08:56, Ian Kelly wrote: >> > On Thu, Oct 23, 2014 at 1:20 AM, Mark Lawrence wrote: >> >> If you were to read and digest what is written it would help. You're trying >> >> to run IDLE. We're talking the interactive interpreter. >> > >> > IDLE includes the interactive interpreter. >> > >> >> If (at least on >> >> Windows) you run a command prompt and then type python you should see >> >> something like this. >> >> >> >> Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit >> >> (AMD64)] on win32 >> >> Type "help", "copyright", "credits" or "license" for more information. >> > >> > Same thing comes up when I start IDLE, so what's your point? >> > >> >> When you run the interactive interpreter thats all you get. The OP >> isn't the first person to try things with IDLE not realising you need to >> have a script loaded to do something. > >If I do (at the shell prompt with an example) >$ python3 >Python 3.4.2 (default, Oct 8 2014, 10:45:20) >[GCC 4.9.1] on linux >Type "help", "copyright", "credits" or "license" for more information. >>>> 2+3 >5 > >And if I do >$ idle3 >I get a new window containing > >Python 3.4.2 (default, Oct 8 2014, 10:45:20) >[GCC 4.9.1] on linux >Type "copyright", "credits" or "license()" for more information. >>>> 2+3 >5 > >so... >Still not clear whats your point. >idle and python interpreter seem to be mostly the same > >[As best as I can make out the OP is not using the standalone >interpreter >nor idle >nor (the many options like) python-interpreter-inside-emacs >nor ipython >nor ... >] I don't know the difference, yet. I am gonna get around to reading the Internet one of these days. :) From Seymore4Head at Hotmail.invalid Thu Oct 23 10:04:56 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 10:04:56 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Thu, 23 Oct 2014 09:15:16 +0000 (UTC), Denis McMahon wrote: >On Wed, 22 Oct 2014 18:30:17 -0400, Seymore4Head wrote: > >> One more question. >> if y in str(range(10) >> Why doesn't that work. >> I commented it out and just did it "long hand" > >In the last post I made, I suggested to you the mechanisms of using the >python console and using code which prints out variables after every line. > >Try the following 3 commands at the console: > >>>> 10 >>>> range(10) >>>> str(range(10)) > >10 is just the number 10 >range(10) is a list of 10 integers in the sequence 0 to 9 >str(range(10)) is? > >Please stop the stab in the dark trial and error coding followed by the >plaintive "why doesn't it work" wailing, and put some effort into reading >and understanding the manuals. > >If a function doesn't do what you expect with the input you think you've >given it, there is invariably one of three causes: > >a) The input you actually gave it isn't the input you thought you gave it >b) You didn't read the description of the function, and it doesn't in >fact do what you thought >c) Both a and b above Ok Thanks From ian.g.kelly at gmail.com Thu Oct 23 10:24:07 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 23 Oct 2014 08:24:07 -0600 Subject: (test) ? a:b In-Reply-To: <878uk6x5nd.fsf@elektro.pacujo.net> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> Message-ID: On Thu, Oct 23, 2014 at 7:44 AM, Marko Rauhamaa wrote: > However, the "[f, g][cond]()" technique is how pure lambda calculus > implements conditional branching so it is interesting in its own right. I wasn't aware that lambda calculus had lists and indexing built in. > IOW, you can do "short-circuiting" in purely functional programming: > > j = j + 1 if j < 10 else 3 > > <=> > > j = (lambda: 3, lambda: j + 1)[j < 10]() The implementation given by Wikipedia (and translated into Python by me) is: >>> true = lambda x: lambda y: x >>> false = lambda x: lambda y: y >>> ifthenelse = lambda p: lambda a: lambda b: p(a)(b) >>> ifthenelse(true)(1)(2) 1 >>> ifthenelse(false)(1)(2) 2 For demonstration purposes I used Python ints as the branches rather than actual lambda calculus constructs, but this shows how selection can be done using only lambda abstractions and applications. In any case I don't see how this relates to the "[f, g][cond]()" technique of Python, unless you just meant the general approach of first selecting a function and then applying it. In that sense though, the ternary operator does the same thing; the application is just done invisibly by the language in the form of evaluating an expression as opposed to explicitly applying a function. From pecore at pascolo.net Thu Oct 23 10:25:28 2014 From: pecore at pascolo.net (giacomo boffi) Date: Thu, 23 Oct 2014 16:25:28 +0200 Subject: I am out of trial and error again Lists References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> Message-ID: <8738aehnhj.fsf@pascolo.net> Rustom Mody writes: > [As best as I can make out the OP is not using the standalone > interpreter > nor idle > nor (the many options like) python-interpreter-inside-emacs > nor ipython > nor ... but CodeSkulptor ] CodeSkulptor has been mentioned recently by S4H, and he had explained why he uses CodeSkulptor, but I cannot remember anything of the explanation... -- > Sarebbe ora gli scienziati italiani mostrassero un po' i coglioni si`, vabbe`, ma a chi? -- PLS, in IFQ From sffjunkie at gmail.com Thu Oct 23 10:30:07 2014 From: sffjunkie at gmail.com (Simon Kennedy) Date: Thu, 23 Oct 2014 07:30:07 -0700 (PDT) Subject: Truthiness Message-ID: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> Just out of academic interest, is there somewhere in the Python docs where the following is explained? >>> 3 == True False >>> if 3: print("It's Twue") It's Twue i.e. in the if statement 3 is True but not in the first From Seymore4Head at Hotmail.invalid Thu Oct 23 10:29:49 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 10:29:49 -0400 Subject: I am out of trial and error again Lists References: <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> <8738aehnhj.fsf@pascolo.net> Message-ID: On Thu, 23 Oct 2014 16:25:28 +0200, giacomo boffi wrote: >Rustom Mody writes: > >> [As best as I can make out the OP is not using the standalone >> interpreter >> nor idle >> nor (the many options like) python-interpreter-inside-emacs >> nor ipython >> nor ... > >but CodeSkulptor ] > >CodeSkulptor has been mentioned recently by S4H, and he had explained >why he uses CodeSkulptor, but I cannot remember anything of the explanation... They are using it in the online course I am taking An Introduction to Interactive Programming in Python https://www.coursera.org/ It is clumsy and it is not compatible with Python3, but it is free. 3 more weeks. From pecore at pascolo.net Thu Oct 23 10:40:22 2014 From: pecore at pascolo.net (giacomo boffi) Date: Thu, 23 Oct 2014 16:40:22 +0200 Subject: I am out of trial and error again Lists References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> Message-ID: <87y4s6g889.fsf@pascolo.net> Seymore4Head writes: > Because most of the practice I am getting is not using Python. I > use Codeskulptor. Seymore, it's been months that you're struggling with python, if you happen to own a computer could you please take the time to install python on it and familiarise with the interactive interpreter? I'll see that as a personal favor. If you have to hand in assignments using codeskulptor or are in any other way bound by your institution to use that service you could anyway use the interactive interpreter on your pc, applying the debugging and self-learning techniques that were shown to you, in many different circumstances, by the very, very helpful folks of clp. thank you for your attention From alain at dpt-info.u-strasbg.fr Thu Oct 23 10:41:02 2014 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 23 Oct 2014 16:41:02 +0200 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> Message-ID: <87fvee3l35.fsf@dpt-info.u-strasbg.fr> Marko Rauhamaa writes: > "BartC" : >>> x = [f, g][cond]() >> It will select f or g (which should refer to functions), and call one of >> those depending on cond. That's not a problem. >> >> The problem is it will still evaluate both f and g, > > That's not really the problem. The problem is in readability. Readability is in the eye of the beholder. The evaluation is the central concern here. > However, the "[f, g][cond]()" technique is how pure lambda calculus > implements conditional branching so it is interesting in its own > right. Yes, but lambda calculus constructs have no meaning without an evaluation strategy ("reduction" strategy in lambda calculs parlance). > IOW, you can do "short-circuiting" in purely functional programming: > > j = j + 1 if j < 10 else 3 > <=> > j = (lambda: 3, lambda: j + 1)[j < 10]() This is just a way to delay evaluation *of the potential results*, i.e., instill a bit of lazyness. One could object that, again, both expressions in the tuple have been evaluated (building two lambdas), only one of which is finally called. I guess that's what BartC meant. -- Alain. From ian.g.kelly at gmail.com Thu Oct 23 10:45:47 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 23 Oct 2014 08:45:47 -0600 Subject: Truthiness In-Reply-To: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> References: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> Message-ID: On Thu, Oct 23, 2014 at 8:30 AM, Simon Kennedy wrote: > Just out of academic interest, is there somewhere in the Python docs where the following is explained? https://docs.python.org/3/reference/expressions.html#booleans >>>> 3 == True > False >>>> if 3: > print("It's Twue") > > It's Twue > > i.e. in the if statement 3 is True but not in the first No, 3 is merely true, not True. True is just the name of a particular singleton object that is also true. From wolfgang.maier at biologie.uni-freiburg.de Thu Oct 23 10:49:05 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Thu, 23 Oct 2014 16:49:05 +0200 Subject: Truthiness In-Reply-To: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> References: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> Message-ID: On 10/23/2014 04:30 PM, Simon Kennedy wrote: > Just out of academic interest, is there somewhere in the Python docs where the following is explained? > https://docs.python.org/3/library/stdtypes.html#truth-value-testing >>>> 3 == True > False as opposed to: https://docs.python.org/3/library/stdtypes.html#comparisons >>>> if 3: > print("It's Twue") > > It's Twue > > i.e. in the if statement 3 is True but not in the first > Here is the misunderstanding: it is not true that 3 is True in the if example, but it's evaluated as True in a boolean context. Illustration: >>> 3 == True False >>> bool(3) == True True >>> bool(3) is True True If you combine if and a comparison, it behaves like in your first example: >>> if 3 == True: print('True') else: print('False') False From alain at dpt-info.u-strasbg.fr Thu Oct 23 10:47:27 2014 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Thu, 23 Oct 2014 16:47:27 +0200 Subject: Truthiness References: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> Message-ID: <87bnp23ksg.fsf@dpt-info.u-strasbg.fr> Simon Kennedy writes: > Just out of academic interest, is there somewhere in the Python docs where the following is explained? > >>>> 3 == True > False >>>> if 3: > print("It's Twue") > > It's Twue > > i.e. in the if statement 3 is True but not in the first https://docs.python.org/2/reference/compound_stmts.html#the-if-statement says: "The if statement [...] selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section Boolean operations for the definition of true and false)" and then: https://docs.python.org/2/reference/expressions.html#booleans says: "In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true." (links are to the 2.7 version of the reference manual, I think not much has changed in 3.* versions.) -- Alain. From Seymore4Head at Hotmail.invalid Thu Oct 23 10:46:12 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 10:46:12 -0400 Subject: I am out of trial and error again Lists References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> <87y4s6g889.fsf@pascolo.net> Message-ID: <725i4altu8gl3pdkhgb5tpej9dr254t1cn@4ax.com> On Thu, 23 Oct 2014 16:40:22 +0200, giacomo boffi wrote: >Seymore4Head writes: > >> Because most of the practice I am getting is not using Python. I >> use Codeskulptor. > >Seymore, > >it's been months that you're struggling with python, if you happen to >own a computer could you please take the time to install python on it >and familiarise with the interactive interpreter? I'll see that as a >personal favor. If you have to hand in assignments using codeskulptor >or are in any other way bound by your institution to use that service >you could anyway use the interactive interpreter on your pc, applying >the debugging and self-learning techniques that were shown to you, in >many different circumstances, by the very, very helpful folks of clp. > >thank you for your attention I have Python installed. I will learn the interpreter. I also acknowledge there are very, very helpful folks here. Thanks From skip.montanaro at gmail.com Thu Oct 23 10:51:47 2014 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Thu, 23 Oct 2014 09:51:47 -0500 Subject: Truthiness In-Reply-To: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> References: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> Message-ID: On Thu, Oct 23, 2014 at 9:30 AM, Simon Kennedy wrote: > Just out of academic interest, is there somewhere in the Python docs where > the following is explained? Yes: https://docs.python.org/3/library/stdtypes.html#truth-value-testing https://docs.python.org/2.7/library/stdtypes.html#truth-value-testing Skip -------------- next part -------------- An HTML attachment was scrubbed... URL: From toby at tobiah.org Thu Oct 23 10:51:11 2014 From: toby at tobiah.org (Tobiah) Date: Thu, 23 Oct 2014 07:51:11 -0700 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 10/22/2014 01:30 PM, Seymore4Head wrote: > def nametonumber(name): > lst=[""] > for x,y in enumerate (name): > lst=lst.append(y) > print (lst) > return (lst) > a=["1-800-getcharter"] > print (nametonumber(a))#18004382427837 > > > The syntax for when to use a () and when to use [] still throws me a > curve. > > For now, I am trying to end up with a list that has each character in > "a" as a single item. >>> a = "1-800-getcharter" >>> list(a) ['1', '-', '8', '0', '0', '-', 'g', 'e', 't', 'c', 'h', 'a', 'r', 't', 'e', 'r'] >>> From sffjunkie at gmail.com Thu Oct 23 10:56:43 2014 From: sffjunkie at gmail.com (Simon Kennedy) Date: Thu, 23 Oct 2014 07:56:43 -0700 (PDT) Subject: Truthiness In-Reply-To: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> References: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> Message-ID: <074b949d-9999-42b9-9136-6e32d1cee922@googlegroups.com> Thanks everyone. That's a thorough enough explanation for me. From wolfgang.maier at biologie.uni-freiburg.de Thu Oct 23 11:01:43 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Thu, 23 Oct 2014 17:01:43 +0200 Subject: Truthiness In-Reply-To: <87bnp23ksg.fsf@dpt-info.u-strasbg.fr> References: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> <87bnp23ksg.fsf@dpt-info.u-strasbg.fr> Message-ID: On 10/23/2014 04:47 PM, Alain Ketterlin wrote: > Simon Kennedy writes: > >> Just out of academic interest, is there somewhere in the Python docs where the following is explained? >> >>>>> 3 == True >> False >>>>> if 3: >> print("It's Twue") >> >> It's Twue >> >> i.e. in the if statement 3 is True but not in the first > > https://docs.python.org/2/reference/compound_stmts.html#the-if-statement > > says: "The if statement [...] selects exactly one of the suites by > evaluating the expressions one by one until one is found to be true (see > section Boolean operations for the definition of true and false)" > Exactly, but in if 3 == True: the expression is 3==True , in which 3 and True compare unequal, thus, the expression is false. On the other hand, in if 3: the expression to evaluate is just the int object and the rules below apply. > and then: > > https://docs.python.org/2/reference/expressions.html#booleans > > says: "In the context of Boolean operations, and also when expressions > are used by control flow statements, the following values are > interpreted as false: False, None, numeric zero of all types, and empty > strings and containers (including strings, tuples, lists, dictionaries, > sets and frozensets). All other values are interpreted as true." > > (links are to the 2.7 version of the reference manual, I think not much > has changed in 3.* versions.) > > -- Alain. > From random832 at fastmail.us Thu Oct 23 11:24:43 2014 From: random832 at fastmail.us (random832 at fastmail.us) Date: Thu, 23 Oct 2014 11:24:43 -0400 Subject: Truthiness In-Reply-To: <074b949d-9999-42b9-9136-6e32d1cee922@googlegroups.com> References: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> <074b949d-9999-42b9-9136-6e32d1cee922@googlegroups.com> Message-ID: <1414077883.1391942.182486049.525AE5E1@webmail.messagingengine.com> On Thu, Oct 23, 2014, at 10:56, Simon Kennedy wrote: > Thanks everyone. That's a thorough enough explanation for me. You should know, though, that numeric values equal to 1 (and 0 for False) _are_ == True. This works for dictionary keys, array indexes, etc. The bool type is actually a subclass of int. Mathematical operations on it will simply return an int, or float for division - logical operations and bitwise and/or/xor return bool (bitwise not returns an int because it returns the values -1 and -2) So checking if something is == True is the same as checking if it's == 1, and checking if it's == False is the same as checking if it's == 0. From rustompmody at gmail.com Thu Oct 23 11:35:50 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 23 Oct 2014 08:35:50 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> Message-ID: <55a283b9-adfb-44b9-b35e-cf18aeb5f87e@googlegroups.com> On Thursday, October 23, 2014 7:36:28 PM UTC+5:30, Seymore4Head wrote: > On Thu, 23 Oct 2014 06:42:43 -0700 (PDT), Rustom Mody wrote: > >[As best as I can make out the OP is not using the standalone > >interpreter > >nor idle > >nor (the many options like) python-interpreter-inside-emacs > >nor ipython > >nor ... > >] > I don't know the difference, yet. I am gonna get around to reading > the Internet one of these days. > :) Hoo Boy! You may like to start here http://en.wikibooks.org/wiki/Python_Programming/Interactive_mode Then stop and try what is suggested Then come back here and ask what (if any) goes wrong From denismfmcmahon at gmail.com Thu Oct 23 11:55:35 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 23 Oct 2014 15:55:35 +0000 (UTC) Subject: I am out of trial and error again Lists References: Message-ID: On Thu, 23 Oct 2014 10:04:56 -0400, Seymore4Head wrote: > On Thu, 23 Oct 2014 09:15:16 +0000 (UTC), Denis McMahon > wrote: >>Try the following 3 commands at the console: You obviously didn't, so I'll try again. Try each of the following three commands in the python console at the ">>>" prompt. 1) 10 2) range(10) 3) str(range(10)) Show *and* describe the output in each case. Describing the output that you see is actually the key here, as it will allow us to assess whether you understand what you are actually seeing or not, and if you don't understand the output you see in the console, then we need to fix that very fundamental and basic issue before moving on to more complex stuff! > Ok Thanks You were expected to answer the question in the original. I have now set it as a clearer and more specific task. If you're not going to do these things that are intended to help you learn some of the basic features of the language, then I and everyone else here that has so far been attempting to help you are wasting our time. -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Thu Oct 23 12:00:30 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 23 Oct 2014 16:00:30 +0000 (UTC) Subject: I am out of trial and error again Lists References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> <8738aehnhj.fsf@pascolo.net> Message-ID: On Thu, 23 Oct 2014 16:25:28 +0200, giacomo boffi wrote: > Rustom Mody writes: > >> [As best as I can make out the OP is not using the standalone >> interpreter nor idle nor (the many options like) >> python-interpreter-inside-emacs nor ipython nor ... > > but CodeSkulptor ] > > CodeSkulptor has been mentioned recently by S4H, and he had explained > why he uses CodeSkulptor, but I cannot remember anything of the > explanation... CodeSkulptor is a tool used by a group of instructors at RICE to teach an on-line python programming course in a web browser environment. It may be a python IDE and interpreter implemented in HTML, CSS and javascript, I'm not sure. IO is handled by a package called simplegui, and I believe there's a wrapper for tkinter that presents simplegui if you want to run code written for codeskulptor outside of the codeskulptor environment. -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Thu Oct 23 12:07:14 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Thu, 23 Oct 2014 16:07:14 +0000 (UTC) Subject: Truthiness References: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> <87bnp23ksg.fsf@dpt-info.u-strasbg.fr> Message-ID: On Thu, 23 Oct 2014 16:47:27 +0200, Alain Ketterlin wrote: > says: "In the context of Boolean operations, and also when expressions > are used by control flow statements, the following values are > interpreted as false: False, None, numeric zero of all types, and empty > strings and containers (including strings, tuples, lists, dictionaries, > sets and frozensets). All other values are interpreted as true." Yep, and I expect this to bite S4H shortly, when he can't understand why the following are not all of the same truthiness: 0 (falsey - numeric 0) [] (falsey - empty set) "" (falsey - empty string) [""] (truthy - non empty set) [0] (truthy - non empty set) -- Denis McMahon, denismfmcmahon at gmail.com From marko at pacujo.net Thu Oct 23 12:20:03 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Thu, 23 Oct 2014 19:20:03 +0300 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <87fvee3l35.fsf@dpt-info.u-strasbg.fr> Message-ID: <87iojag3m4.fsf@elektro.pacujo.net> Alain Ketterlin : >> j = (lambda: 3, lambda: j + 1)[j < 10]() > > This is just a way to delay evaluation *of the potential results*, > i.e., instill a bit of lazyness. That's one way to characterize a function, or code in general. That point of view is apparent in PostScript, where control structures are expressed "lazily" with lambdas: 5 eq { gsave 0.85 1 0.85 setrgbcolor fill grestore } if The { ... } block is a piece of code pushed onto the stack. Marko From Seymore4Head at Hotmail.invalid Thu Oct 23 13:01:18 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 13:01:18 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Thu, 23 Oct 2014 15:55:35 +0000 (UTC), Denis McMahon wrote: >On Thu, 23 Oct 2014 10:04:56 -0400, Seymore4Head wrote: > >> On Thu, 23 Oct 2014 09:15:16 +0000 (UTC), Denis McMahon >> wrote: > >>>Try the following 3 commands at the console: > >You obviously didn't, so I'll try again. Try each of the following three >commands in the python console at the ">>>" prompt. > >1) 10 10 >2) range(10) range(0, 10) >3) str(range(10)) 'range(0, 10)' [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > >Show *and* describe the output in each case. Describing the output that >you see is actually the key here, as it will allow us to assess whether >you understand what you are actually seeing or not, and if you don't >understand the output you see in the console, then we need to fix that >very fundamental and basic issue before moving on to more complex stuff! > >> Ok Thanks > >You were expected to answer the question in the original. I have now set >it as a clearer and more specific task. > >If you're not going to do these things that are intended to help you >learn some of the basic features of the language, then I and everyone >else here that has so far been attempting to help you are wasting our >time. I did try them. I may have missed replying your to your specific comment, but I tried them. BTW str(range (10)) does work with Python 2 which is where I may have got the idea. I happened to be using Python 3 at the time I tried to implement it. It is a little confusing jumping back and forth, but for the moment, I am going to tough it out. I do appreciate all the help too. From jkn_gg at nicorp.f9.co.uk Thu Oct 23 13:07:15 2014 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Thu, 23 Oct 2014 10:07:15 -0700 (PDT) Subject: FYI: Micro Python running on kickstarter pyBoard project, now shipping Message-ID: <25b4884f-a3f9-436d-8d7d-f49f83c3e544@googlegroups.com> Hi all I haven't heard in mentioned here, but since I saw one of the boards today thought I'd pass on the news: The Kickstarter 'MicroPython' project, which has a tiny 'pyboard' (only a couple of sq.inches in size) with a processor running 'a complete re-write of the Python (version 3.4) programming language so that it fits and runs on a microcontroller' is now shipping. https://micropython.org/ Looks nice; I have no connection but will be getting one myself to play with... Cheers J^n From Seymore4Head at Hotmail.invalid Thu Oct 23 13:07:30 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 13:07:30 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Thu, 23 Oct 2014 13:01:18 -0400, Seymore4Head wrote: >On Thu, 23 Oct 2014 15:55:35 +0000 (UTC), Denis McMahon > wrote: > >>On Thu, 23 Oct 2014 10:04:56 -0400, Seymore4Head wrote: >> >>> On Thu, 23 Oct 2014 09:15:16 +0000 (UTC), Denis McMahon >>> wrote: >> >>>>Try the following 3 commands at the console: >> >>You obviously didn't, so I'll try again. Try each of the following three >>commands in the python console at the ">>>" prompt. >> >>1) 10 >10 > >>2) range(10) >range(0, 10) > >>3) str(range(10)) >'range(0, 10)' >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >> BTW I forgot to add that example 2 and 3 don't seem to be too useful in Python 3, but they are in Python 2. I don't understand how the Python 3 is an improved version. >>Show *and* describe the output in each case. Describing the output that >>you see is actually the key here, as it will allow us to assess whether >>you understand what you are actually seeing or not, and if you don't >>understand the output you see in the console, then we need to fix that >>very fundamental and basic issue before moving on to more complex stuff! >> >>> Ok Thanks >> >>You were expected to answer the question in the original. I have now set >>it as a clearer and more specific task. >> >>If you're not going to do these things that are intended to help you >>learn some of the basic features of the language, then I and everyone >>else here that has so far been attempting to help you are wasting our >>time. > >I did try them. I may have missed replying your to your specific >comment, but I tried them. > >BTW str(range (10)) does work with Python 2 which is where I may have >got the idea. I happened to be using Python 3 at the time I tried to >implement it. It is a little confusing jumping back and forth, but >for the moment, I am going to tough it out. > >I do appreciate all the help too. From tjreedy at udel.edu Thu Oct 23 13:32:06 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 23 Oct 2014 13:32:06 -0400 Subject: OS X Menubar in Tkinter In-Reply-To: References: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> Message-ID: On 10/23/2014 9:25 AM, Kevin Walzer wrote: > On 10/21/14, 1:58 AM, Mark Lawrence wrote: >> I'm pleased to see that you have an answer. In return would you please >> access this list via >> https://mail.python.org/mailman/listinfo/python-list or read and action >> this https://wiki.python.org/moin/GoogleGroupsPython to prevent us >> seeing double line spacing and single line paragraphs, thanks. > > And admonitions of this type should be taken to > comp.misc.propernntpformatting or > groups.google.com/propergroupsformatting. They are OT for a list devoted > to the Python programming language. I'd rather see flame wars over > indenting vs. curly braces than this kind of constant policing of folks > who come to us via Google: they greatly increase the noise I have to > filter out. Kevin, feel free to filter out all of Mark's messages. People posting from Google groups do not know that messages look like the above after a few rounds thru gg since gg apparently corrects its own misformatting in its displays. Most people pay attention to Mark's information. I ignore those who do not and send quad- or octo-spaced messages. I have asked on python-list-admin that the same info be sent to new gg posters automatically and privately, or that the extra blanks be filtered out, but to no avail. -- Terry Jan Reedy From rosuav at gmail.com Thu Oct 23 15:02:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 24 Oct 2014 06:02:24 +1100 Subject: OS X Menubar in Tkinter In-Reply-To: References: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> Message-ID: On Fri, Oct 24, 2014 at 4:32 AM, Terry Reedy wrote: > I have asked on python-list-admin that the same info be sent to new gg > posters automatically and privately, or that the extra blanks be filtered > out, but to no avail. I don't think it's possible to auto-solve the Google Groups formatting issues at the mailing list level, as the fundamental problem is that information isn't being transmitted. (Forcing everything to be wrapped and forcing blank line removal risks breaking other formatting.) The last time I had a job interview with Google, I said that I wanted to spend my 20% time fixing Google Groups' paragraph handling... and then they didn't hire me. Not sure if this is coincidental or not. :) ChrisA From ian.g.kelly at gmail.com Thu Oct 23 15:39:06 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 23 Oct 2014 13:39:06 -0600 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On Thu, Oct 23, 2014 at 11:07 AM, Seymore4Head wrote: > BTW I forgot to add that example 2 and 3 don't seem to be too useful > in Python 3, but they are in Python 2. I don't understand how the > Python 3 is an improved version. In Python 2, range returns a list containing all the requested elements. This is simple to work with but often not desirable, because it forces the entire sequence to be loaded into memory at once. Large ranges may cause excessive memory use and related slowdowns, while very large ranges may not even be usable. In Python 3, range returns a compact object that knows what elements it contains and can iterate over them (which is the most common use of ranges by far), but without needing to load them all into memory at once. While iterating, only the current element needs to exist in memory. You can still get the range as a list if you want it, by calling list(range(10)), but it doesn't force you to create a list, which makes it more versatile than the Python 2 construct. The more specialized data structure used in Python 3 also allows for certain optimizations, for example membership testing. In Python 2, if you do the test "97 in range(100)", it has to construct a 100-element list and then iterate over 97 of the elements before discovering that the list does in fact contain the number 97. The Python 3 range object knows what the bounds of the range are, so all it has to do is check that 0 <= 97 < 100 to know that the number 97 is included in the range. From Seymore4Head at Hotmail.invalid Thu Oct 23 16:15:19 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 16:15:19 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Thu, 23 Oct 2014 13:39:06 -0600, Ian Kelly wrote: >On Thu, Oct 23, 2014 at 11:07 AM, Seymore4Head > wrote: >> BTW I forgot to add that example 2 and 3 don't seem to be too useful >> in Python 3, but they are in Python 2. I don't understand how the >> Python 3 is an improved version. > >In Python 2, range returns a list containing all the requested >elements. This is simple to work with but often not desirable, because >it forces the entire sequence to be loaded into memory at once. Large >ranges may cause excessive memory use and related slowdowns, while >very large ranges may not even be usable. > >In Python 3, range returns a compact object that knows what elements >it contains and can iterate over them (which is the most common use of >ranges by far), but without needing to load them all into memory at >once. While iterating, only the current element needs to exist in >memory. You can still get the range as a list if you want it, by >calling list(range(10)), but it doesn't force you to create a list, >which makes it more versatile than the Python 2 construct. > >The more specialized data structure used in Python 3 also allows for >certain optimizations, for example membership testing. In Python 2, if >you do the test "97 in range(100)", it has to construct a 100-element >list and then iterate over 97 of the elements before discovering that >the list does in fact contain the number 97. The Python 3 range object >knows what the bounds of the range are, so all it has to do is check >that 0 <= 97 < 100 to know that the number 97 is included in the >range. I agree that does seem improved. Thanks From Seymore4Head at Hotmail.invalid Thu Oct 23 16:44:01 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 23 Oct 2014 16:44:01 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Thu, 23 Oct 2014 13:39:06 -0600, Ian Kelly wrote: >On Thu, Oct 23, 2014 at 11:07 AM, Seymore4Head > wrote: >> BTW I forgot to add that example 2 and 3 don't seem to be too useful >> in Python 3, but they are in Python 2. I don't understand how the >> Python 3 is an improved version. > >In Python 2, range returns a list containing all the requested >elements. This is simple to work with but often not desirable, because >it forces the entire sequence to be loaded into memory at once. Large >ranges may cause excessive memory use and related slowdowns, while >very large ranges may not even be usable. > >In Python 3, range returns a compact object that knows what elements >it contains and can iterate over them (which is the most common use of >ranges by far), but without needing to load them all into memory at >once. While iterating, only the current element needs to exist in >memory. You can still get the range as a list if you want it, by >calling list(range(10)), but it doesn't force you to create a list, >which makes it more versatile than the Python 2 construct. > >The more specialized data structure used in Python 3 also allows for >certain optimizations, for example membership testing. In Python 2, if >you do the test "97 in range(100)", it has to construct a 100-element >list and then iterate over 97 of the elements before discovering that >the list does in fact contain the number 97. The Python 3 range object >knows what the bounds of the range are, so all it has to do is check >that 0 <= 97 < 100 to know that the number 97 is included in the >range. I tried to make range(10) work in Python 3 by: if int(y) in range(10): name.append(str(y)) It doesn't. def nametonumber(name): lst=[] for y in (name): y.lower() if int(y) in range(10): name.append(str(y)) if y in " -()": name.append(y) if y in "abc": name.append("2") if y in "def": name.append("3") if y in "ghi": name.append("4") if y in "jkl": name.append("5") if y in "mno": name.append("6") if y in "pqrs": name.append("7") if y in "tuv": name.append("8") if y in "wxyz": name.append("9") number="".join(str(e) for e in name) return (number) a="1-800-getcharter" print (nametonumber(a))#1800 438 2427 837 a="1-800-leo laporte" print (nametonumber(a)) a="1 800 callaprogrammer" print (nametonumber(a)) From python at mrabarnett.plus.com Thu Oct 23 17:03:23 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 23 Oct 2014 22:03:23 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: <54496D1B.5000904@mrabarnett.plus.com> On 2014-10-23 21:44, Seymore4Head wrote: [snip] > > I tried to make range(10) work in Python 3 by: > if int(y) in range(10): > name.append(str(y)) > > It doesn't. > You didn't say what happened when you tried, but I can guess. When given, say, "g", it complains that it's not valid. Well, "g" isn't a valid digit, so no surprise there! > def nametonumber(name): > lst=[] > for y in (name): > y.lower() The .lower method _returns_ its result, which is just discarded. What you need is: y = y.lower() > if int(y) in range(10): Non-digits don't have a numeric value, so that can fail. > name.append(str(y)) y is already a string, so str(y) is pointless. > if y in " -()": > name.append(y) > if y in "abc": > name.append("2") > if y in "def": > name.append("3") > if y in "ghi": > name.append("4") > if y in "jkl": > name.append("5") > if y in "mno": > name.append("6") > if y in "pqrs": > name.append("7") > if y in "tuv": > name.append("8") > if y in "wxyz": > name.append("9") > number="".join(str(e) for e in name) The elements of the list name are already strings. > return (number) > a="1-800-getcharter" > print (nametonumber(a))#1800 438 2427 837 > a="1-800-leo laporte" > print (nametonumber(a)) > a="1 800 callaprogrammer" > print (nametonumber(a)) > From sohcahtoa82 at gmail.com Thu Oct 23 17:11:53 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Thu, 23 Oct 2014 14:11:53 -0700 (PDT) Subject: FYI: Micro Python running on kickstarter pyBoard project, now shipping In-Reply-To: <25b4884f-a3f9-436d-8d7d-f49f83c3e544@googlegroups.com> References: <25b4884f-a3f9-436d-8d7d-f49f83c3e544@googlegroups.com> Message-ID: On Thursday, October 23, 2014 10:07:26 AM UTC-7, jkn wrote: > Hi all > I haven't heard in mentioned here, but since I saw one of the boards today thought I'd pass on the news: > > The Kickstarter 'MicroPython' project, which has a tiny 'pyboard' (only a couple of sq.inches in size) with a processor running 'a complete re-write of the Python (version 3.4) programming language so that it fits and runs on a microcontroller' is now shipping. > > https://micropython.org/ > > Looks nice; I have no connection but will be getting one myself to play with... > > Cheers > J^n Is there any particular reason to get one of these when I can get a Raspberry Pi which is faster, has more memory, and a bundle of other features? I mean, the idea seems cool and all, but I'm trying to understand why I would want to spend the ~$45 on something like that when a ~$35 Raspberry Pi will do everything and more, and do it faster. From travisgriggs at gmail.com Thu Oct 23 17:50:49 2014 From: travisgriggs at gmail.com (Travis Griggs) Date: Thu, 23 Oct 2014 14:50:49 -0700 Subject: FYI: Micro Python running on kickstarter pyBoard project, now shipping In-Reply-To: References: <25b4884f-a3f9-436d-8d7d-f49f83c3e544@googlegroups.com> Message-ID: <88F8D6C4-B7EC-4FD8-9F29-AB800489E956@gmail.com> > On Oct 23, 2014, at 2:11 PM, sohcahtoa82 at gmail.com wrote: > > On Thursday, October 23, 2014 10:07:26 AM UTC-7, jkn wrote: >> Hi all >> I haven't heard in mentioned here, but since I saw one of the boards today thought I'd pass on the news: >> >> The Kickstarter 'MicroPython' project, which has a tiny 'pyboard' (only a couple of sq.inches in size) with a processor running 'a complete re-write of the Python (version 3.4) programming language so that it fits and runs on a microcontroller' is now shipping. >> >> https://micropython.org/ >> >> Looks nice; I have no connection but will be getting one myself to play with... >> >> Cheers >> J^n > > > Is there any particular reason to get one of these when I can get a Raspberry Pi which is faster, has more memory, and a bundle of other features? > > I mean, the idea seems cool and all, but I'm trying to understand why I would want to spend the ~$45 on something like that when a ~$35 Raspberry Pi will do everything and more, and do it faster. Power Consumption. I don?t know (looked quick, but didn?t find anything fast enough) the exact numbers, but the Pi is meant to be plugged in to something, or chew through batteries quickly. If your IoT device fits in that space and you need all that periphery, that?s great. The Pyboard is running a STM32F405RG (low power contex M4). So I?m betting various children of mine, that it can go a whole lot longer on the same bit of power. Coin cell operation for long periods is probable. I think you look at the $45 as a development board. The site says you can get access to just about everything, so there?s nothing to keep you from prototyping your killer pythonic IoT gadget with these, then doing your own tiny board, populating them with the same chip that you can get from DigiKey for $7 a piece in quantity. Can?t really do that with the Pi. From steve+comp.lang.python at pearwood.info Thu Oct 23 20:42:47 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 24 Oct 2014 11:42:47 +1100 Subject: Truthiness References: <61f0b04c-b827-4c03-b55d-4d5bd85b56f6@googlegroups.com> Message-ID: <5449a089$0$12988$c3e8da3$5496439d@news.astraweb.com> Ian Kelly wrote: > No, 3 is merely true, not True. True is just the name of a particular > singleton object that is also true. Sometimes I distinguish between "true" and "True", where True is the canonical boolean true object, but I prefer to refer to "true-like", "true-ish", or "truthy" objects as a shorthand for "evaluates the same as True in a boolean context" Likewise for "false-like, false-ish, falsey" for objects which evaluate the same as False in a boolean context. It should also be pointed out that, for built-ins and the standard library at least, a good distinction to make is that representations of Nothing (e.g. None, empty string, empty list, zero, empty set, etc.) are falsey, while representations of Something (e.g. non-empty strings, non-empty lists, numbers other than zero, non-empty sets, etc.) are truthy. -- Steven From orgnut at yahoo.com Thu Oct 23 22:13:53 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Thu, 23 Oct 2014 19:13:53 -0700 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 10/23/2014 01:44 PM, Seymore4Head wrote: > I tried to make range(10) work in Python 3 by: > if int(y) in range(10): > name.append(str(y)) > > It doesn't. > That's true, it doesn't. However, did you actually READ the error message it gives? It has NOTHING to do with range(). BTW, did you notice that I cut out most of the quote of your post? I do that because the parts I cut out are not relevant to what I'm referring to. PLEASE, try that in your posts -- that will make them much less annoying to the other people here. Quote enough to maintain context, but more is rarely necessary. Also as others here have already pointed out, if you are replying to different parts of a post, use an interleaved style: [Your reply] [Another reply] References: Message-ID: On 10/23/2014 3:39 PM, Ian Kelly wrote: > On Thu, Oct 23, 2014 at 11:07 AM, Seymore4Head > wrote: >> BTW I forgot to add that example 2 and 3 don't seem to be too useful >> in Python 3, but they are in Python 2. I don't understand how the >> Python 3 is an improved version. > > In Python 2, range returns a list containing all the requested > elements. This is simple to work with but often not desirable, because > it forces the entire sequence to be loaded into memory at once. Large > ranges may cause excessive memory use and related slowdowns, while > very large ranges may not even be usable. > > In Python 3, range returns a compact object that knows what elements > it contains and can iterate over them (which is the most common use of > ranges by far), but without needing to load them all into memory at > once. While iterating, only the current element needs to exist in > memory. You can still get the range as a list if you want it, by > calling list(range(10)), but it doesn't force you to create a list, > which makes it more versatile than the Python 2 construct. > > The more specialized data structure used in Python 3 also allows for > certain optimizations, for example membership testing. In Python 2, if > you do the test "97 in range(100)", it has to construct a 100-element > list and then iterate over 97 of the elements before discovering that > the list does in fact contain the number 97. The Python 3 range object > knows what the bounds of the range are, so all it has to do is check > that 0 <= 97 < 100 to know that the number 97 is included in the > range. Example that works 'instantly' in 3.x, but would be slightly insane in 2.x, even if you have enough memory for it to work on a 64 bit build. >>> r =range(0, 1000000000000000, 999937) >>> 3428761974385 in r False >>> 3428761974386 in r True -- Terry Jan Reedy From rosuav at gmail.com Thu Oct 23 23:32:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 24 Oct 2014 14:32:18 +1100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On Fri, Oct 24, 2014 at 2:14 PM, Terry Reedy wrote: > Example that works 'instantly' in 3.x, but would be slightly insane in 2.x, > even if you have enough memory for it to work on a 64 bit build. > >>>> r =range(0, 1000000000000000, 999937) >>>> 3428761974385 in r > False >>>> 3428761974386 in r > True That's over a billion entries. The array of pointers alone would be roughly 4GB on a 32-bit build, so there's no way that'll ever fit... on a 64-bit build, that'll take up 8GBish for the list, plus probably 24 bytes minimum per integer, so even if there's absolutely no heap overhead, you're still looking at 32GB to store that list. Yeeeouch. I think we can drop the "slightly" from your description! For comparison, a 64-bit Python 3 says: >>> sys.getsizeof(range(0, 1000000000000000, 999937)) 48 Thanks, much nicer. ChrisA From rustompmody at gmail.com Fri Oct 24 00:56:31 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 23 Oct 2014 21:56:31 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> On Thursday, October 23, 2014 10:33:57 PM UTC+5:30, Seymore4Head wrote: > On Thu, 23 Oct 2014 15:55:35 +0000 (UTC), Denis McMahon wrote: > > >On Thu, 23 Oct 2014 10:04:56 -0400, Seymore4Head wrote: > > > >> On Thu, 23 Oct 2014 09:15:16 +0000 (UTC), Denis McMahon wrote: > > > >>>Try the following 3 commands at the console: > > > >You obviously didn't, so I'll try again. Try each of the following three > >commands in the python console at the ">>>" prompt. > > > >1) 10 > 10 > > >2) range(10) > range(0, 10) > > >3) str(range(10)) > 'range(0, 10)' > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > > >Show *and* describe the output in each case. Describing the output that > >you see is actually the key here, as it will allow us to assess whether > >you understand what you are actually seeing or not, and if you don't > >understand the output you see in the console, then we need to fix that > >very fundamental and basic issue before moving on to more complex stuff! > > > >> Ok Thanks > > > >You were expected to answer the question in the original. I have now set > >it as a clearer and more specific task. > > > >If you're not going to do these things that are intended to help you > >learn some of the basic features of the language, then I and everyone > >else here that has so far been attempting to help you are wasting our > >time. > > I did try them. I may have missed replying your to your specific > comment, but I tried them. > > BTW str(range (10)) does work with Python 2 which is where I may have > got the idea. I happened to be using Python 3 at the time I tried to > implement it. It is a little confusing jumping back and forth, but > for the moment, I am going to tough it out. > > I do appreciate all the help too. Hi Seymore! Happy to see that you are moving on from "reading much; understanding nothing; thrashing" to "reading a bit; understanding a bit" [And thanks to Denis to getting you out of your confusion-hole] So heres a small additional question set that I promise will more than repay you your time. Better done in python 2. But if you use python3, below replace range(10) with list(range(10)) So now in the python console, please try a. >>> range(10) and b. >>> print (range(10)) And then post back (without consulting google!!)? 1. Are they same or different? 2. If same, how come different expressions are same? 3. If different whats the difference? 4. [Most important]: When would you prefer which? ================= ? Actually its ok to consult google AFTER you try From nomail at invalid.com Fri Oct 24 02:38:12 2014 From: nomail at invalid.com (ast) Date: Fri, 24 Oct 2014 08:38:12 +0200 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: <5449f3d7$0$2061$426a74cc@news.free.fr> > 48K? Luxury! ZX81 had an option for 64K From breamoreboy at yahoo.co.uk Fri Oct 24 03:05:01 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 24 Oct 2014 08:05:01 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 22/10/2014 21:30, Seymore4Head wrote: > def nametonumber(name): > lst=[""] > for x,y in enumerate (name): > lst=lst.append(y) > print (lst) > return (lst) > a=["1-800-getcharter"] > print (nametonumber(a))#18004382427837 > > > The syntax for when to use a () and when to use [] still throws me a > curve. > > For now, I am trying to end up with a list that has each character in > "a" as a single item. > > I get: > None > None > Following on from the numerous responses you've had here, I've no idea if this helps your thought processes but there's only one way for you to find out http://www.greenteapress.com/thinkpython/ :) -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve+comp.lang.python at pearwood.info Fri Oct 24 03:49:47 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 24 Oct 2014 18:49:47 +1100 Subject: When to use assert References: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com> <5447d20c$0$12997$c3e8da3$5496439d@news.astraweb.com> Message-ID: <544a049c$0$13011$c3e8da3$5496439d@news.astraweb.com> Dan Stromberg wrote: > I like to use assertions and "if cond: raise ValueError('foo')" a lot. > > I think Eiffel may be the poster-child for a language with > pre-conditions, post-conditions and assertions. Yes. I don't think Eiffel is the only language with explicit support for testing invariants, but it's probably the best known one. https://archive.eiffel.com/doc/online/eiffel50/intro/language/invitation-07.html Others include Ada2012, Mercury, D, Perl6, Cobra, Clojure, and others. Cobra is especially interesting as the syntax is heavily influenced by Python's. http://cobra-language.com/trac/cobra/wiki/Contracts > I think you're in good company - a lot of developers don't use assertions > much. "You" in this context is Chris Angelico. > I like assertions, because they tend to stop bugs pretty quickly. If > you have 3 functions, one calling another calling another, assertions > in each can keep you from having to backtrack among them when > debugging, instead going directly to the problem's source. Yes, the purpose of assertions is to help errors be discovered as close to the cause as possible, rather than somewhere much later on. Consider: addresses = [get_address(name) for name in database] # ... much later on ... for i, address in enumerate(addresses): if some_condition(): addresses[i] = modify(address) # ... much later on ... for address in list_of_addresses: process_non_empty_address(address) where you can't easily modify or check the get_address() and modify() functions. If you have a failure in process_non_empty_address, due to a violation of the "address must not be empty" invariant, which function is to blame? You could wrap them and find out that way: from somewhere import get_address as _get_addr def get_address(*args, **kwargs): result = _get_addr(*args, **kwargs) if not result: raise RuntimeError("bug in get_address") return result and under some circumstances that's a good strategy, but often you just want to determine which function is violating the constraint, fix that one, and leave the other unmodified. addresses = [get_address(name) for name in database] assert all(address for address in addresses) # ... much later on ... for i, address in enumerate(addresses): if some_condition(): addresses[i] = modify(address) assert addresses[i] will either identify the culprit, or at least prove that neither get_address() nor modify() are to blame. Because you're using an assertion, it's easy to leave the asserts in place forever, and disable them by passing -O to the Python interpreter in production. [Aside: it would be nice if Python did it the other way around, and require a --debugging switch to turn assertions on. Oh well.] >> This is the job of a test suite. > > Test suites are great, and I can't really question your reliance on > them. I love having lots of automated tests. But for the reason I > described above, I still like having lots of assertions. Assertions and test suites are complementary, not in opposition, like belt and braces. Assertions insure that the code branch will be tested if it is ever exercised, something test suites can't in general promise. Here's a toy example: def some_function(value): import random random.seed(value) if random.random() == 0.25000375: assert some_condition else: pass Try writing a unit test that guarantees to test the some_condition branch :-) [Actually, it's not that hard, if you're willing to monkey-patch the random module. But you may have reasons for wanting to avoid such drastic measures.] I don't know what value will cause some_function() to take the some_condition branch, but I know that if it ever takes that branch, the assert will guard it, regardless of whether or not I've written a unit test to cover that situation. >> You don't pepper your code with >> assertions to the effect that "I just pushed something onto my queue, >> it should now have this item in it"; you create a test case for it, >> and verify your function there. In the rest of the code, you trust >> that your test suite passes, and don't waste time with assertions. > > I wouldn't test that a value was added to a queue immediately after > adding it. That's excessive, and may even require an abstraction > violation. > > But if, for example, I have a string with 3 known-good values, I'll > if/elif/elif/else, and make the else raise an AssertionError. The > assertion should never fire, but if the code changes, it could, and if > there's a typo somewhere, it could then too. I like this style: assert x in (a, b, c) if x == a: do_this() elif x == b: do_that() else: assert x == c do_something_else() Why do I prefer that? To defend against future code changes. Defensive programming can defend not only against bugs in the current code, but also bugs in *future* code. Consider this common case: # x is either a or b. if x == a: do_this() elif x == b: do_that() else: # x must be c. do_something_else() Comments lie, and people don't read them. The comment at the top of the suite is already out of date. I'm sure every experienced programmer has seen situations like that -- or even written code like that. What happens when the requirements change and x can also take the value d? With an eye to defensive programming, the first improvement is: # x is a, b or c. if x == a: do_this() elif x == b: do_that() elif x == c: do_something_else() else: # This cannot possibly happen, but just in case it does... raise RuntimeError('an unexpected error occurred') except that still relies on the next maintainer reading the comment. It's vulnerable to somebody "fixing" the code by removing the dead code and the redundant test for x == c. Besides, it's embarrassing to see "an unexpected error occurred" messages in production, and you know you will. A better solution is to use assertions as checked comments. If the requirements change and you forget to update this part of the code, the assertions will fail: assert x in (a, b, c) if x == a: do_this() elif x == b: do_that() else: assert x == c do_something_else() >> Or is that insufficiently paranoid? > > With good tests, you're probably fine. Is it possible to be too paranoid when it comes to tests? :-) -- Steven From info at egenix.com Fri Oct 24 04:08:05 2014 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Fri, 24 Oct 2014 10:08:05 +0200 Subject: ANN: eGenix pyOpenSSL Distribution 0.13.5 Message-ID: <544A08E5.7030407@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.13.5 An easy-to-install and easy-to-use distribution of the pyOpenSSL Python interface for OpenSSL - available for Windows, Mac OS X and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.13.5.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy-to-use installer that includes the most recent OpenSSL library versions in pre-compiled form, making your application independent of OS provided OpenSSL libraries: http://www.egenix.com/products/python/pyOpenSSL/ pyOpenSSL is an open-source Python add-on that allows writing SSL/TLS- aware network applications as well as certificate management tools: https://launchpad.net/pyopenssl/ OpenSSL is an open-source implementation of the SSL/TLS protocol: http://www.openssl.org/ ________________________________________________________________________ NEWS This new release of the eGenix.com pyOpenSSL Distribution updates the included OpenSSL version to the latest OpenSSL 1.0.1h version and adds a few more context options: New in OpenSSL -------------- * Updated included OpenSSL libraries from OpenSSL 1.0.1i to 1.0.1j. See https://www.openssl.org/news/secadv_20141015.txt for a complete list of changes. The following fixes are relevant for pyOpenSSL applications: - CVE-2014-3567: Memory leak in OpenSSL session ticket management. - OpenSSL has added support for TLS_FALLBACK_SCSV to allow applications to block the ability for a MITM attacker to force a protocol downgrade, e.g. to enable a POODLE (CVE-2014-3566) attack by forcing a downgrade to SSLv3. This is enabled automatically for servers. - CVE-2014-3568: OpenSSL configured with "no-ssl3" would still allow a complete SSL 3.0 handshake to run. New in pyOpenSSL ---------------- * Dropped zlib support from OpenSSL builds to more easily prevent the CRIME attack without having to use special SSL context options. * Disabled the SSLv2 support in OpenSSL builds. SSLv2 has long been broken and this simplifies writing secure servers/clients. * Updated the included CA root certificate bundles to Mozilla's 2014-08-26 update. * Improved cipher list in https_client.py example which prefers the newer AES128-GCM and elliptic curve DH over over ciphers. * Added new context flag MODE_SEND_FALLBACK_SCSV. Documented previously undocumented MODE_RELEASE_BUFFERS and removed non-existing MODE_NO_COMPRESSION from the documentation. * Added web installer package to the Python Package Index (PyPI) which simplifies installation. * In addition to the usual ways of installing eGenix pyOpenSSL, we have uploaded a web installer to PyPI, so that it is now also possible to use one of these installation methods on all supported platforms (Windows, Linux, Mac OS X): - easy_install egenix-pyopenssl via PyPI - pip install egenix-pyopenssl via PyPI - egg reference in zc.buildout via PyPI - running "python setup.py install" in the unzipped web installer archive directory The web installer will automatically detect the platform and choose the right binary download package for you. All downloads are verified before installation. * Resolved a problem with a pyOpenSSL test for certificate extensions: OpenSSL 1.0.1i+ wants a signature algorithm to be defined when loading PEM certificates. * Moved eGenix additions to pyOpenSSL to a new extras/ dir in the source distribution. * In previous releases, we also added the OpenSSL version number to the package version. Since this causes very long version numbers, we have dropped the OpenSSL version starting with 0.13.5 and will only increase the main version number from now on. In the future, we plan to switch to a new version scheme that is compatible with our normal version number scheme for products. pyOpenSSL / OpenSSL Binaries Included ------------------------------------- In addition to providing sources, we make binaries available that include both pyOpenSSL and the necessary OpenSSL libraries for all supported platforms: Windows x86 and x64, Linux x86 and x64, Mac OS X PPC, x86 and x64. We've also added egg-file distribution versions of our eGenix.com pyOpenSSL Distribution for Windows, Linux and Mac OS X to the available download options. These make setups using e.g. zc.buildout and other egg-file based installers a lot easier. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. ________________________________________________________________________ MORE INFORMATION For more information about the eGenix pyOpenSSL Distribution, licensing and download instructions, please visit our web-site or write to sales at egenix.com. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Oct 24 2014) >>> Python Projects, Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope/Plone.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::::: Try our mxODBC.Connect Python Database Interface for free ! :::::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From breamoreboy at yahoo.co.uk Fri Oct 24 04:12:28 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 24 Oct 2014 09:12:28 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 24/10/2014 08:05, Mark Lawrence wrote: > On 22/10/2014 21:30, Seymore4Head wrote: >> def nametonumber(name): >> lst=[""] >> for x,y in enumerate (name): >> lst=lst.append(y) >> print (lst) >> return (lst) >> a=["1-800-getcharter"] >> print (nametonumber(a))#18004382427837 >> >> >> The syntax for when to use a () and when to use [] still throws me a >> curve. >> >> For now, I am trying to end up with a list that has each character in >> "a" as a single item. >> >> I get: >> None >> None >> > > Following on from the numerous responses you've had here, I've no idea > if this helps your thought processes but there's only one way for you to > find out http://www.greenteapress.com/thinkpython/ :) > And another http://tinyurl.com/k26vjhr -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rosuav at gmail.com Fri Oct 24 04:18:24 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 24 Oct 2014 19:18:24 +1100 Subject: When to use assert In-Reply-To: <544a049c$0$13011$c3e8da3$5496439d@news.astraweb.com> References: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com> <5447d20c$0$12997$c3e8da3$5496439d@news.astraweb.com> <544a049c$0$13011$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Oct 24, 2014 at 6:49 PM, Steven D'Aprano wrote: > addresses = [get_address(name) for name in database] > assert all(address for address in addresses) > # ... much later on ... > for i, address in enumerate(addresses): > if some_condition(): > addresses[i] = modify(address) > assert addresses[i] > > > will either identify the culprit, or at least prove that neither > get_address() nor modify() are to blame. Because you're using an assertion, > it's easy to leave the asserts in place forever, and disable them by > passing -O to the Python interpreter in production. The first assertion is fine, assuming that the emptiness of your address corresponds to falsiness as defined in Python. (This could be safe to assume, if the address is an object that knows how to boolify itself.) The second assertion then proves that modify() isn't returning nothing, but that might be better done by sticking the assertion into modify itself. And that's what I'm talking about: checking a function's postcondition with an assert implies putting that assertion after every call, and anything that you have to do every time you call a function belongs inside that function. Imagine writing this kind of defensive code, and then having lots of places that call modify()... and missing the assert in some of them. Can you trust what you're getting back? > [Aside: it would be nice if Python did it the other way around, and require > a --debugging switch to turn assertions on. Oh well.] Maybe. But unless someone actually tests that their assertions are being run, there's the risk that they're flying blind and assuming that it's all happening. There'll be all these lovely "checked comments"... or so people think. Nobody ever runs the app with --debugging, so nobody ever sees anything. > Assertions and test suites are complementary, not in opposition, like belt > and braces. Assertions insure that the code branch will be tested if it is > ever exercised, something test suites can't in general promise. Here's a > toy example: > > def some_function(value): > import random > random.seed(value) > if random.random() == 0.25000375: > assert some_condition > else: > pass > > > Try writing a unit test that guarantees to test the some_condition > branch :-) > > [Actually, it's not that hard, if you're willing to monkey-patch the random > module. But you may have reasons for wanting to avoid such drastic > measures.] Easy. You craft a test case that passes the right argument, and then have the test case test itself. You will want to have a script that figures out what seed value to use: def find_seed(value): import random for seed in range(1000000): # Restrict to not-too-many tries random.seed(seed) if random.random() == value: return seed I didn't say it'd be efficient to run, but hey, it's easy. I've no idea how many bits of internal state the default Python RNGs use, but testing a million seeds took a notable amount of time, so I told it to fail after that many. (And I didn't find one that gave that result.) But actually, it would be really simple to monkey-patch. And in any non-toy situation, there's probably something more significant being tested here... unless you really are probing a random number generator or something, in which case you probably know more about its internals. > I like this style: > > assert x in (a, b, c) > if x == a: > do_this() > elif x == b: > do_that() > else: > assert x == c > do_something_else() If all your branches are simple function calls, I'd be happy with a KeyError instead of an AssertionError or RuntimeError. {a:do_this, b:do_that, c:do_something_else}[x]() I was talking to a student this week who had a long if/elif chain that translated keywords into values, something like this: def get_whatever_value(kwd): if kwd == 'value_should_be_50': return 50 elif kwd == 'value_wants_to_be_75': return 75 elif kwd == 'one_hundred': return 100 There was no 'else' clause, so in the event of an incorrect keyword, it would return None. Now, I could have advised adding an "else ValueError" or an assertion, but my preferred technique here is a simple dict lookup. Simpler AND guarantees that all inputs are checked. >>> Or is that insufficiently paranoid? >> >> With good tests, you're probably fine. > > Is it possible to be too paranoid when it comes to tests? Yeah, it is. I said earlier about checking that len() returns an integer. The only way[1] for len(some_object) to return a non-integer is for someone to have shadowed len, and if you're asserting to see if someone's maliciously shadowing builtins, you *really* need a hobby. But hey. Maybe asserting *is* your hobby! ChrisA [1] Cue the response pointing out some way that it'll return something else. I wasn't able to break it, though. From steve+comp.lang.python at pearwood.info Fri Oct 24 04:38:45 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 24 Oct 2014 19:38:45 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> Message-ID: <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> Marko Rauhamaa wrote: > "BartC" : > >>> Ah, but what would >>> >>> x = [f, g][cond]() >>> >>> produce? >> >> It will select f or g (which should refer to functions), and call one of >> those depending on cond. That's not a problem. >> >> The problem is it will still evaluate both f and g, > > That's not really the problem. The problem is in readability. I don't get why that's considered hard to read. We write things like this all the time: item = somelist[index] value = data[key] Presumably people won't have a problem with: values = [f(), g(), h()] value = values[index] (If they do, they're going to have a bad time with Python.) They probably won't even mind if we skip the temporary variable: value = [f(), g(), h()][index] and if they're experienced with languages that treat functions as first-class values, they'll be fine with factoring out the function call: value = [f, g, h][index]() So why is it hard to read when the index is a flag? value = [f, g][cond]() Of course one can write hard-to-read code using any idiom by sheer weight of complexity or obfuscated naming: value = [some_function(arg)[23]['key'] or another_function.method((x + y)/(z-x**(y-4)))* some_list[get_index(a)].spam(eggs=False, tomato='yum'), something.do_this(p|q).get(alpha, beta) ^ aardvark.bobble("string%s" % carrot.gamma(r&s)* (this & that).fetch(83, 36, when=when or "now") ][cond or flag or foo(42)-1 > 17 or bar(b) < thingy(c) or not d] but re-writing that using ternary if operator won't help one iota. I don't see why `[a, b][flag]` is inherently less readable than `b if flag else a`. -- Steven From rosuav at gmail.com Fri Oct 24 04:45:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 24 Oct 2014 19:45:25 +1100 Subject: (test) ? a:b In-Reply-To: <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Oct 24, 2014 at 7:38 PM, Steven D'Aprano wrote: > Of course one can write hard-to-read code using any idiom by sheer weight of > complexity or obfuscated naming: > > value = [some_function(arg)[23]['key'] or > another_function.method((x + y)/(z-x**(y-4)))* > some_list[get_index(a)].spam(eggs=False, tomato='yum'), > something.do_this(p|q).get(alpha, beta) ^ > aardvark.bobble("string%s" % carrot.gamma(r&s)* > (this & that).fetch(83, 36, when=when or "now") > ][cond or flag or foo(42)-1 > 17 or bar(b) < thingy(c) or not d] > I can see where your problem is. It is a cardinal error in readability to have "(x + y)" followed by "z-x". No wonder it's hard to read. ChrisA From marko at pacujo.net Fri Oct 24 05:37:33 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 24 Oct 2014 12:37:33 +0300 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87tx2tvmea.fsf@elektro.pacujo.net> Steven D'Aprano : > So why is it hard to read when the index is a flag? > > value = [f, g][cond]() So, subjectively, which syntax would you prefer: if j < 10: j += 1 else: j = 3 or: j = j + 1 if j < 10 else 3 or: j = (lambda: 3, lambda: j + 1)[j < 10]() Marko From luc2 at nospam.invalid Fri Oct 24 07:39:41 2014 From: luc2 at nospam.invalid (luc2) Date: 24 Oct 2014 11:39:41 GMT Subject: setuptools + data_files = 2 References: <5447fac2$0$2384$426a74cc@news.free.fr> <7ec70158-2eab-4590-93a6-784ffc8538e4@googlegroups.com> Message-ID: <544a3a7d$0$2122$426a74cc@news.free.fr> On 2014-10-23, Simon Kennedy wrote: > If you're creating an sdist then you'll need to create a MANIFEST.in > file in the same folder as setup.py with the following contents > > include share/test_file.txt > > If you're creating a bdist (egg or wheel) the parameter name you need > is > > package_data={'share': [share/test_file.txt]}, thanks man. From steve+comp.lang.python at pearwood.info Fri Oct 24 09:07:02 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 25 Oct 2014 00:07:02 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <87tx2tvmea.fsf@elektro.pacujo.net> Message-ID: <544a4ef7$0$12984$c3e8da3$5496439d@news.astraweb.com> Marko Rauhamaa wrote: > Steven D'Aprano : > >> So why is it hard to read when the index is a flag? >> >> value = [f, g][cond]() > > So, subjectively, which syntax would you prefer: Depends on what else the code is doing. But my personal preference is a red herring: you didn't say that you "liked" or "preferred" one version over the other, you said that the problem with the [f, g][cond] idiom is readability, implying that it is hard to read. I'm not asking for your personal preference, I'm asking for justification for your suggestion that it is hard to read. > if j < 10: > j += 1 > else: > j = 3 > > or: > > j = j + 1 if j < 10 else 3 > > or: > > j = (lambda: 3, lambda: j + 1)[j < 10]() Certainly not the third one. That's needlessly obfuscated for the sake of premature optimization. This version is much better, and probably not only simpler and easier to read but probably more efficient too: j = (3, j + 1)[j < 10] -- Steven From Seymore4Head at Hotmail.invalid Fri Oct 24 10:38:31 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 10:38:31 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Thu, 23 Oct 2014 21:56:31 -0700 (PDT), Rustom Mody wrote: >On Thursday, October 23, 2014 10:33:57 PM UTC+5:30, Seymore4Head wrote: >> On Thu, 23 Oct 2014 15:55:35 +0000 (UTC), Denis McMahon wrote: >> >> >On Thu, 23 Oct 2014 10:04:56 -0400, Seymore4Head wrote: >> > >> >> On Thu, 23 Oct 2014 09:15:16 +0000 (UTC), Denis McMahon wrote: >> > >> >>>Try the following 3 commands at the console: >> > >> >You obviously didn't, so I'll try again. Try each of the following three >> >commands in the python console at the ">>>" prompt. >> > >> >1) 10 >> 10 >> >> >2) range(10) >> range(0, 10) >> >> >3) str(range(10)) >> 'range(0, 10)' >> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >> > >> >Show *and* describe the output in each case. Describing the output that >> >you see is actually the key here, as it will allow us to assess whether >> >you understand what you are actually seeing or not, and if you don't >> >understand the output you see in the console, then we need to fix that >> >very fundamental and basic issue before moving on to more complex stuff! >> > >> >> Ok Thanks >> > >> >You were expected to answer the question in the original. I have now set >> >it as a clearer and more specific task. >> > >> >If you're not going to do these things that are intended to help you >> >learn some of the basic features of the language, then I and everyone >> >else here that has so far been attempting to help you are wasting our >> >time. >> >> I did try them. I may have missed replying your to your specific >> comment, but I tried them. >> >> BTW str(range (10)) does work with Python 2 which is where I may have >> got the idea. I happened to be using Python 3 at the time I tried to >> implement it. It is a little confusing jumping back and forth, but >> for the moment, I am going to tough it out. >> >> I do appreciate all the help too. > >Hi Seymore! > >Happy to see that you are moving on from >"reading much; understanding nothing; thrashing" > >to > >"reading a bit; understanding a bit" >[And thanks to Denis to getting you out of your confusion-hole] > >So heres a small additional question set that I promise will more than repay >you your time. > >Better done in python 2. But if you use python3, below replace >range(10) >with >list(range(10)) > >So now in the python console, please try > >a. >>>> range(10) > >and > >b. >>>> print (range(10)) > >And then post back (without consulting google!!)? > >1. Are they same or different? > >2. If same, how come different expressions are same? > >3. If different whats the difference? > >4. [Most important]: When would you prefer which? > >================= >? Actually its ok to consult google AFTER you try I do get the difference. I don't actually use Python 2. I use CodeSkulptor. I do have Python 3 installed. Actually I have Python 2 installed but IDLE defaults to Python 3. So it is a pain to actually load Python 2. Range(10) stores the min max values and loads each number in between when needed. Ian explained that very clearly. I tried list(range(10) I thought that would work in Python 3. It didn't. I spent quite a bit of time last night trying to come up with the right combination of str and int commands to make range(10) work with my simple example. It didn't. I am pretty frustrated. I am just skipping that little bit of code for the moment. Thanks everyone for your suggestions. From Seymore4Head at Hotmail.invalid Fri Oct 24 10:47:16 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 10:47:16 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Fri, 24 Oct 2014 08:05:01 +0100, Mark Lawrence wrote: >On 22/10/2014 21:30, Seymore4Head wrote: >> def nametonumber(name): >> lst=[""] >> for x,y in enumerate (name): >> lst=lst.append(y) >> print (lst) >> return (lst) >> a=["1-800-getcharter"] >> print (nametonumber(a))#18004382427837 >> >> >> The syntax for when to use a () and when to use [] still throws me a >> curve. >> >> For now, I am trying to end up with a list that has each character in >> "a" as a single item. >> >> I get: >> None >> None >> > >Following on from the numerous responses you've had here, I've no idea >if this helps your thought processes but there's only one way for you to >find out http://www.greenteapress.com/thinkpython/ :) I have at least 10 ebooks. I will get around to reading them soon. http://i.imgur.com/rpOcKP8.jpg Thanks From rosuav at gmail.com Fri Oct 24 10:51:41 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 25 Oct 2014 01:51:41 +1100 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Sat, Oct 25, 2014 at 1:38 AM, Seymore4Head wrote: > I tried list(range(10) I thought that would work in Python 3. It > didn't. This is your problem: You say "it didn't work". That is almost *never* the right thing to say or to think. What happened when you tried that? Did you get a SyntaxError because of the omitted close parenthesis? Did the interpreter prompt for more input? Did a velociraptor come out of nowhere and try to kill you [1]? When you come back to python-list, you should say exactly what you did and exactly what happened, not "I tried X and it didn't work". Copy and paste from your interactive session - do NOT retype, because you introduce new errors. It's very hard to help you when you don't explain what you're doing, and just keep on telling us how frustrated you are. ChrisA [1] http://xkcd.com/292/ From Seymore4Head at Hotmail.invalid Fri Oct 24 10:48:26 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 10:48:26 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Fri, 24 Oct 2014 09:12:28 +0100, Mark Lawrence wrote: >On 24/10/2014 08:05, Mark Lawrence wrote: >> On 22/10/2014 21:30, Seymore4Head wrote: >>> def nametonumber(name): >>> lst=[""] >>> for x,y in enumerate (name): >>> lst=lst.append(y) >>> print (lst) >>> return (lst) >>> a=["1-800-getcharter"] >>> print (nametonumber(a))#18004382427837 >>> >>> >>> The syntax for when to use a () and when to use [] still throws me a >>> curve. >>> >>> For now, I am trying to end up with a list that has each character in >>> "a" as a single item. >>> >>> I get: >>> None >>> None >>> >> >> Following on from the numerous responses you've had here, I've no idea >> if this helps your thought processes but there's only one way for you to >> find out http://www.greenteapress.com/thinkpython/ :) >> > >And another http://tinyurl.com/k26vjhr Google. I have heard of that. :) From Seymore4Head at Hotmail.invalid Fri Oct 24 11:04:31 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 11:04:31 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Sat, 25 Oct 2014 01:51:41 +1100, Chris Angelico wrote: >On Sat, Oct 25, 2014 at 1:38 AM, Seymore4Head > wrote: >> I tried list(range(10) I thought that would work in Python 3. It >> didn't. > >This is your problem: You say "it didn't work". That is almost *never* >the right thing to say or to think. What happened when you tried that? >Did you get a SyntaxError because of the omitted close parenthesis? >Did the interpreter prompt for more input? Did a velociraptor come out >of nowhere and try to kill you [1]? > I understand that it makes it easier for you if I can describe better the error I get, but by the time I ask for help here I have tried many different things to get the error to go away. I will try in the future to do better at this. For now, I am just putting that exercise behind me. I do try to find out how to do things before asking first. I tried so many things last night, I had to go back to an old message to get code that worked again. Thanks >When you come back to python-list, you should say exactly what you did >and exactly what happened, not "I tried X and it didn't work". Copy >and paste from your interactive session - do NOT retype, because you >introduce new errors. It's very hard to help you when you don't >explain what you're doing, and just keep on telling us how frustrated >you are. > >ChrisA > >[1] http://xkcd.com/292/ From rosuav at gmail.com Fri Oct 24 11:13:34 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 25 Oct 2014 02:13:34 +1100 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Sat, Oct 25, 2014 at 2:04 AM, Seymore4Head wrote: > I understand that it makes it easier for you if I can describe better > the error I get, but by the time I ask for help here I have tried many > different things to get the error to go away. That's part of the problem. You let yourself get frustrated and confused, and you still have no idea what you're doing. Ask sooner, if you have to; or develop the discipline to keep track of what you do and what happens. But regardless of what actually happens, "it didn't work" is not a helpful thing to say. Trust me, making it easier for us will make everything easier for you too. Even if we were to never answer a single question of yours ever again, learning to read error messages will benefit you more than you can imagine. ChrisA From rustompmody at gmail.com Fri Oct 24 11:56:31 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 08:56:31 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> On Friday, October 24, 2014 8:11:12 PM UTC+5:30, Seymore4Head wrote: > On Thu, 23 Oct 2014 21:56:31 -0700 (PDT), Rustom Mody wrote: > > >On Thursday, October 23, 2014 10:33:57 PM UTC+5:30, Seymore4Head wrote: > >> On Thu, 23 Oct 2014 15:55:35 +0000 (UTC), Denis McMahon wrote: > >> > >> >On Thu, 23 Oct 2014 10:04:56 -0400, Seymore4Head wrote: > >> > > >> >> On Thu, 23 Oct 2014 09:15:16 +0000 (UTC), Denis McMahon wrote: > >> > > >> >>>Try the following 3 commands at the console: > >> > > >> >You obviously didn't, so I'll try again. Try each of the following three > >> >commands in the python console at the ">>>" prompt. > >> > > >> >1) 10 > >> 10 > >> > >> >2) range(10) > >> range(0, 10) > >> > >> >3) str(range(10)) > >> 'range(0, 10)' > >> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > >> > > >> >Show *and* describe the output in each case. Describing the output that > >> >you see is actually the key here, as it will allow us to assess whether > >> >you understand what you are actually seeing or not, and if you don't > >> >understand the output you see in the console, then we need to fix that > >> >very fundamental and basic issue before moving on to more complex stuff! > >> > > >> >> Ok Thanks > >> > > >> >You were expected to answer the question in the original. I have now set > >> >it as a clearer and more specific task. > >> > > >> >If you're not going to do these things that are intended to help you > >> >learn some of the basic features of the language, then I and everyone > >> >else here that has so far been attempting to help you are wasting our > >> >time. > >> > >> I did try them. I may have missed replying your to your specific > >> comment, but I tried them. > >> > >> BTW str(range (10)) does work with Python 2 which is where I may have > >> got the idea. I happened to be using Python 3 at the time I tried to > >> implement it. It is a little confusing jumping back and forth, but > >> for the moment, I am going to tough it out. > >> > >> I do appreciate all the help too. > > > >Hi Seymore! > > > >Happy to see that you are moving on from > >"reading much; understanding nothing; thrashing" > > > >to > > > >"reading a bit; understanding a bit" > >[And thanks to Denis to getting you out of your confusion-hole] > > > >So heres a small additional question set that I promise will more than repay > >you your time. > > > >Better done in python 2. But if you use python3, below replace > >range(10) > >with > >list(range(10)) > > I tried list(range(10) I thought that would work in Python 3. It > didn't. I spent quite a bit of time last night trying to come up with > the right combination of str and int commands to make range(10) work > with my simple example. It didn't. I am pretty frustrated. I am > just skipping that little bit of code for the moment. I asked you to try list(range(10)) Did you try EXACTLY (cut-paste) that? You are claiming to have tried list(range(10) Thats one closing parenthesis less The interaction with your version would go something like this: [Two versions The KeyboardInterrupt comes from giving a control-C Dunno what happens in codeskulptor ] >>> list(range(10) ... ... ... ... ) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> list(range(10) ... KeyboardInterrupt > > Thanks everyone for your suggestions. 1. You are reading too much 2. Trying tooooo hard Think of riding a bicycle. Cant do it by reading many books on cycling -- thats 1. Nor by holding the handle so hard you tremble -- thats 2. Just relax a bit... And take small steps Chill... as Chris joked, no monster in the computer (or on this list!) > Range(10) stores the min max values and loads each number in between > when needed. It loads?? As in 'load-up-a-van'?? When you see: >>> 10 10 1. Does someone (a clerk maybe) in the computer count to 10? 2. Or do you, seeing that interaction, count to 10? [If you do, replace the 10 by 1000] 3. Or do you, remember what it means to count to 10 without having to do it? Now go back to your statement about 'loading' and find a better verb From pecore at pascolo.net Fri Oct 24 11:56:40 2014 From: pecore at pascolo.net (giacomo boffi) Date: Fri, 24 Oct 2014 17:56:40 +0200 Subject: I am out of trial and error again Lists References: <54484635$0$12992$c3e8da3$5496439d@news.astraweb.com> <8nmg4aljnmigjtjk70cc4g6dmacca6negc@4ax.com> <87y4s6g889.fsf@pascolo.net> Message-ID: <87vbn9bgw7.fsf@pascolo.net> ERRATA CORRIGE: > many different circumstances, by the very, very helpful folks of clp. many different circumstances, by the very, very helpful folks of clpy -- sapete contare fino a venticinque? Olimpia Milano Jugoplastika Split Partizan Beograd Roberto Premier Duska Ivanovic Zarko Paspalj From ian.g.kelly at gmail.com Fri Oct 24 12:35:41 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 24 Oct 2014 10:35:41 -0600 Subject: I am out of trial and error again Lists In-Reply-To: <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> Message-ID: On Fri, Oct 24, 2014 at 9:56 AM, Rustom Mody wrote: >> Range(10) stores the min max values and loads each number in between >> when needed. > > It loads?? As in 'load-up-a-van'?? As in loads into memory. > When you see: > >>>> 10 > 10 > > 1. Does someone (a clerk maybe) in the computer count to 10? > 2. Or do you, seeing that interaction, count to 10? > [If you do, replace the 10 by 1000] > 3. Or do you, remember what it means to count to 10 without having to do it? I don't understand why you think any of these are implied by the word "load". > Now go back to your statement about 'loading' and find a better verb I presume he used "load" because that was the word I used in my explanatory post about the difference between range in Python 2 and Python 3 yesterday. From Seymore4Head at Hotmail.invalid Fri Oct 24 12:37:32 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 12:37:32 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 08:56:31 -0700 (PDT), Rustom Mody wrote: >On Friday, October 24, 2014 8:11:12 PM UTC+5:30, Seymore4Head wrote: >> On Thu, 23 Oct 2014 21:56:31 -0700 (PDT), Rustom Mody wrote: >> >> >On Thursday, October 23, 2014 10:33:57 PM UTC+5:30, Seymore4Head wrote: >> >> On Thu, 23 Oct 2014 15:55:35 +0000 (UTC), Denis McMahon wrote: >> >> >> >> >On Thu, 23 Oct 2014 10:04:56 -0400, Seymore4Head wrote: >> >> > >> >> >> On Thu, 23 Oct 2014 09:15:16 +0000 (UTC), Denis McMahon wrote: >> >> > >> >> >>>Try the following 3 commands at the console: >> >> > >> >> >You obviously didn't, so I'll try again. Try each of the following three >> >> >commands in the python console at the ">>>" prompt. >> >> > >> >> >1) 10 >> >> 10 >> >> >> >> >2) range(10) >> >> range(0, 10) >> >> >> >> >3) str(range(10)) >> >> 'range(0, 10)' >> >> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >> >> > >> >> >Show *and* describe the output in each case. Describing the output that >> >> >you see is actually the key here, as it will allow us to assess whether >> >> >you understand what you are actually seeing or not, and if you don't >> >> >understand the output you see in the console, then we need to fix that >> >> >very fundamental and basic issue before moving on to more complex stuff! >> >> > >> >> >> Ok Thanks >> >> > >> >> >You were expected to answer the question in the original. I have now set >> >> >it as a clearer and more specific task. >> >> > >> >> >If you're not going to do these things that are intended to help you >> >> >learn some of the basic features of the language, then I and everyone >> >> >else here that has so far been attempting to help you are wasting our >> >> >time. >> >> >> >> I did try them. I may have missed replying your to your specific >> >> comment, but I tried them. >> >> >> >> BTW str(range (10)) does work with Python 2 which is where I may have >> >> got the idea. I happened to be using Python 3 at the time I tried to >> >> implement it. It is a little confusing jumping back and forth, but >> >> for the moment, I am going to tough it out. >> >> >> >> I do appreciate all the help too. >> > >> >Hi Seymore! >> > >> >Happy to see that you are moving on from >> >"reading much; understanding nothing; thrashing" >> > >> >to >> > >> >"reading a bit; understanding a bit" >> >[And thanks to Denis to getting you out of your confusion-hole] >> > >> >So heres a small additional question set that I promise will more than repay >> >you your time. >> > >> >Better done in python 2. But if you use python3, below replace >> >range(10) >> >with >> >list(range(10)) > > > >> >> I tried list(range(10) I thought that would work in Python 3. It >> didn't. I spent quite a bit of time last night trying to come up with >> the right combination of str and int commands to make range(10) work >> with my simple example. It didn't. I am pretty frustrated. I am >> just skipping that little bit of code for the moment. > >I asked you to try >list(range(10)) > >Did you try EXACTLY (cut-paste) that? > >You are claiming to have tried >list(range(10) > >Thats one closing parenthesis less > >The interaction with your version would go something like this: >[Two versions >The KeyboardInterrupt comes from giving a control-C >Dunno what happens in codeskulptor >] > >>>> list(range(10) >... >... >... >... ) >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>> list(range(10) >... >KeyboardInterrupt > > >> >> Thanks everyone for your suggestions. > >1. You are reading too much >2. Trying tooooo hard > >Think of riding a bicycle. >Cant do it by reading many books on cycling -- thats 1. >Nor by holding the handle so hard you tremble -- thats 2. > >Just relax a bit... >And take small steps > >Chill... as Chris joked, no monster in the computer (or on this list!) > > >> Range(10) stores the min max values and loads each number in between >> when needed. > >It loads?? As in 'load-up-a-van'?? > >When you see: > >>>> 10 >10 > >1. Does someone (a clerk maybe) in the computer count to 10? >2. Or do you, seeing that interaction, count to 10? > [If you do, replace the 10 by 1000] >3. Or do you, remember what it means to count to 10 without having to do it? > >Now go back to your statement about 'loading' and find a better verb If I could explain to you why something doesn't work then I could fix it myself. I don't understand why it doesn't work. The best I can do is repost the code. When I use list(range(10)) I get: Traceback (most recent call last): File "C:/Functions/name to number digit.py", line 37, in print (nametonumber(a))#1800 438 2427 837 File "C:/Functions/name to number digit.py", line 10, in nametonumber if y in lst(range(1,10)): TypeError: 'list' object is not callable All the lines I have commented out work. Trying to use list(range(10)) doesn't. (Python 3) http://i.imgur.com/LtiCyZS.jpg It doesn't work. It's broke. :) I don't know what else to say. import string def nametonumber(name): lst=[] nx=[] digit=[] digit="".join(str(i) for i in range(10)) for x in name: lst.append(x) for y in (lst): if y in lst(range(1,10)): #if y in "1234567890": #if y.isdigit(): #if y in digit: #if y in string.digits: nx.append(y) if y in " -()": nx.append(y) if y in "abc": nx.append("2") if y in "def": nx.append("3") if y in "ghi": nx.append("4") if y in "jkl": nx.append("5") if y in "mno": nx.append("6") if y in "pqrs": nx.append("7") if y in "tuv": nx.append("8") if y in "wxyz": nx.append("9") number="".join(e for e in nx) return number a="1-800-getcharter" print (nametonumber(a))#1800 438 2427 837 a="1-800-leo laporte" print (nametonumber(a)) a="1 800 dialaho" print (nametonumber(a)) BTW thanks again for all the help From fomcl at yahoo.com Fri Oct 24 12:42:32 2014 From: fomcl at yahoo.com (Albert-Jan Roskam) Date: Fri, 24 Oct 2014 09:42:32 -0700 Subject: I am out of trial and error again Lists Message-ID: <1414168952.7511.BPMail_high_carrier@web163806.mail.gq1.yahoo.com> ----------------------------- On Fri, Oct 24, 2014 5:56 PM CEST Rustom Mody wrote: >On Friday, October 24, 2014 8:11:12 PM UTC+5:30, Seymore4Head wrote: >> On Thu, 23 Oct 2014 21:56:31 -0700 (PDT), Rustom Mody wrote: >> >> >On Thursday, October 23, 2014 10:33:57 PM UTC+5:30, Seymore4Head wrote: >> > On Thu, 23 Oct 2014 15:55:35 +0000 (UTC), Denis McMahon wrote: >> > >> > >On Thu, 23 Oct 2014 10:04:56 -0400, Seymore4Head wrote: >> > > >> > > On Thu, 23 Oct 2014 09:15:16 +0000 (UTC), Denis McMahon wrote: >> > > >> > >>Try the following 3 commands at the console: >> > > >> > >You obviously didn't, so I'll try again. Try each of the following three >> > >commands in the python console at the ">>" prompt. >> > > >> > >1) 10 >> > 10 >> > >> > >2) range(10) >> > range(0, 10) >> > >> > >3) str(range(10)) >> > 'range(0, 10)' >> > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >> > > >> > >Show *and* describe the output in each case. Describing the output that >> > >you see is actually the key here, as it will allow us to assess whether >> > >you understand what you are actually seeing or not, and if you don't >> > >understand the output you see in the console, then we need to fix that >> > >very fundamental and basic issue before moving on to more complex stuff! >> > > >> > > Ok Thanks >> > > >> > >You were expected to answer the question in the original. I have now set >> > >it as a clearer and more specific task. >> > > >> > >If you're not going to do these things that are intended to help you >> > >learn some of the basic features of the language, then I and everyone >> > >else here that has so far been attempting to help you are wasting our >> > >time. >> > >> > I did try them. I may have missed replying your to your specific >> > comment, but I tried them. >> > >> > BTW str(range (10)) does work with Python 2 which is where I may have >> > got the idea. I happened to be using Python 3 at the time I tried to >> > implement it. It is a little confusing jumping back and forth, but >> > for the moment, I am going to tough it out. u0_a100 at condor_umts:/ $ python Python 3.2.2 (default, Jun 23 2014, 00:13:13) [GCC 4.8] on linux-armv7l Type "help", "copyright", "credits" or "license" for more information. >>> list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> >> > I do appreciate all the help too. >> > >> >Hi Seymore! >> > >> >Happy to see that you are moving on from >> >"reading much; understanding nothing; thrashing" >> > >> >to >> > >> >"reading a bit; understanding a bit" >> >[And thanks to Denis to getting you out of your confusion-hole] >> > >> >So heres a small additional question set that I promise will more than repay >> >you your time. >> > >> >Better done in python 2. But if you use python3, below replace >> >range(10) >> >with >> >list(range(10)) > > > > >1. You are reading too much >2. Trying tooooo hard > >Think of riding a bicycle. >Cant do it by reading many books on cycling -- thats 1. >Nor by holding the handle so hard you tremble -- thats 2. > >Just relax a bit... >And take small steps > >Chill... as Chris joked, no monster in the computer (or on this list!) +1 for that remark. Talking about chill: grab a couple of beers (suggest: sixpack) and enjoy an evening of Python! > From rosuav at gmail.com Fri Oct 24 12:47:51 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 25 Oct 2014 03:47:51 +1100 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> Message-ID: On Sat, Oct 25, 2014 at 3:37 AM, Seymore4Head wrote: > When I use list(range(10)) I get: > Traceback (most recent call last): > File "C:/Functions/name to number digit.py", line 37, in > print (nametonumber(a))#1800 438 2427 837 > File "C:/Functions/name to number digit.py", line 10, in > nametonumber > if y in lst(range(1,10)): > TypeError: 'list' object is not callable Now, finally, you're showing us an actual line of code and an actual traceback. And from here, we can see that you misspelled "list". That's why it isn't working. Several people have told you to use the interactive interpreter. Please do so. ChrisA From rustompmody at gmail.com Fri Oct 24 12:54:23 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 09:54:23 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> Message-ID: <526127b6-4f00-4040-9c11-6fc172bce952@googlegroups.com> Totally befuddled myself! Are you deliberately misspelling list to lst and hoping the error will go away. And Puh LEESE dont post screen shots of good ol ASCII text From rustompmody at gmail.com Fri Oct 24 12:56:31 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 09:56:31 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> Message-ID: <8e78cf4b-d7a8-4010-bf8d-fee8712dd912@googlegroups.com> On Friday, October 24, 2014 10:18:12 PM UTC+5:30, Chris Angelico wrote: > On Sat, Oct 25, 2014 at 3:37 AM, Seymore4Head wrote: > > When I use list(range(10)) I get: > > Traceback (most recent call last): > > File "C:/Functions/name to number digit.py", line 37, in > > print (nametonumber(a))#1800 438 2427 837 > > File "C:/Functions/name to number digit.py", line 10, in > > nametonumber > > if y in lst(range(1,10)): > > TypeError: 'list' object is not callable > > Now, finally, you're showing us an actual line of code and an actual > traceback. And from here, we can see that you misspelled "list". > That's why it isn't working. > > Several people have told you to use the interactive interpreter. Please do so. > > ChrisA Right. Good. Sorry for being impatient Seymore You are now making progress From ian.g.kelly at gmail.com Fri Oct 24 13:05:41 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 24 Oct 2014 11:05:41 -0600 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> Message-ID: On Fri, Oct 24, 2014 at 10:37 AM, Seymore4Head wrote: > If I could explain to you why something doesn't work then I could fix > it myself. I don't understand why it doesn't work. The best I can do > is repost the code. You don't need to be able to explain why it doesn't work. You just need to be able to explain what you expected it to do and what it actually did. Posting the code and the traceback that you get is a fine start. > if y in lst(range(1,10)): The name of the builtin is "list". It's a function* that takes an argument and uses it to construct a list, which it returns. "lst" is the name of some specific list that you're using in your code. It's not a function, which is why the error is complaining that it isn't callable. *Actually it's a type object, and calling it causes an instance of the type to be constructed, but for all intents and purposes here it works exactly like a function. From Seymore4Head at Hotmail.invalid Fri Oct 24 13:03:47 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 13:03:47 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> Message-ID: <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> On Sat, 25 Oct 2014 03:47:51 +1100, Chris Angelico wrote: >On Sat, Oct 25, 2014 at 3:37 AM, Seymore4Head > wrote: >> When I use list(range(10)) I get: >> Traceback (most recent call last): >> File "C:/Functions/name to number digit.py", line 37, in >> print (nametonumber(a))#1800 438 2427 837 >> File "C:/Functions/name to number digit.py", line 10, in >> nametonumber >> if y in lst(range(1,10)): >> TypeError: 'list' object is not callable > >Now, finally, you're showing us an actual line of code and an actual >traceback. And from here, we can see that you misspelled "list". >That's why it isn't working. > >Several people have told you to use the interactive interpreter. Please do so. > >ChrisA Actually I was a little frustrated when I added that line back in as the other lines all work. Using list(range(10)) Doesn't throw an error but it doesn't work. http://i.imgur.com/DTc5zoL.jpg The interpreter. I don't know how to use that either. From Seymore4Head at Hotmail.invalid Fri Oct 24 13:04:59 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 13:04:59 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <526127b6-4f00-4040-9c11-6fc172bce952@googlegroups.com> Message-ID: <9k1l4a13av05ejjjpl319onkrgi37qma22@4ax.com> On Fri, 24 Oct 2014 09:54:23 -0700 (PDT), Rustom Mody wrote: >Totally befuddled myself! > >Are you deliberately misspelling list to lst >and hoping the error will go away. > >And Puh LEESE >dont post screen shots of good ol ASCII text I didn't do that on purpose. I make a lot of typing mistakes. Sorry From rosuav at gmail.com Fri Oct 24 13:10:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 25 Oct 2014 04:10:45 +1100 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> Message-ID: On Sat, Oct 25, 2014 at 4:05 AM, Ian Kelly wrote: > The name of the builtin is "list". It's a function* that takes an > argument and uses it to construct a list, which it returns. > > *Actually it's a type object, and calling it causes an instance of the > type to be constructed, but for all intents and purposes here it works > exactly like a function. It's callable, that's all that matters. callable(object) -> bool Return whether the object is callable (i.e., some kind of function). :) ChrisA From rustompmody at gmail.com Fri Oct 24 13:10:06 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 10:10:06 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> Message-ID: <2c07fa2b-6c85-4572-abff-eab5c2454be6@googlegroups.com> On Friday, October 24, 2014 10:06:47 PM UTC+5:30, Ian wrote: > On Fri, Oct 24, 2014 at 9:56 AM, Rustom Mody wrote: > >> Range(10) stores the min max values and loads each number in between > >> when needed. > > > > It loads?? As in 'load-up-a-van'?? > > As in loads into memory. > > > When you see: > > > >>>> 10 > > 10 > > > > 1. Does someone (a clerk maybe) in the computer count to 10? > > 2. Or do you, seeing that interaction, count to 10? > > [If you do, replace the 10 by 1000] > > 3. Or do you, remember what it means to count to 10 without having to do it? > > I don't understand why you think any of these are implied by the word "load". > > > Now go back to your statement about 'loading' and find a better verb > > I presume he used "load" because that was the word I used in my > explanatory post about the difference between range in Python 2 and > Python 3 yesterday. I would be very surprised (Ian) if we had any essential disagreement on this subject. [JFTR I see nothing wrong with your explanation] I would also be (pleasantly) surprised if Seymore were to benefit by these discussions at this stage. So is it ok if we drop it here (or start a new thread)? From albert.visser at gmail.com Fri Oct 24 13:18:12 2014 From: albert.visser at gmail.com (Albert Visser) Date: Fri, 24 Oct 2014 19:18:12 +0200 Subject: I am out of trial and error again Lists In-Reply-To: <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On Fri, 24 Oct 2014 19:03:47 +0200, Seymore4Head wrote: > > http://i.imgur.com/DTc5zoL.jpg > > The interpreter. I don't know how to use that either. > It's what's on the left hand side of your screenshot. You can simply type Python statements following the >>> prompt and hit enter to examine the result, instead of pushing F5 to run your code -- Vriendelijke groeten / Kind regards, Albert Visser Using Opera's mail client: http://www.opera.com/mail/ From rustompmody at gmail.com Fri Oct 24 13:17:58 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 10:17:58 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: <9k1l4a13av05ejjjpl319onkrgi37qma22@4ax.com> References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <526127b6-4f00-4040-9c11-6fc172bce952@googlegroups.com> <9k1l4a13av05ejjjpl319onkrgi37qma22@4ax.com> Message-ID: <4dc5a4e8-4001-4628-be75-1e137739bfab@googlegroups.com> On Friday, October 24, 2014 10:37:45 PM UTC+5:30, Seymore4Head wrote: > On Fri, 24 Oct 2014 09:54:23 -0700 (PDT), Rustom Mody wrote: > > >Totally befuddled myself! > > > >Are you deliberately misspelling list to lst > >and hoping the error will go away. > > > >And Puh LEESE > >dont post screen shots of good ol ASCII text > > I didn't do that on purpose. I make a lot of typing mistakes. > Sorry Right No sweat! I was genuinely asking: - Did you mis-spell list as lst? - Or did you go thrashing (Steven gave a picturesque description) just changing things until the error went? [Believe you me, I do the same when I am in a strange place and I am searching for something in my (suit|brief)case ] From drsalists at gmail.com Fri Oct 24 13:20:30 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Fri, 24 Oct 2014 10:20:30 -0700 Subject: (test) ? a:b In-Reply-To: <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Oct 24, 2014 at 1:38 AM, Steven D'Aprano wrote: > I don't get why that's considered hard to read. > So why is it hard to read when the index is a flag? > > value = [f, g][cond]() It's clear to you, it's clear to me, but is it clear to everyone? I very much doubt it. Also, you've gone to the trouble of def'ing two functions here - you may as well do a function for the if/else. From toby at tobiah.org Fri Oct 24 13:23:26 2014 From: toby at tobiah.org (Tobiah) Date: Fri, 24 Oct 2014 10:23:26 -0700 Subject: (test) ? a:b In-Reply-To: <54476af8$0$21651$426a74cc@news.free.fr> References: <54476af8$0$21651$426a74cc@news.free.fr> Message-ID: On 10/22/2014 01:29 AM, ast wrote: > Hello > > Is there in Python something like: > > j = (j >= 10) ? 3 : j+1; > > as in C language ? > > thx Out of all of the replies, I don't think anyone actually offered the answer: a if condition else b From rosuav at gmail.com Fri Oct 24 13:27:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 25 Oct 2014 04:27:18 +1100 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> Message-ID: On Sat, Oct 25, 2014 at 4:23 AM, Tobiah wrote: > Out of all of the replies, I don't think anyone > actually offered the answer: > > > a if condition else b Jean-Michel did, the very first response. ChrisA From Seymore4Head at Hotmail.invalid Fri Oct 24 13:23:06 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 13:23:06 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On Fri, 24 Oct 2014 19:18:12 +0200, "Albert Visser" wrote: >On Fri, 24 Oct 2014 19:03:47 +0200, Seymore4Head > wrote: > >> >> http://i.imgur.com/DTc5zoL.jpg >> >> The interpreter. I don't know how to use that either. >> > >It's what's on the left hand side of your screenshot. You can simply type >Python statements following the >>> prompt and hit enter to examine the >result, instead of pushing F5 to run your code I guess I am confusing the Interpreter with the debugger. Someone suggested I use the Interpreter to step through line by line. I don't know how to do that. From rustompmody at gmail.com Fri Oct 24 13:42:08 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 10:42:08 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On Friday, October 24, 2014 10:55:44 PM UTC+5:30, Seymore4Head wrote: > On Fri, 24 Oct 2014 19:18:12 +0200, "Albert Visser" wrote: > > >On Fri, 24 Oct 2014 19:03:47 +0200, Seymore4Head wrote: > > > >> > >> http://i.imgur.com/DTc5zoL.jpg > >> > >> The interpreter. I don't know how to use that either. > >> > > > >It's what's on the left hand side of your screenshot. You can simply type > >Python statements following the >>> prompt and hit enter to examine the > >result, instead of pushing F5 to run your code > > I guess I am confusing the Interpreter with the debugger. Someone > suggested I use the Interpreter to step through line by line. > I don't know how to do that. Dont bother with the debugger just yet. For most python programmers, sticking a few print statements (expressions in python 3) in adroitly is good enough.* For now best if you concentrate on 1. What are the features of python -- the language 2. What are the standard data types and functions -- the libraries 3. How to use and jump between the two windows of your screenshot most effectively. What you should and should not type in each etc * One neat trick of using the print to debug. Say you have a line like nx.append("2") and nx is not getting to be what you expect. Change it to nx.append("2"); print(nx) Cleaning up the print after debugging is easier than if you use a separate line like so nx.append("2") print(nx) [I think I learnt this trick from Mark Lawrence] From Seymore4Head at Hotmail.invalid Fri Oct 24 13:42:51 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 13:42:51 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On Fri, 24 Oct 2014 10:42:08 -0700 (PDT), Rustom Mody wrote: >On Friday, October 24, 2014 10:55:44 PM UTC+5:30, Seymore4Head wrote: >> On Fri, 24 Oct 2014 19:18:12 +0200, "Albert Visser" wrote: >> >> >On Fri, 24 Oct 2014 19:03:47 +0200, Seymore4Head wrote: >> > >> >> >> >> http://i.imgur.com/DTc5zoL.jpg >> >> >> >> The interpreter. I don't know how to use that either. >> >> >> > >> >It's what's on the left hand side of your screenshot. You can simply type >> >Python statements following the >>> prompt and hit enter to examine the >> >result, instead of pushing F5 to run your code >> >> I guess I am confusing the Interpreter with the debugger. Someone >> suggested I use the Interpreter to step through line by line. >> I don't know how to do that. > >Dont bother with the debugger just yet. >For most python programmers, sticking a few print statements >(expressions in python 3) in adroitly is good enough.* > >For now best if you concentrate on >1. What are the features of python -- the language >2. What are the standard data types and functions -- the libraries >3. How to use and jump between the two windows of your screenshot most > effectively. What you should and should not type in each etc > >* One neat trick of using the print to debug. >Say you have a line like > >nx.append("2") > >and nx is not getting to be what you expect. >Change it to > >nx.append("2"); print(nx) > >Cleaning up the print after debugging is easier than if you use a >separate line like so > >nx.append("2") >print(nx) > >[I think I learnt this trick from Mark Lawrence] Useful tips Thanks From ian.g.kelly at gmail.com Fri Oct 24 13:52:15 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 24 Oct 2014 11:52:15 -0600 Subject: I am out of trial and error again Lists In-Reply-To: <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On Fri, Oct 24, 2014 at 11:03 AM, Seymore4Head wrote: > Actually I was a little frustrated when I added that line back in as > the other lines all work. > Using list(range(10)) Doesn't throw an error but it doesn't work. > > http://i.imgur.com/DTc5zoL.jpg > > The interpreter. I don't know how to use that either. Try both of these in the interpreter, and observe the difference: 7 in range(10) "7" in range(10) Do you understand what the difference between 7 and "7" is? From davea at davea.name Fri Oct 24 13:57:08 2014 From: davea at davea.name (Dave Angel) Date: Fri, 24 Oct 2014 13:57:08 -0400 (EDT) Subject: (-1)**1000 References: <54476a77$0$21664$426a74cc@news.free.fr> Message-ID: Terry Reedy Wrote in message: > On 10/22/2014 4:27 AM, ast wrote: >> Hello >> >> If i am writing (-1)**1000 on a python program, will the >> interpreter do (-1)*(-1)*...*(-1) or something clever ? > > The answer depends on the implementation. > >> In fact i have (-1)**N with N an integer potentially big. >> >> I do some tests that suggest that Python is clever > > You probably mean "CPython is clever". Other implementations may or may > not have the same optimizations. > I can see several potential optimizations for x**n. Some the CPython implementation does, others I don't know. First, if the two component numbers are known at function compile time, evaluate at compile time. If x is known at compile time to be -1, and n is a non negative integer, just mask the bottom bit of n, and choose -1 or 1 based on that bit. There are other special values, such as 0, -1. If x is a power of 2, and n is an int, then count the trailing zeroes of x, multiply that by n, and construct a (binary) value with that many trailing zeroes. If x isn't any of the above, but n is a postive int, use the square and multiply technique, which is of order log(n). In particular for n of a billion (10**9), it can be done in about 60 multiplies. If neither value is known at compile time, it may still be worth checking for some of these, such as the last. And if x is a float, the last optimization has the advantage of improving accuracy as well as speed. -- DaveA From Seymore4Head at Hotmail.invalid Fri Oct 24 14:15:13 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 14:15:13 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On Fri, 24 Oct 2014 11:52:15 -0600, Ian Kelly wrote: >On Fri, Oct 24, 2014 at 11:03 AM, Seymore4Head > wrote: >> Actually I was a little frustrated when I added that line back in as >> the other lines all work. >> Using list(range(10)) Doesn't throw an error but it doesn't work. >> >> http://i.imgur.com/DTc5zoL.jpg >> >> The interpreter. I don't know how to use that either. > >Try both of these in the interpreter, and observe the difference: > >7 in range(10) > >"7" in range(10) > >Do you understand what the difference between 7 and "7" is? I do understand that. 7 is a number and "7" is a string. What my question was...and still is...is why Python 3 fails when I try using y=1 800 get charter y in range str(range(10)) should work because y is a string and str(range(10)) should be "y" in str(1) fails. It doesn't give an error it's just not True when y is a number. These hints are just not working. I am too thick for hints. :) If you could use it in the code, I might understand. The other work arounds that were posted work. I have used them. str(range(10)) doesn't work. import string def nametonumber(name): lst=[] nx=[] digit=[] digit="".join(str(i) for i in range(10)) for x in name: lst.append(x) for y in (lst): if y in list(range(1,10)): #if y in "1234567890": #if y.isdigit(): #if y in digit: #if y in string.digits: nx.append(y) if y in " -()": nx.append(y) if y in "abc": nx.append("2") if y in "def": nx.append("3") if y in "ghi": nx.append("4") if y in "jkl": nx.append("5") if y in "mno": nx.append("6") if y in "pqrs": nx.append("7") if y in "tuv": nx.append("8") if y in "wxyz": nx.append("9") number="".join(e for e in nx) return number a="1-800-getcharter" print (nametonumber(a))#1800 438 2427 837 a="1-800-leo laporte" print (nametonumber(a)) a="1 800 dialaho" print (nametonumber(a)) Please From ian.g.kelly at gmail.com Fri Oct 24 14:22:33 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 24 Oct 2014 12:22:33 -0600 Subject: (test) ? a:b In-Reply-To: <544a4ef7$0$12984$c3e8da3$5496439d@news.astraweb.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <87tx2tvmea.fsf@elektro.pacujo.net> <544a4ef7$0$12984$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, Oct 24, 2014 at 7:07 AM, Steven D'Aprano >> if j < 10: >> j += 1 >> else: >> j = 3 >> >> or: >> >> j = j + 1 if j < 10 else 3 >> >> or: >> >> j = (lambda: 3, lambda: j + 1)[j < 10]() > > Certainly not the third one. That's needlessly obfuscated for the sake of > premature optimization. This version is much better, and probably not only > simpler and easier to read but probably more efficient too: > > j = (3, j + 1)[j < 10] Yes, the lambda approach falls victim to function calls being slow. $ python3 -m timeit -s "j = 5" "if j < 10: j+=1 > else: j=3" 10000000 loops, best of 3: 0.0513 usec per loop $ python3 -m timeit -s "j = 5" "j = j + 1 if j < 10 else 3" 10000000 loops, best of 3: 0.0519 usec per loop $ python3 -m timeit -s "j = 5" "j = (3, j+1)[j < 10]" 10000000 loops, best of 3: 0.0883 usec per loop $ python3 -m timeit -s "j = 5" "j = (lambda: 3, lambda: j+1)[j < 10]()" 1000000 loops, best of 3: 0.312 usec per loop From Seymore4Head at Hotmail.invalid Fri Oct 24 14:20:37 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 14:20:37 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: I meant to type: if y in range(1,10) doesn't work. Sigh Sorry On Fri, 24 Oct 2014 14:15:13 -0400, Seymore4Head wrote: >On Fri, 24 Oct 2014 11:52:15 -0600, Ian Kelly >wrote: > >>On Fri, Oct 24, 2014 at 11:03 AM, Seymore4Head >> wrote: >>> Actually I was a little frustrated when I added that line back in as >>> the other lines all work. >>> Using list(range(10)) Doesn't throw an error but it doesn't work. >>> >>> http://i.imgur.com/DTc5zoL.jpg >>> >>> The interpreter. I don't know how to use that either. >> >>Try both of these in the interpreter, and observe the difference: >> >>7 in range(10) >> >>"7" in range(10) >> >>Do you understand what the difference between 7 and "7" is? > >I do understand that. 7 is a number and "7" is a string. >What my question was...and still is...is why >Python 3 fails when I try using >y=1 800 get charter > >y in range str(range(10)) >should work because y is a string and str(range(10)) should be >"y" in str(1) fails. >It doesn't give an error it's just not True when y is a number. > >These hints are just not working. I am too thick for hints. :) >If you could use it in the code, I might understand. >The other work arounds that were posted work. >I have used them. str(range(10)) doesn't work. > >import string >def nametonumber(name): > lst=[] > nx=[] > digit=[] > digit="".join(str(i) for i in range(10)) > for x in name: > lst.append(x) > for y in (lst): > if y in list(range(1,10)): > #if y in "1234567890": > #if y.isdigit(): > #if y in digit: > #if y in string.digits: > nx.append(y) > if y in " -()": > nx.append(y) > if y in "abc": > nx.append("2") > if y in "def": > nx.append("3") > if y in "ghi": > nx.append("4") > if y in "jkl": > nx.append("5") > if y in "mno": > nx.append("6") > if y in "pqrs": > nx.append("7") > if y in "tuv": > nx.append("8") > if y in "wxyz": > nx.append("9") > number="".join(e for e in nx) > return number >a="1-800-getcharter" >print (nametonumber(a))#1800 438 2427 837 >a="1-800-leo laporte" >print (nametonumber(a)) >a="1 800 dialaho" >print (nametonumber(a)) > >Please > From breamoreboy at yahoo.co.uk Fri Oct 24 14:33:22 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 24 Oct 2014 19:33:22 +0100 Subject: I am out of trial and error again Lists In-Reply-To: <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On 24/10/2014 18:03, Seymore4Head wrote: > > Actually I was a little frustrated when I added that line back in as > the other lines all work. > Using list(range(10)) Doesn't throw an error but it doesn't work. > > http://i.imgur.com/DTc5zoL.jpg > > The interpreter. I don't know how to use that either. > You've stated that you can use google so why not try it to find out about the interpreter? Or simply navigate to docs.python.org and see what the contents or index tell you? Failing that carry on charging around like a headless chicken and hope that the extremely patient folk here keep helping you out. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From toby at tobiah.org Fri Oct 24 14:31:47 2014 From: toby at tobiah.org (Tobiah) Date: Fri, 24 Oct 2014 11:31:47 -0700 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> Message-ID: On 10/24/2014 10:27 AM, Chris Angelico wrote: > On Sat, Oct 25, 2014 at 4:23 AM, Tobiah wrote: >> Out of all of the replies, I don't think anyone >> actually offered the answer: >> >> >> a if condition else b > > Jean-Michel did, the very first response. > > ChrisA > I had to search for it. For some reason Thunderbird didn't thread that message with all the others. From breamoreboy at yahoo.co.uk Fri Oct 24 14:40:39 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 24 Oct 2014 19:40:39 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On 24/10/2014 19:20, Seymore4Head wrote: > I meant to type: > if y in range(1,10) doesn't work. > Sigh > Sorry > How many more times, state what you expect to happen and what actually happens. "doesn't work" is useless. Please read this http://sscce.org/ -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From marko at pacujo.net Fri Oct 24 14:46:33 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 24 Oct 2014 21:46:33 +0300 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <87tx2tvmea.fsf@elektro.pacujo.net> <544a4ef7$0$12984$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87k33pb912.fsf@elektro.pacujo.net> Ian Kelly : >> j = (lambda: 3, lambda: j + 1)[j < 10]() > Yes, the lambda approach falls victim to function calls being slow. That's just a deficiency in the compiler. There's nothing there that prevents the optimizer from translating the expression into the equivalent if statement. At any rate, the only issue at hand is the obviousness of the idiom. You should generally choose the syntax that best expresses the logic of the program. Marko From sohcahtoa82 at gmail.com Fri Oct 24 14:57:12 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Fri, 24 Oct 2014 11:57:12 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: <6e065210-797a-4494-9fd5-a72f5c069869@googlegroups.com> On Friday, October 24, 2014 11:17:53 AM UTC-7, Seymore4Head wrote: > On Fri, 24 Oct 2014 11:52:15 -0600, Ian Kelly > wrote: > > >On Fri, Oct 24, 2014 at 11:03 AM, Seymore4Head > > wrote: > >> Actually I was a little frustrated when I added that line back in as > >> the other lines all work. > >> Using list(range(10)) Doesn't throw an error but it doesn't work. > >> > >> http://i.imgur.com/DTc5zoL.jpg > >> > >> The interpreter. I don't know how to use that either. > > > >Try both of these in the interpreter, and observe the difference: > > > >7 in range(10) > > > >"7" in range(10) > > > >Do you understand what the difference between 7 and "7" is? > > I do understand that. 7 is a number and "7" is a string. > What my question was...and still is...is why > Python 3 fails when I try using > y=1 800 get charter > > y in range str(range(10)) > should work because y is a string and str(range(10)) should be > "y" in str(1) fails. > It doesn't give an error it's just not True when y is a number. > > These hints are just not working. I am too thick for hints. :) > If you could use it in the code, I might understand. > The other work arounds that were posted work. > I have used them. str(range(10)) doesn't work. > > import string > def nametonumber(name): > lst=[] > nx=[] > digit=[] > digit="".join(str(i) for i in range(10)) > for x in name: > lst.append(x) > for y in (lst): > if y in list(range(1,10)): > #if y in "1234567890": > #if y.isdigit(): > #if y in digit: > #if y in string.digits: > nx.append(y) > if y in " -()": > nx.append(y) > if y in "abc": > nx.append("2") > if y in "def": > nx.append("3") > if y in "ghi": > nx.append("4") > if y in "jkl": > nx.append("5") > if y in "mno": > nx.append("6") > if y in "pqrs": > nx.append("7") > if y in "tuv": > nx.append("8") > if y in "wxyz": > nx.append("9") > number="".join(e for e in nx) > return number > a="1-800-getcharter" > print (nametonumber(a))#1800 438 2427 837 > a="1-800-leo laporte" > print (nametonumber(a)) > a="1 800 dialaho" > print (nametonumber(a)) > > Please Your code here is actually pretty close to a correct answer. Just a few things to consider... - Why are you converting your name string to a list? It is unnecessary. When you do "for y in ", then y will still be single characters on each iteration of the loop. - "if y in string.digits" should work fine. - "if y in list(range(1,10)" won't work for two reasons: First, it creates a list of numbers, not strings. Second, even if it did, it would be missing the "0" digit. - At the end, when you convert your list to a string, you don't need to use list comprehension, since nx is already a list. number = "".join(nx) should work fine. Also, in general, you need to stop and slow down and think like a programmer. If you get an error, your instinct shouldn't be to just hack at it to make the error go away. Look at the error and try to make sense of it. Learn what the error means and try to fix the core problem. And for @#$%'s sake...stop saying "It isn't working" and not elaborating. You've been told by every other post in this thread to show us what you did and what the error was. You've also been told to *NOT* retype what you see and to copy/paste your code and the error because when you make a typo when copying, we might see a problem that doesn't exist and then you just get more confused. From Seymore4Head at Hotmail.invalid Fri Oct 24 15:07:06 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 15:07:06 -0400 Subject: I am out of trial and error again Lists References: <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On Fri, 24 Oct 2014 19:40:39 +0100, Mark Lawrence wrote: >On 24/10/2014 19:20, Seymore4Head wrote: >> I meant to type: >> if y in range(1,10) doesn't work. >> Sigh >> Sorry >> > >How many more times, state what you expect to happen and what actually >happens. "doesn't work" is useless. Please read this http://sscce.org/ Good suggestion. OK how is this? It doesn't print what I expect. Does it print what you expect? name="123-xyz-abc" for x in name: if x in range(10): print ("Range",(x)) if x in str(range(10)): print ("String range",(x)) http://i.imgur.com/EGKUpAb.jpg From Seymore4Head at Hotmail.invalid Fri Oct 24 15:09:31 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 15:09:31 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> <6e065210-797a-4494-9fd5-a72f5c069869@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 11:57:12 -0700 (PDT), sohcahtoa82 at gmail.com wrote: >On Friday, October 24, 2014 11:17:53 AM UTC-7, Seymore4Head wrote: >> On Fri, 24 Oct 2014 11:52:15 -0600, Ian Kelly >> wrote: >> >> >On Fri, Oct 24, 2014 at 11:03 AM, Seymore4Head >> > wrote: >> >> Actually I was a little frustrated when I added that line back in as >> >> the other lines all work. >> >> Using list(range(10)) Doesn't throw an error but it doesn't work. >> >> >> >> http://i.imgur.com/DTc5zoL.jpg >> >> >> >> The interpreter. I don't know how to use that either. >> > >> >Try both of these in the interpreter, and observe the difference: >> > >> >7 in range(10) >> > >> >"7" in range(10) >> > >> >Do you understand what the difference between 7 and "7" is? >> >> I do understand that. 7 is a number and "7" is a string. >> What my question was...and still is...is why >> Python 3 fails when I try using >> y=1 800 get charter >> >> y in range str(range(10)) >> should work because y is a string and str(range(10)) should be >> "y" in str(1) fails. >> It doesn't give an error it's just not True when y is a number. >> >> These hints are just not working. I am too thick for hints. :) >> If you could use it in the code, I might understand. >> The other work arounds that were posted work. >> I have used them. str(range(10)) doesn't work. >> >> import string >> def nametonumber(name): >> lst=[] >> nx=[] >> digit=[] >> digit="".join(str(i) for i in range(10)) >> for x in name: >> lst.append(x) >> for y in (lst): >> if y in list(range(1,10)): >> #if y in "1234567890": >> #if y.isdigit(): >> #if y in digit: >> #if y in string.digits: >> nx.append(y) >> if y in " -()": >> nx.append(y) >> if y in "abc": >> nx.append("2") >> if y in "def": >> nx.append("3") >> if y in "ghi": >> nx.append("4") >> if y in "jkl": >> nx.append("5") >> if y in "mno": >> nx.append("6") >> if y in "pqrs": >> nx.append("7") >> if y in "tuv": >> nx.append("8") >> if y in "wxyz": >> nx.append("9") >> number="".join(e for e in nx) >> return number >> a="1-800-getcharter" >> print (nametonumber(a))#1800 438 2427 837 >> a="1-800-leo laporte" >> print (nametonumber(a)) >> a="1 800 dialaho" >> print (nametonumber(a)) >> >> Please > >Your code here is actually pretty close to a correct answer. Just a few things to consider... > >- Why are you converting your name string to a list? It is unnecessary. When you do "for y in ", then y will still be single characters on each iteration of the loop. > >- "if y in string.digits" should work fine. > >- "if y in list(range(1,10)" won't work for two reasons: First, it creates a list of numbers, not strings. Second, even if it did, it would be missing the "0" digit. > >- At the end, when you convert your list to a string, you don't need to use list comprehension, since nx is already a list. number = "".join(nx) should work fine. > >Also, in general, you need to stop and slow down and think like a programmer. If you get an error, your instinct shouldn't be to just hack at it to make the error go away. Look at the error and try to make sense of it. Learn what the error means and try to fix the core problem. > >And for @#$%'s sake...stop saying "It isn't working" and not elaborating. You've been told by every other post in this thread to show us what you did and what the error was. You've also been told to *NOT* retype what you see and to copy/paste your code and the error because when you make a typo when copying, we might see a problem that doesn't exist and then you just get more confused. Ok I think I may have the question you guys are looking for. I just posted it. See above. But it's still broke. :( From sohcahtoa82 at gmail.com Fri Oct 24 15:25:33 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Fri, 24 Oct 2014 12:25:33 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> <6e065210-797a-4494-9fd5-a72f5c069869@googlegroups.com> Message-ID: <234a2b69-b120-48ba-b697-6ee937d7498f@googlegroups.com> On Friday, October 24, 2014 12:12:10 PM UTC-7, Seymore4Head wrote: > On Fri, 24 Oct 2014 11:57:12 -0700 (PDT), sohcahtoa82 at gmail.com wrote: > > >On Friday, October 24, 2014 11:17:53 AM UTC-7, Seymore4Head wrote: > >> On Fri, 24 Oct 2014 11:52:15 -0600, Ian Kelly > >> wrote: > >> > >> >On Fri, Oct 24, 2014 at 11:03 AM, Seymore4Head > >> > wrote: > >> >> Actually I was a little frustrated when I added that line back in as > >> >> the other lines all work. > >> >> Using list(range(10)) Doesn't throw an error but it doesn't work. > >> >> > >> >> http://i.imgur.com/DTc5zoL.jpg > >> >> > >> >> The interpreter. I don't know how to use that either. > >> > > >> >Try both of these in the interpreter, and observe the difference: > >> > > >> >7 in range(10) > >> > > >> >"7" in range(10) > >> > > >> >Do you understand what the difference between 7 and "7" is? > >> > >> I do understand that. 7 is a number and "7" is a string. > >> What my question was...and still is...is why > >> Python 3 fails when I try using > >> y=1 800 get charter > >> > >> y in range str(range(10)) > >> should work because y is a string and str(range(10)) should be > >> "y" in str(1) fails. > >> It doesn't give an error it's just not True when y is a number. > >> > >> These hints are just not working. I am too thick for hints. :) > >> If you could use it in the code, I might understand. > >> The other work arounds that were posted work. > >> I have used them. str(range(10)) doesn't work. > >> > >> import string > >> def nametonumber(name): > >> lst=[] > >> nx=[] > >> digit=[] > >> digit="".join(str(i) for i in range(10)) > >> for x in name: > >> lst.append(x) > >> for y in (lst): > >> if y in list(range(1,10)): > >> #if y in "1234567890": > >> #if y.isdigit(): > >> #if y in digit: > >> #if y in string.digits: > >> nx.append(y) > >> if y in " -()": > >> nx.append(y) > >> if y in "abc": > >> nx.append("2") > >> if y in "def": > >> nx.append("3") > >> if y in "ghi": > >> nx.append("4") > >> if y in "jkl": > >> nx.append("5") > >> if y in "mno": > >> nx.append("6") > >> if y in "pqrs": > >> nx.append("7") > >> if y in "tuv": > >> nx.append("8") > >> if y in "wxyz": > >> nx.append("9") > >> number="".join(e for e in nx) > >> return number > >> a="1-800-getcharter" > >> print (nametonumber(a))#1800 438 2427 837 > >> a="1-800-leo laporte" > >> print (nametonumber(a)) > >> a="1 800 dialaho" > >> print (nametonumber(a)) > >> > >> Please > > > >Your code here is actually pretty close to a correct answer. Just a few things to consider... > > > >- Why are you converting your name string to a list? It is unnecessary. When you do "for y in ", then y will still be single characters on each iteration of the loop. > > > >- "if y in string.digits" should work fine. > > > >- "if y in list(range(1,10)" won't work for two reasons: First, it creates a list of numbers, not strings. Second, even if it did, it would be missing the "0" digit. > > > >- At the end, when you convert your list to a string, you don't need to use list comprehension, since nx is already a list. number = "".join(nx) should work fine. > > > >Also, in general, you need to stop and slow down and think like a programmer. If you get an error, your instinct shouldn't be to just hack at it to make the error go away. Look at the error and try to make sense of it. Learn what the error means and try to fix the core problem. > > > >And for @#$%'s sake...stop saying "It isn't working" and not elaborating. You've been told by every other post in this thread to show us what you did and what the error was. You've also been told to *NOT* retype what you see and to copy/paste your code and the error because when you make a typo when copying, we might see a problem that doesn't exist and then you just get more confused. > > Ok I think I may have the question you guys are looking for. > I just posted it. > See above. > > But it's still broke. :( str(range(10)) doesn't do what you think it does. Run 'print(str(range(10)))' and look at what you get. From Seymore4Head at Hotmail.invalid Fri Oct 24 15:33:38 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 15:33:38 -0400 Subject: I am out of trial and error again Lists References: <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> <6e065210-797a-4494-9fd5-a72f5c069869@googlegroups.com> <234a2b69-b120-48ba-b697-6ee937d7498f@googlegroups.com> Message-ID: <38al4a9aefpve7vk3e0080rljql72pel5p@4ax.com> On Fri, 24 Oct 2014 12:25:33 -0700 (PDT), sohcahtoa82 at gmail.com wrote: >On Friday, October 24, 2014 12:12:10 PM UTC-7, Seymore4Head wrote: >> On Fri, 24 Oct 2014 11:57:12 -0700 (PDT), sohcahtoa82 at gmail.com wrote: >> >> >On Friday, October 24, 2014 11:17:53 AM UTC-7, Seymore4Head wrote: >> >> On Fri, 24 Oct 2014 11:52:15 -0600, Ian Kelly >> >> wrote: >> >> >> >> >On Fri, Oct 24, 2014 at 11:03 AM, Seymore4Head >> >> > wrote: >> >> >> Actually I was a little frustrated when I added that line back in as >> >> >> the other lines all work. >> >> >> Using list(range(10)) Doesn't throw an error but it doesn't work. >> >> >> >> >> >> http://i.imgur.com/DTc5zoL.jpg >> >> >> >> >> >> The interpreter. I don't know how to use that either. >> >> > >> >> >Try both of these in the interpreter, and observe the difference: >> >> > >> >> >7 in range(10) >> >> > >> >> >"7" in range(10) >> >> > >> >> >Do you understand what the difference between 7 and "7" is? >> >> >> >> I do understand that. 7 is a number and "7" is a string. >> >> What my question was...and still is...is why >> >> Python 3 fails when I try using >> >> y=1 800 get charter >> >> >> >> y in range str(range(10)) >> >> should work because y is a string and str(range(10)) should be >> >> "y" in str(1) fails. >> >> It doesn't give an error it's just not True when y is a number. >> >> >> >> These hints are just not working. I am too thick for hints. :) >> >> If you could use it in the code, I might understand. >> >> The other work arounds that were posted work. >> >> I have used them. str(range(10)) doesn't work. >> >> >> >> import string >> >> def nametonumber(name): >> >> lst=[] >> >> nx=[] >> >> digit=[] >> >> digit="".join(str(i) for i in range(10)) >> >> for x in name: >> >> lst.append(x) >> >> for y in (lst): >> >> if y in list(range(1,10)): >> >> #if y in "1234567890": >> >> #if y.isdigit(): >> >> #if y in digit: >> >> #if y in string.digits: >> >> nx.append(y) >> >> if y in " -()": >> >> nx.append(y) >> >> if y in "abc": >> >> nx.append("2") >> >> if y in "def": >> >> nx.append("3") >> >> if y in "ghi": >> >> nx.append("4") >> >> if y in "jkl": >> >> nx.append("5") >> >> if y in "mno": >> >> nx.append("6") >> >> if y in "pqrs": >> >> nx.append("7") >> >> if y in "tuv": >> >> nx.append("8") >> >> if y in "wxyz": >> >> nx.append("9") >> >> number="".join(e for e in nx) >> >> return number >> >> a="1-800-getcharter" >> >> print (nametonumber(a))#1800 438 2427 837 >> >> a="1-800-leo laporte" >> >> print (nametonumber(a)) >> >> a="1 800 dialaho" >> >> print (nametonumber(a)) >> >> >> >> Please >> > >> >Your code here is actually pretty close to a correct answer. Just a few things to consider... >> > >> >- Why are you converting your name string to a list? It is unnecessary. When you do "for y in ", then y will still be single characters on each iteration of the loop. >> > >> >- "if y in string.digits" should work fine. >> > >> >- "if y in list(range(1,10)" won't work for two reasons: First, it creates a list of numbers, not strings. Second, even if it did, it would be missing the "0" digit. >> > >> >- At the end, when you convert your list to a string, you don't need to use list comprehension, since nx is already a list. number = "".join(nx) should work fine. >> > >> >Also, in general, you need to stop and slow down and think like a programmer. If you get an error, your instinct shouldn't be to just hack at it to make the error go away. Look at the error and try to make sense of it. Learn what the error means and try to fix the core problem. >> > >> >And for @#$%'s sake...stop saying "It isn't working" and not elaborating. You've been told by every other post in this thread to show us what you did and what the error was. You've also been told to *NOT* retype what you see and to copy/paste your code and the error because when you make a typo when copying, we might see a problem that doesn't exist and then you just get more confused. >> >> Ok I think I may have the question you guys are looking for. >> I just posted it. >> See above. >> >> But it's still broke. :( > >str(range(10)) doesn't do what you think it does. > >Run 'print(str(range(10)))' and look at what you get. Yeah, I know that. My question is why? The answer was that Python 3 only stores the min and max values but you can still iterate over them. I don't think that means what I think it means. From sohcahtoa82 at gmail.com Fri Oct 24 15:55:19 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Fri, 24 Oct 2014 12:55:19 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: <38al4a9aefpve7vk3e0080rljql72pel5p@4ax.com> References: <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> <6e065210-797a-4494-9fd5-a72f5c069869@googlegroups.com> <234a2b69-b120-48ba-b697-6ee937d7498f@googlegroups.com> <38al4a9aefpve7vk3e0080rljql72pel5p@4ax.com> Message-ID: <42fdc118-a0f7-453e-baf6-9f93f6eb9321@googlegroups.com> On Friday, October 24, 2014 12:36:23 PM UTC-7, Seymore4Head wrote: > On Fri, 24 Oct 2014 12:25:33 -0700 (PDT), sohcahtoa82 at gmail.com wrote: > > >On Friday, October 24, 2014 12:12:10 PM UTC-7, Seymore4Head wrote: > >> On Fri, 24 Oct 2014 11:57:12 -0700 (PDT), sohcahtoa82 at gmail.com wrote: > >> > >> >On Friday, October 24, 2014 11:17:53 AM UTC-7, Seymore4Head wrote: > >> >> On Fri, 24 Oct 2014 11:52:15 -0600, Ian Kelly > >> >> wrote: > >> >> > >> >> >On Fri, Oct 24, 2014 at 11:03 AM, Seymore4Head > >> >> > wrote: > >> >> >> Actually I was a little frustrated when I added that line back in as > >> >> >> the other lines all work. > >> >> >> Using list(range(10)) Doesn't throw an error but it doesn't work. > >> >> >> > >> >> >> http://i.imgur.com/DTc5zoL.jpg > >> >> >> > >> >> >> The interpreter. I don't know how to use that either. > >> >> > > >> >> >Try both of these in the interpreter, and observe the difference: > >> >> > > >> >> >7 in range(10) > >> >> > > >> >> >"7" in range(10) > >> >> > > >> >> >Do you understand what the difference between 7 and "7" is? > >> >> > >> >> I do understand that. 7 is a number and "7" is a string. > >> >> What my question was...and still is...is why > >> >> Python 3 fails when I try using > >> >> y=1 800 get charter > >> >> > >> >> y in range str(range(10)) > >> >> should work because y is a string and str(range(10)) should be > >> >> "y" in str(1) fails. > >> >> It doesn't give an error it's just not True when y is a number. > >> >> > >> >> These hints are just not working. I am too thick for hints. :) > >> >> If you could use it in the code, I might understand. > >> >> The other work arounds that were posted work. > >> >> I have used them. str(range(10)) doesn't work. > >> >> > >> >> import string > >> >> def nametonumber(name): > >> >> lst=[] > >> >> nx=[] > >> >> digit=[] > >> >> digit="".join(str(i) for i in range(10)) > >> >> for x in name: > >> >> lst.append(x) > >> >> for y in (lst): > >> >> if y in list(range(1,10)): > >> >> #if y in "1234567890": > >> >> #if y.isdigit(): > >> >> #if y in digit: > >> >> #if y in string.digits: > >> >> nx.append(y) > >> >> if y in " -()": > >> >> nx.append(y) > >> >> if y in "abc": > >> >> nx.append("2") > >> >> if y in "def": > >> >> nx.append("3") > >> >> if y in "ghi": > >> >> nx.append("4") > >> >> if y in "jkl": > >> >> nx.append("5") > >> >> if y in "mno": > >> >> nx.append("6") > >> >> if y in "pqrs": > >> >> nx.append("7") > >> >> if y in "tuv": > >> >> nx.append("8") > >> >> if y in "wxyz": > >> >> nx.append("9") > >> >> number="".join(e for e in nx) > >> >> return number > >> >> a="1-800-getcharter" > >> >> print (nametonumber(a))#1800 438 2427 837 > >> >> a="1-800-leo laporte" > >> >> print (nametonumber(a)) > >> >> a="1 800 dialaho" > >> >> print (nametonumber(a)) > >> >> > >> >> Please > >> > > >> >Your code here is actually pretty close to a correct answer. Just a few things to consider... > >> > > >> >- Why are you converting your name string to a list? It is unnecessary. When you do "for y in ", then y will still be single characters on each iteration of the loop. > >> > > >> >- "if y in string.digits" should work fine. > >> > > >> >- "if y in list(range(1,10)" won't work for two reasons: First, it creates a list of numbers, not strings. Second, even if it did, it would be missing the "0" digit. > >> > > >> >- At the end, when you convert your list to a string, you don't need to use list comprehension, since nx is already a list. number = "".join(nx) should work fine. > >> > > >> >Also, in general, you need to stop and slow down and think like a programmer. If you get an error, your instinct shouldn't be to just hack at it to make the error go away. Look at the error and try to make sense of it. Learn what the error means and try to fix the core problem. > >> > > >> >And for @#$%'s sake...stop saying "It isn't working" and not elaborating. You've been told by every other post in this thread to show us what you did and what the error was. You've also been told to *NOT* retype what you see and to copy/paste your code and the error because when you make a typo when copying, we might see a problem that doesn't exist and then you just get more confused. > >> > >> Ok I think I may have the question you guys are looking for. > >> I just posted it. > >> See above. > >> > >> But it's still broke. :( > > > >str(range(10)) doesn't do what you think it does. > > > >Run 'print(str(range(10)))' and look at what you get. > > Yeah, I know that. My question is why? > The answer was that Python 3 only stores the min and max values but > you can still iterate over them. > I don't think that means what I think it means. "You can iterate over them" pretty much just means you can use them as the source of a 'for' loop. But in your case, when you're calling 'for y in str(range(10))', you're not using 'range(10)' as the source of your loop, you're using the result of a str() function call, and you're calling str() on range(), which doesn't return a concrete value in Python 3. If you try to print a range(), you're just getting a string containing your original call to range. And that's why you're seeing the 1 and a in your output. str(range(10)) returns the string 'range(10)'. Like I said in a previous post, use 'string.digits'. Try this test code and see what you get: import string name="123-xyz-abc" print("string.digits is", string.digits) for x in name: if x in range(10): print ("Range",(x)) if x in string.digits: print ("string.digits",(x)) From Seymore4Head at Hotmail.invalid Fri Oct 24 16:00:30 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 16:00:30 -0400 Subject: I am out of trial and error again Lists References: <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> <6e065210-797a-4494-9fd5-a72f5c069869@googlegroups.com> <234a2b69-b120-48ba-b697-6ee937d7498f@googlegroups.com> <38al4a9aefpve7vk3e0080rljql72pel5p@4ax.com> <42fdc118-a0f7-453e-baf6-9f93f6eb9321@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 12:55:19 -0700 (PDT), sohcahtoa82 at gmail.com wrote: >On Friday, October 24, 2014 12:36:23 PM UTC-7, Seymore4Head wrote: >> On Fri, 24 Oct 2014 12:25:33 -0700 (PDT), sohcahtoa82 at gmail.com wrote: >> >> >On Friday, October 24, 2014 12:12:10 PM UTC-7, Seymore4Head wrote: >> >> On Fri, 24 Oct 2014 11:57:12 -0700 (PDT), sohcahtoa82 at gmail.com wrote: >> >> >> >> >On Friday, October 24, 2014 11:17:53 AM UTC-7, Seymore4Head wrote: >> >> >> On Fri, 24 Oct 2014 11:52:15 -0600, Ian Kelly >> >> >> wrote: >> >> >> >> >> >> >On Fri, Oct 24, 2014 at 11:03 AM, Seymore4Head >> >> >> > wrote: >> >> >> >> Actually I was a little frustrated when I added that line back in as >> >> >> >> the other lines all work. >> >> >> >> Using list(range(10)) Doesn't throw an error but it doesn't work. >> >> >> >> >> >> >> >> http://i.imgur.com/DTc5zoL.jpg >> >> >> >> >> >> >> >> The interpreter. I don't know how to use that either. >> >> >> > >> >> >> >Try both of these in the interpreter, and observe the difference: >> >> >> > >> >> >> >7 in range(10) >> >> >> > >> >> >> >"7" in range(10) >> >> >> > >> >> >> >Do you understand what the difference between 7 and "7" is? >> >> >> >> >> >> I do understand that. 7 is a number and "7" is a string. >> >> >> What my question was...and still is...is why >> >> >> Python 3 fails when I try using >> >> >> y=1 800 get charter >> >> >> >> >> >> y in range str(range(10)) >> >> >> should work because y is a string and str(range(10)) should be >> >> >> "y" in str(1) fails. >> >> >> It doesn't give an error it's just not True when y is a number. >> >> >> >> >> >> These hints are just not working. I am too thick for hints. :) >> >> >> If you could use it in the code, I might understand. >> >> >> The other work arounds that were posted work. >> >> >> I have used them. str(range(10)) doesn't work. >> >> >> >> >> >> import string >> >> >> def nametonumber(name): >> >> >> lst=[] >> >> >> nx=[] >> >> >> digit=[] >> >> >> digit="".join(str(i) for i in range(10)) >> >> >> for x in name: >> >> >> lst.append(x) >> >> >> for y in (lst): >> >> >> if y in list(range(1,10)): >> >> >> #if y in "1234567890": >> >> >> #if y.isdigit(): >> >> >> #if y in digit: >> >> >> #if y in string.digits: >> >> >> nx.append(y) >> >> >> if y in " -()": >> >> >> nx.append(y) >> >> >> if y in "abc": >> >> >> nx.append("2") >> >> >> if y in "def": >> >> >> nx.append("3") >> >> >> if y in "ghi": >> >> >> nx.append("4") >> >> >> if y in "jkl": >> >> >> nx.append("5") >> >> >> if y in "mno": >> >> >> nx.append("6") >> >> >> if y in "pqrs": >> >> >> nx.append("7") >> >> >> if y in "tuv": >> >> >> nx.append("8") >> >> >> if y in "wxyz": >> >> >> nx.append("9") >> >> >> number="".join(e for e in nx) >> >> >> return number >> >> >> a="1-800-getcharter" >> >> >> print (nametonumber(a))#1800 438 2427 837 >> >> >> a="1-800-leo laporte" >> >> >> print (nametonumber(a)) >> >> >> a="1 800 dialaho" >> >> >> print (nametonumber(a)) >> >> >> >> >> >> Please >> >> > >> >> >Your code here is actually pretty close to a correct answer. Just a few things to consider... >> >> > >> >> >- Why are you converting your name string to a list? It is unnecessary. When you do "for y in ", then y will still be single characters on each iteration of the loop. >> >> > >> >> >- "if y in string.digits" should work fine. >> >> > >> >> >- "if y in list(range(1,10)" won't work for two reasons: First, it creates a list of numbers, not strings. Second, even if it did, it would be missing the "0" digit. >> >> > >> >> >- At the end, when you convert your list to a string, you don't need to use list comprehension, since nx is already a list. number = "".join(nx) should work fine. >> >> > >> >> >Also, in general, you need to stop and slow down and think like a programmer. If you get an error, your instinct shouldn't be to just hack at it to make the error go away. Look at the error and try to make sense of it. Learn what the error means and try to fix the core problem. >> >> > >> >> >And for @#$%'s sake...stop saying "It isn't working" and not elaborating. You've been told by every other post in this thread to show us what you did and what the error was. You've also been told to *NOT* retype what you see and to copy/paste your code and the error because when you make a typo when copying, we might see a problem that doesn't exist and then you just get more confused. >> >> >> >> Ok I think I may have the question you guys are looking for. >> >> I just posted it. >> >> See above. >> >> >> >> But it's still broke. :( >> > >> >str(range(10)) doesn't do what you think it does. >> > >> >Run 'print(str(range(10)))' and look at what you get. >> >> Yeah, I know that. My question is why? >> The answer was that Python 3 only stores the min and max values but >> you can still iterate over them. >> I don't think that means what I think it means. > >"You can iterate over them" pretty much just means you can use them as the source of a 'for' loop. But in your case, when you're calling 'for y in str(range(10))', you're not using 'range(10)' as the source of your loop, you're using the result of a str() function call, and you're calling str() on range(), which doesn't return a concrete value in Python 3. If you try to print a range(), you're just getting a string containing your original call to range. > >And that's why you're seeing the 1 and a in your output. str(range(10)) returns the string 'range(10)'. > >Like I said in a previous post, use 'string.digits'. Try this test code and see what you get: > >import string >name="123-xyz-abc" >print("string.digits is", string.digits) >for x in name: > if x in range(10): > print ("Range",(x)) > if x in string.digits: > print ("string.digits",(x)) Your example works. With range(10) you don't expect to see an "a" either. Thanks From denismfmcmahon at gmail.com Fri Oct 24 16:37:31 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 24 Oct 2014 20:37:31 +0000 (UTC) Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 10:38:31 -0400, Seymore4Head wrote: > I tried list(range(10) This is missing a ")" It probably sat there waiting for you to finish the line. list(range(10)) You have two "(" in the line, you need two ")" to match them. > I thought that would work in Python 3. It > didn't. It does if you enter it properly. also try: str(list(range(10))) Note that that has three "(" and three ")" on the line. -- Denis McMahon, denismfmcmahon at gmail.com From alister.nospam.ware at ntlworld.com Fri Oct 24 16:58:13 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Fri, 24 Oct 2014 20:58:13 GMT Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, 24 Oct 2014 10:20:30 -0700, Dan Stromberg wrote: > On Fri, Oct 24, 2014 at 1:38 AM, Steven D'Aprano > wrote: >> I don't get why that's considered hard to read. > >> So why is it hard to read when the index is a flag? >> >> value = [f, g][cond]() > > It's clear to you, it's clear to me, but is it clear to everyone? I > very much doubt it. I had to mentally step through this before it became apparent what it was doing, can see places where it could be usefull (a switch replacement) but it is not instantly obvious a = if else is instantly obvious (at least to a native English speaker anyway) > > Also, you've gone to the trouble of def'ing two functions here - you may > as well do a function for the if/else. -- "Humor is a drug which it's the fashion to abuse." -- William Gilbert From Seymore4Head at Hotmail.invalid Fri Oct 24 16:58:00 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 16:58:00 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 20:37:31 +0000 (UTC), Denis McMahon wrote: >On Fri, 24 Oct 2014 10:38:31 -0400, Seymore4Head wrote: > >> I tried list(range(10) > >This is missing a ")" > >It probably sat there waiting for you to finish the line. > >list(range(10)) > >You have two "(" in the line, you need two ")" to match them. > >> I thought that would work in Python 3. It >> didn't. > >It does if you enter it properly. > >also try: > >str(list(range(10))) > >Note that that has three "(" and three ")" on the line. I make lots of typing mistakes. It is not that. Did you see the short example I posted? name="123-xyz-abc" for x in name: if x in range(10): print ("Range",(x)) if x in str(range(10)): print ("String range",(x)) It doesn't throw an error but it doesn't print what you would expect. From marko at pacujo.net Fri Oct 24 17:02:58 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sat, 25 Oct 2014 00:02:58 +0300 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <8738adb2pp.fsf@elektro.pacujo.net> alister : > a = if else > > is instantly obvious (at least to a native English speaker anyway) And you can go further down that road. For example, you could say things like: die unless everything is OK Marko From none at mailinator.com Fri Oct 24 17:06:02 2014 From: none at mailinator.com (mm0fmf) Date: Fri, 24 Oct 2014 22:06:02 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: <4bz2w.756033$ZX5.542327@fx32.am4> On 24/10/2014 15:47, Seymore4Head wrote: > I have at least 10 ebooks. I will get around to reading them soon. Sooner would be better. From alister.nospam.ware at ntlworld.com Fri Oct 24 17:07:53 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Fri, 24 Oct 2014 21:07:53 GMT Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 16:58:00 -0400, Seymore4Head wrote: > On Fri, 24 Oct 2014 20:37:31 +0000 (UTC), Denis McMahon > wrote: > >>On Fri, 24 Oct 2014 10:38:31 -0400, Seymore4Head wrote: >> >>> I tried list(range(10) >> >>This is missing a ")" >> >>It probably sat there waiting for you to finish the line. >> >>list(range(10)) >> >>You have two "(" in the line, you need two ")" to match them. >> >>> I thought that would work in Python 3. It didn't. >> >>It does if you enter it properly. >> >>also try: >> >>str(list(range(10))) >> >>Note that that has three "(" and three ")" on the line. > > I make lots of typing mistakes. It is not that. Did you see the short > example I posted? > > name="123-xyz-abc" > for x in name: > if x in range(10): > print ("Range",(x)) > if x in str(range(10)): > print ("String range",(x)) > > It doesn't throw an error but it doesn't print what you would expect. it prints what "I" expect, it probably does not print what you expect you have may times been told that str(range(10)) does not do what you expect but you keep failing to test you think that it crates a list of strings ['1','2','3'....] but it does not it creates a list & then turns the whole list into a string '[1,2,3...]' people are suggesting you try this things in the interactive prompt because doing teaches far better than just reading. -- Honesty's the best policy. -- Miguel de Cervantes From ian.g.kelly at gmail.com Fri Oct 24 17:11:14 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 24 Oct 2014 15:11:14 -0600 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Fri, Oct 24, 2014 at 2:58 PM, Seymore4Head wrote: > name="123-xyz-abc" > for x in name: > if x in range(10): > print ("Range",(x)) > if x in str(range(10)): > print ("String range",(x)) > > It doesn't throw an error but it doesn't print what you would expect. That prints exactly what I expect it to. The first if prints nothing, because you're testing whether a string is contained in a sequence of ints. That will always be false. The second if prints those characters from name that happen to be in the string "range(10)". That's the "1" and the "a". Apparently it doesn't print what *you* expect, which is why you need to make your expectation clear and not assume that we will just read your mind and immediately understand what you expect the code to do. From denismfmcmahon at gmail.com Fri Oct 24 17:19:22 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 24 Oct 2014 21:19:22 +0000 (UTC) Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On Fri, 24 Oct 2014 14:15:13 -0400, Seymore4Head wrote: > I do understand that. 7 is a number and "7" is a string. > What my question was...and still is...is why Python 3 fails when I try > using y=1 800 get charter > > y in range str(range(10)) > should work because y is a string and str(range(10)) should be "y" in > str(1) fails. > It doesn't give an error it's just not True when y is a number. This is because str(range(10)) does not do what you think it does. In python 2.x, str(range(10)) creates a string representation of the complete list, not a list of the string representation of the separate list elements. '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' In python 3.x, str(range(10)) creates a string representation of the list object. 'range(0, 10)' the only single digit strings in the python3 representation are "0" and "1" To recreate the python2 behaviour in python 3, use: str(list(range(10))) which gives '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' howver the test: if x.isdigit(): is much better. But finally, with your telephone number decoder, look at: http://www.codeskulptor.org/#user38_QnR06Upp4AH6h0Q.py -- Denis McMahon, denismfmcmahon at gmail.com From Seymore4Head at Hotmail.invalid Fri Oct 24 17:35:34 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 17:35:34 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: <41hl4a1va2dafjtm8gi8q9diknn484dnje@4ax.com> On Fri, 24 Oct 2014 21:19:22 +0000 (UTC), Denis McMahon wrote: >On Fri, 24 Oct 2014 14:15:13 -0400, Seymore4Head wrote: > >> I do understand that. 7 is a number and "7" is a string. >> What my question was...and still is...is why Python 3 fails when I try >> using y=1 800 get charter >> >> y in range str(range(10)) >> should work because y is a string and str(range(10)) should be "y" in >> str(1) fails. >> It doesn't give an error it's just not True when y is a number. > >This is because str(range(10)) does not do what you think it does. > >In python 2.x, str(range(10)) creates a string representation of the >complete list, not a list of the string representation of the separate >list elements. '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' > >In python 3.x, str(range(10)) creates a string representation of the list >object. 'range(0, 10)' > >the only single digit strings in the python3 representation are "0" and >"1" > >To recreate the python2 behaviour in python 3, use: > >str(list(range(10))) > >which gives > >'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' > >howver the test: > >if x.isdigit(): > >is much better. > >But finally, with your telephone number decoder, look at: > >http://www.codeskulptor.org/#user38_QnR06Upp4AH6h0Q.py That is much cleaner than mine. Nice. I did make one more change to mine that makes it easier to read. I changed treating all " -()" With a space. I am still thinking about how to treat the large space if it is a digit instead: 1 800 555 5555 From denismfmcmahon at gmail.com Fri Oct 24 17:48:14 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 24 Oct 2014 21:48:14 +0000 (UTC) Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 10:38:31 -0400, Seymore4Head wrote: > Thanks everyone for your suggestions. Try loading the following in codeskulptor: http://www.codeskulptor.org/#user38_j6kGKgeOMr_0.py -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Fri Oct 24 17:49:27 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 24 Oct 2014 21:49:27 +0000 (UTC) Subject: I am out of trial and error again Lists References: <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: On Fri, 24 Oct 2014 15:07:06 -0400, Seymore4Head wrote: > On Fri, 24 Oct 2014 19:40:39 +0100, Mark Lawrence > wrote: > >>On 24/10/2014 19:20, Seymore4Head wrote: >>> I meant to type: >>> if y in range(1,10) doesn't work. >>> Sigh Sorry >>> >>> >>How many more times, state what you expect to happen and what actually >>happens. "doesn't work" is useless. Please read this http://sscce.org/ > > Good suggestion. > OK how is this? > It doesn't print what I expect. > Does it print what you expect? > > name="123-xyz-abc" > for x in name: > if x in range(10): > print ("Range",(x)) > if x in str(range(10)): > print ("String range",(x)) > > http://i.imgur.com/EGKUpAb.jpg I suspect you're discovering the difference between the python2 and python3 range() functions, and what happens when you encapsulate them in string. I've already posted about this once this evening. -- Denis McMahon, denismfmcmahon at gmail.com From davea at davea.name Fri Oct 24 18:09:59 2014 From: davea at davea.name (Dave Angel) Date: Fri, 24 Oct 2014 18:09:59 -0400 (EDT) Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <526127b6-4f00-4040-9c11-6fc172bce952@googlegroups.com> <9k1l4a13av05ejjjpl319onkrgi37qma22@4ax.com> Message-ID: Seymore4Head Wrote in message: > On Fri, 24 Oct 2014 09:54:23 -0700 (PDT), Rustom Mody > wrote: > >>Totally befuddled myself! >> >>Are you deliberately misspelling list to lst >>and hoping the error will go away. >> >>And Puh LEESE >>dont post screen shots of good ol ASCII text > > I didn't do that on purpose. I make a lot of typing mistakes. > Sorry > That's what copy/paste are for. Copy from your console, and paste into your email. Don't ever retype unless you're trying to frustrate us, -- DaveA From Seymore4Head at Hotmail.invalid Fri Oct 24 18:14:25 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 18:14:25 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: <9ojl4allmth89g1jd8286njq5722ssqen8@4ax.com> On Fri, 24 Oct 2014 21:48:14 +0000 (UTC), Denis McMahon wrote: >On Fri, 24 Oct 2014 10:38:31 -0400, Seymore4Head wrote: > >> Thanks everyone for your suggestions. > >Try loading the following in codeskulptor: > >http://www.codeskulptor.org/#user38_j6kGKgeOMr_0.py That is a useful way to test. Thanks. From Seymore4Head at Hotmail.invalid Fri Oct 24 18:26:14 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 18:26:14 -0400 Subject: I am out of trial and error again Lists References: Message-ID: <39kl4algu6ddgs2bsev3vlf9md9blmfdpm@4ax.com> On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: Thanks for all the helpful replies. I just discovered that there is something wrong with my news feed. Some of the messages did not make it to me. I can go back and read this thread in Google Groups but I can't reply to it. If I missed thanking or replying to anyone, that is the reason. Thanks again From Seymore4Head at Hotmail.invalid Fri Oct 24 18:27:15 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 18:27:15 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <526127b6-4f00-4040-9c11-6fc172bce952@googlegroups.com> <9k1l4a13av05ejjjpl319onkrgi37qma22@4ax.com> Message-ID: <4hkl4app29cjecaiadi9fe6e8tgttl3os6@4ax.com> On Fri, 24 Oct 2014 18:09:59 -0400 (EDT), Dave Angel wrote: >Seymore4Head Wrote in message: >> On Fri, 24 Oct 2014 09:54:23 -0700 (PDT), Rustom Mody >> wrote: >> >>>Totally befuddled myself! >>> >>>Are you deliberately misspelling list to lst >>>and hoping the error will go away. >>> >>>And Puh LEESE >>>dont post screen shots of good ol ASCII text >> >> I didn't do that on purpose. I make a lot of typing mistakes. >> Sorry >> > >That's what copy/paste are for. Copy from your console, and paste > into your email. Don't ever retype unless you're trying to > frustrate us, I promise I am not trying to frustrate anyone. I know I have. Sorry From Seymore4Head at Hotmail.invalid Fri Oct 24 18:58:04 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 18:58:04 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: name="123-xyz-abc" a=range(10) b=list(range(10)) c=str(list(range(10))) print ("a",(a)) print ("b",(b)) print ("c",(c)) for x in name: if x in a: print ("a",(x)) if x in b: print ("b",(x)) if x in c: print ("c",(x)) B is type list and C is type str. I guess I am still a little too thick. I would expect b and c to work. http://i.imgur.com/dT3sEQq.jpg From rustompmody at gmail.com Fri Oct 24 19:01:39 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 16:01:39 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: <4hkl4app29cjecaiadi9fe6e8tgttl3os6@4ax.com> References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <526127b6-4f00-4040-9c11-6fc172bce952@googlegroups.com> <9k1l4a13av05ejjjpl319onkrgi37qma22@4ax.com> <4hkl4app29cjecaiadi9fe6e8tgttl3os6@4ax.com> Message-ID: On Saturday, October 25, 2014 4:00:01 AM UTC+5:30, Seymore4Head wrote: > On Fri, 24 Oct 2014 18:09:59 -0400 (EDT), Dave Angel wrote: > > Don't ever retype unless you're trying to > > frustrate us, > > I promise I am not trying to frustrate anyone. I know I have. > Sorry No issues Seymore :-) As far as I am concerned this has been useful and educative for me -- I found out about codeskulptor. Though I am a bit conflicted whether it helps or confuses students. Also many other things... What I take as minor distinctions between python 2 and 3 may not be so minor if one doesn't know whats going on. From denismfmcmahon at gmail.com Fri Oct 24 19:21:43 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 24 Oct 2014 23:21:43 +0000 (UTC) Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 16:58:00 -0400, Seymore4Head wrote: > I make lots of typing mistakes. It is not that. Did you see the short > example I posted? > > name="123-xyz-abc" > for x in name: > if x in range(10): > print ("Range",(x)) > if x in str(range(10)): > print ("String range",(x)) > > It doesn't throw an error but it doesn't print what you would expect. It prints exactly what I expect. Try the following: print(str(range(10)), type(str(range(10)))) print(str(list(range(10))), type(str(listr(range(10))))) In python 3, str(x) just wraps x up and puts it in a string. range(x) generates an iterable range object. hence str(range(10)) is a string telling you that range(10) is an iterable range object with certain boundaries. However, list(iterable) expands the iterable to the full list of possible values, so str(list(range(10))) is a string representation of the list containing the values that the iterable range(10) creates. Note that whether you're looking at a string representation of a value or the value itself is a lot clearer in the interpreter console where strings are displayed with quotes. -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Fri Oct 24 19:23:42 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 24 Oct 2014 23:23:42 +0000 (UTC) Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> <41hl4a1va2dafjtm8gi8q9diknn484dnje@4ax.com> Message-ID: On Fri, 24 Oct 2014 17:35:34 -0400, Seymore4Head wrote: >>But finally, with your telephone number decoder, look at: >> >>http://www.codeskulptor.org/#user38_QnR06Upp4AH6h0Q.py > > That is much cleaner than mine. Nice. > > I did make one more change to mine that makes it easier to read. I > changed treating all " -()" With a space. > I am still thinking about how to treat the large space if it is a digit > instead: > 1 800 555 5555 Note that my decoder assumes anything other than a letter can be copied straight to the output string. -- Denis McMahon, denismfmcmahon at gmail.com From breamoreboy at yahoo.co.uk Fri Oct 24 19:27:53 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 25 Oct 2014 00:27:53 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: On 24/10/2014 23:58, Seymore4Head wrote: > On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head > wrote: > > name="123-xyz-abc" > a=range(10) > b=list(range(10)) > c=str(list(range(10))) > print ("a",(a)) > print ("b",(b)) > print ("c",(c)) > > for x in name: > if x in a: > print ("a",(x)) > if x in b: > print ("b",(x)) > if x in c: > print ("c",(x)) > > B is type list and C is type str. > I guess I am still a little too thick. I would expect b and c to > work. > http://i.imgur.com/dT3sEQq.jpg > Why? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rustompmody at gmail.com Fri Oct 24 19:27:58 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 16:27:58 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> On Saturday, October 25, 2014 4:30:47 AM UTC+5:30, Seymore4Head wrote: > On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: > > name="123-xyz-abc" > a=range(10) > b=list(range(10)) > c=str(list(range(10))) > print ("a",(a)) > print ("b",(b)) > print ("c",(c)) > > for x in name: > if x in a: > print ("a",(x)) > if x in b: > print ("b",(x)) > if x in c: > print ("c",(x)) > > B is type list and C is type str. > I guess I am still a little too thick. I would expect b and c to > work. Lets simplify the problem a bit. Do all the following in interpreter window >>> name="012" >>> b=list(range(3)) >>> for x in name: print x >>> for x in b: print x Same or different? Now go back to Denis' nice example and put in type(x) into each print Same or different? From denismfmcmahon at gmail.com Fri Oct 24 19:35:02 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 24 Oct 2014 23:35:02 +0000 (UTC) Subject: I am out of trial and error again Lists References: Message-ID: On Fri, 24 Oct 2014 18:58:04 -0400, Seymore4Head wrote: > On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head > wrote: OK, assuming you tried to run this in python3, not python2 or codeskulptor. > name="123-xyz-abc" > a=range(10) ^^^^ a is an iterable object giving the numbers 0 through 9 > b=list(range(10)) ^^^^ b is an list containing the numbers 0 through 9 > c=str(list(range(10))) ^^^^ c is an string representation of a list containing the numbers 0 through 9 > print ("a",(a)) > print ("b",(b)) > print ("c",(c)) > > for x in name: ^^^^^ x is a string representing one character in name > if x in a: > print ("a",(x)) ^^^^ here you are looking for a string x amongst the numbers yielded by an iterable > if x in b: > print ("b",(x)) ^^^^ here you are comparing a string x with the elements of a list of numbers > if x in c: > print ("c",(x)) ^^^^ here you are comparing a string x with the characters in a string representation of a list of numbers > B is type list and C is type str. > I guess I am still a little too thick. I would expect b and c to work. > http://i.imgur.com/dT3sEQq.jpg a is the range object: range(0, 9) b is the list: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] c is the string: "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" When you try and compare a character x eg "8" with the numbers yielded by the iterable a, none of them match because character "8" is not the same as number 8 When you try and compare a character x eg "8" with the elements of the list b, none of them match because character "8" is not the same as number 8 When you try and compare a character x eg "8" with the string representation of the list b, you get a match of x "8" to the 25th character of string c which is also "8". -- Denis McMahon, denismfmcmahon at gmail.com From Seymore4Head at Hotmail.invalid Fri Oct 24 19:48:16 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 19:48:16 -0400 Subject: I am out of trial and error again Lists References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 16:27:58 -0700 (PDT), Rustom Mody wrote: >On Saturday, October 25, 2014 4:30:47 AM UTC+5:30, Seymore4Head wrote: >> On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: >> >> name="123-xyz-abc" >> a=range(10) >> b=list(range(10)) >> c=str(list(range(10))) >> print ("a",(a)) >> print ("b",(b)) >> print ("c",(c)) >> >> for x in name: >> if x in a: >> print ("a",(x)) >> if x in b: >> print ("b",(x)) >> if x in c: >> print ("c",(x)) >> >> B is type list and C is type str. >> I guess I am still a little too thick. I would expect b and c to >> work. > >Lets simplify the problem a bit. >Do all the following in interpreter window > >>>> name="012" >>>> b=list(range(3)) > >>>> for x in name: print x > >>>> for x in b: print x > >Same or different? > >Now go back to Denis' nice example and put in type(x) >into each print > >Same or different? First. The interpreter is not good for me to use even when I am using Python 3 because I forget to add : and I forget to put () around the print statements. To keep me from having to correct myself every time I use it, it is just easier to make a short py file. Here is mine: name="012" b=list(range(3)) for x in name: print (x) print (type (x)) for x in b: print (x) print (type (b)) I don't understand what I was supposed to learn from that. I know that name will be a string so x will be a string. I would still think if you compare a 1 from a string to a 1 from a list, it should be the same. Obviously I am wrong, but we knew that already. I get they are not the same, but I still think they should be. name="012" b=list(range(3)) print (name[1]) print ([1]) 1 [1] OK I get it. They are not the same. I was expecting "1" From Seymore4Head at Hotmail.invalid Fri Oct 24 19:48:58 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 19:48:58 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 23:21:43 +0000 (UTC), Denis McMahon wrote: >On Fri, 24 Oct 2014 16:58:00 -0400, Seymore4Head wrote: > >> I make lots of typing mistakes. It is not that. Did you see the short >> example I posted? >> >> name="123-xyz-abc" >> for x in name: >> if x in range(10): >> print ("Range",(x)) >> if x in str(range(10)): >> print ("String range",(x)) >> >> It doesn't throw an error but it doesn't print what you would expect. > >It prints exactly what I expect. > >Try the following: > >print(str(range(10)), type(str(range(10)))) >print(str(list(range(10))), type(str(listr(range(10))))) > >In python 3, str(x) just wraps x up and puts it in a string. range(x) >generates an iterable range object. > >hence str(range(10)) is a string telling you that range(10) is an iterable >range object with certain boundaries. > >However, list(iterable) expands the iterable to the full list of possible >values, so str(list(range(10))) is a string representation of the list >containing the values that the iterable range(10) creates. > >Note that whether you're looking at a string representation of a value or >the value itself is a lot clearer in the interpreter console where >strings are displayed with quotes. I get it now. Thanks From Seymore4Head at Hotmail.invalid Fri Oct 24 19:57:42 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 19:57:42 -0400 Subject: I am out of trial and error again Lists References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 19:48:16 -0400, Seymore4Head wrote: >On Fri, 24 Oct 2014 16:27:58 -0700 (PDT), Rustom Mody > wrote: > >>On Saturday, October 25, 2014 4:30:47 AM UTC+5:30, Seymore4Head wrote: >>> On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: >>> >>> name="123-xyz-abc" >>> a=range(10) >>> b=list(range(10)) >>> c=str(list(range(10))) >>> print ("a",(a)) >>> print ("b",(b)) >>> print ("c",(c)) >>> >>> for x in name: >>> if x in a: >>> print ("a",(x)) >>> if x in b: >>> print ("b",(x)) >>> if x in c: >>> print ("c",(x)) >>> >>> B is type list and C is type str. >>> I guess I am still a little too thick. I would expect b and c to >>> work. >> >>Lets simplify the problem a bit. >>Do all the following in interpreter window >> >>>>> name="012" >>>>> b=list(range(3)) >> >>>>> for x in name: print x >> >>>>> for x in b: print x >> >>Same or different? >> >>Now go back to Denis' nice example and put in type(x) >>into each print >> >>Same or different? > >First. The interpreter is not good for me to use even when I am using >Python 3 because I forget to add : and I forget to put () around the >print statements. > >To keep me from having to correct myself every time I use it, it is >just easier to make a short py file. > >Here is mine: > >name="012" >b=list(range(3)) >for x in name: print (x) >print (type (x)) >for x in b: print (x) >print (type (b)) > >I don't understand what I was supposed to learn from that. I know >that name will be a string so x will be a string. >I would still think if you compare a 1 from a string to a 1 from a >list, it should be the same. > >Obviously I am wrong, but we knew that already. >I get they are not the same, but I still think they should be. > >name="012" >b=list(range(3)) >print (name[1]) >print ([1]) > >1 >[1] > >OK I get it. They are not the same. I was expecting "1" > Wait! I don't get it. name="012" b=list(range(3)) print (name[1]) print (b[1]) 1 1 I forgot the b From Seymore4Head at Hotmail.invalid Fri Oct 24 20:15:02 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 20:15:02 -0400 Subject: I am out of trial and error again Lists References: Message-ID: On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: name="012" b=list(range(3)) print (name[1]) print (b[1]) if name[1] == b[1]: print ("Eureka!") else: print ("OK, I get it") From python at mrabarnett.plus.com Fri Oct 24 20:20:53 2014 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 25 Oct 2014 01:20:53 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> Message-ID: <544AECE5.50606@mrabarnett.plus.com> On 2014-10-25 00:57, Seymore4Head wrote: [snip] > Wait! I don't get it. > name="012" > b=list(range(3)) > print (name[1]) > print (b[1]) > 1 > 1 > > I forgot the b > If you print the int 1, you'll see: 1 If you print the string "1", you'll see: 1 Normally you want it to print only the characters of the string. Think how annoying it would be if every time you printed a string it appeared in quotes: >>> print("Hello world!") 'Hello world!' How could you print just the text: Hello world! No, it's better that it prints the characters of the string. One function you can use is repr: x = 1 y = "1" print(repr(x)) print(repr(y)) This will print: 1 '1' OK, now it's clear that x is an int and y is a string. From tjreedy at udel.edu Fri Oct 24 20:27:03 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 24 Oct 2014 20:27:03 -0400 Subject: I am out of trial and error again Lists In-Reply-To: <4hkl4app29cjecaiadi9fe6e8tgttl3os6@4ax.com> References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <526127b6-4f00-4040-9c11-6fc172bce952@googlegroups.com> <9k1l4a13av05ejjjpl319onkrgi37qma22@4ax.com> <4hkl4app29cjecaiadi9fe6e8tgttl3os6@4ax.com> Message-ID: On 10/24/2014 6:27 PM, Seymore4Head wrote: > I promise I am not trying to frustrate anyone. I know I have. Seymore, if you want to learn real Python, download and install 3.4.2 and either use the Idle Shell and Editor or the interactive console interpreter and a decent programmer editor. I cannot recommend CodeSkulptor to anyone. The opening statement # CodeSkulptor runs Python programs is deceptive. CodeSkulptor Python is not Python. It does not correspond to any x.y version of Python. It is a somewhat crippled subset of ancient Python (2.1) with selected additions of later features. It does not have exceptions, raise, and try: except:. These are an essential part of original Python and Python today It does not have complex (maybe introduced in 1.5) and unicode (introduced in 2.0). Let that pass. More important, it does not have new-style classes, an essential new feature introduced in 2.2. Python beginners should start with unified new-styled classes. If lucky, they need never learn about the original old style, dis-unified type versus class system that started going away in 2.2, is mostly gone in 2.7. and completely gone in 3.0. If you really want to continue with CodeSkulpter Python, you should find a CodeSkulpterPython list. You cannot expect people here to know that legal code like class I(int): pass will not run, but will fail with an exceeding cryptic message: Line 1: undefined: TypeError: a.$d is undefined Nor can you expect us to know all the other limitations. This is a list for Python. If you want help here, get and use a real Python interpreter, with a proper interactive mode, as multiple people have suggested. -- Terry Jan Reedy From Seymore4Head at Hotmail.invalid Fri Oct 24 20:37:21 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 20:37:21 -0400 Subject: I am out of trial and error again Lists References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> Message-ID: On Sat, 25 Oct 2014 01:20:53 +0100, MRAB wrote: >On 2014-10-25 00:57, Seymore4Head wrote: >[snip] >> Wait! I don't get it. >> name="012" >> b=list(range(3)) >> print (name[1]) >> print (b[1]) >> 1 >> 1 >> >> I forgot the b >> >If you print the int 1, you'll see: > >1 > >If you print the string "1", you'll see: > >1 > >Normally you want it to print only the characters of the string. Think >how annoying it would be if every time you printed a string it appeared >in quotes: > > >>> print("Hello world!") >'Hello world!' > >How could you print just the text: > >Hello world! > >No, it's better that it prints the characters of the string. > >One function you can use is repr: > >x = 1 >y = "1" >print(repr(x)) >print(repr(y)) > >This will print: > >1 >'1' > >OK, now it's clear that x is an int and y is a string. Yes x = 123 y = "123" z = [1,2,3] print(repr(x)) print(repr(y)) print(repr(z)) 123 '123' [1, 2, 3] Thanks From Seymore4Head at Hotmail.invalid Fri Oct 24 20:42:30 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 20:42:30 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <526127b6-4f00-4040-9c11-6fc172bce952@googlegroups.com> <9k1l4a13av05ejjjpl319onkrgi37qma22@4ax.com> <4hkl4app29cjecaiadi9fe6e8tgttl3os6@4ax.com> Message-ID: On Fri, 24 Oct 2014 20:27:03 -0400, Terry Reedy wrote: >On 10/24/2014 6:27 PM, Seymore4Head wrote: > >> I promise I am not trying to frustrate anyone. I know I have. > >Seymore, if you want to learn real Python, download and install 3.4.2 >and either use the Idle Shell and Editor or the interactive console >interpreter and a decent programmer editor. > >I cannot recommend CodeSkulptor to anyone. The opening statement ># CodeSkulptor runs Python programs >is deceptive. CodeSkulptor Python is not Python. It does not correspond >to any x.y version of Python. It is a somewhat crippled subset of >ancient Python (2.1) with selected additions of later features. It does >not have exceptions, raise, and try: except:. These are an essential >part of original Python and Python today It does not have complex >(maybe introduced in 1.5) and unicode (introduced in 2.0). Let that >pass. More important, it does not have new-style classes, an essential >new feature introduced in 2.2. Python beginners should start with >unified new-styled classes. If lucky, they need never learn about the >original old style, dis-unified type versus class system that started >going away in 2.2, is mostly gone in 2.7. and completely gone in 3.0. > >If you really want to continue with CodeSkulpter Python, you should find >a CodeSkulpterPython list. You cannot expect people here to know that >legal code like > class I(int): pass >will not run, but will fail with an exceeding cryptic message: > Line 1: undefined: TypeError: a.$d is undefined >Nor can you expect us to know all the other limitations. > >This is a list for Python. If you want help here, get and use a real >Python interpreter, with a proper interactive mode, as multiple people >have suggested. OK. I will. Thanks But the difference between Python 2 and Codeskulptor was not an issue with this question. From cs at zip.com.au Fri Oct 24 20:52:21 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 25 Oct 2014 11:52:21 +1100 Subject: I am out of trial and error again Lists In-Reply-To: References: Message-ID: <20141025005221.GA39108@cskk.homeip.net> On 24Oct2014 20:37, Seymore4Head wrote: >On Sat, 25 Oct 2014 01:20:53 +0100, MRAB >>One function you can use is repr: >> >>x = 1 >>y = "1" >>print(repr(x)) >>print(repr(y)) >> >>This will print: >> >>1 >>'1' >> >>OK, now it's clear that x is an int and y is a string. > >Yes In particular, Python's interactive mode uses repr to print the result of any expression that whose value was not None: [/Users/cameron]fleet*> python Python 2.7.8 (default, Oct 3 2014, 02:34:26) [GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> x=1 >>> y='1' >>> x 1 >>> y '1' >>> so you get this for free in that mode. Cheers, Cameron Simpson If your new theorem can be stated with great simplicity, then there will exist a pathological exception. - Adrian Mathesis From dreamsmediasolutions2014 at gmail.com Fri Oct 24 21:31:30 2014 From: dreamsmediasolutions2014 at gmail.com (dreams media Solution) Date: Fri, 24 Oct 2014 18:31:30 -0700 (PDT) Subject: Best Jobb Oriented Web Designig Course Institute in Hyderabad Message-ID: <02777301-64c2-4f40-a5e2-ad2cf0050c8b@googlegroups.com> In Web Designing course, students will learn how to develop a rich look web site. We will explain design principles in Photoshop. In Photoshop we will train you, how to develop logos, icons, banners. We will explain animation principles in flash. In Flash we will train you how to develop animated ads, logos, banners. Dreams Media Solutions is One of the Best Web Designing Training Institute in Hyderabad and We aso Provides PHPTraining,Autocad Training Also. For more details: http://www.dreamsmediasolutions.com/software-courses/web-designing-course-in-ameerpet/ From habukaff50 at yahoo.com Fri Oct 24 21:47:42 2014 From: habukaff50 at yahoo.com (heba abukaff) Date: Fri, 24 Oct 2014 18:47:42 -0700 Subject: python student at university of jordan. Message-ID: <1414201662.32895.YahooMailBasic@web122901.mail.ne1.yahoo.com> Hi, my name is heba ibrahim abukaff from jordan ,iam a computer information system student at university of jordan . i have a trouble using the tokenizer to find the frequency list for URL using arabic text.and iam using python 2.7.2 on winXP,I tried this code but every time i run the code appears error with first line COULD YOU HELP ME. WITH REGARDS. :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32 > import re, codecs import nltk from urllib import request url = "http://ar.wikipedia.org/wiki/%D9%85%D9%88%D9%82%D8%B9_%D9%88%D9%8A%D8%A8" response = request.urlopen(url) raw = response.read().decode('utf8') print(raw) import re, codecs import nltk from nltk.probability import * def construct_frequency_list(words): outfile = codecs.open(r'raw.txt' , 'w') fd = nltk.probability.FreqDist() for w in words: fd.inc(w) print "Total number of words: %d Vocbulary size : %d" % (fd.N(), fd.B()) print "word with highest count: %s" % (fd.max()) tokenlist = fd.iteritems() for (key, value) in tokenlist: print>>outfile, "%s\t%d" % (key, value) outfile.close() def read_textfile(raw ): lines = codecs.open(raw ,'r','utf_8').readlines() outfile = codecs.open(r'raw.txt' ,'w','utf_8') counter = 0 wordlist = [] for line in lines: tokens = line.rstrip().lstrip().split() for t in tokens: wordlist.append(t) print>>outfile, '%s\t%d' % (t, len(t)) counter += len(t) outfile.close() return wordlist if __name__ == "__main__": words = read_textfile(r'raw .txt') construct_frequency_list(words) print "Done!" From rosuav at gmail.com Fri Oct 24 22:06:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 25 Oct 2014 13:06:40 +1100 Subject: python student at university of jordan. In-Reply-To: <1414201662.32895.YahooMailBasic@web122901.mail.ne1.yahoo.com> References: <1414201662.32895.YahooMailBasic@web122901.mail.ne1.yahoo.com> Message-ID: On Sat, Oct 25, 2014 at 12:47 PM, heba abukaff wrote: > i have a trouble using the tokenizer to find the frequency list for URL using arabic text.and iam using python 2.7.2 on winXP,I tried this code but every time i run the code appears error with first line I'm seeing two problems here. One of them may not actually be a problem in your code, but just in how you're posting: your text has all been rewrapped. Post the exact code, as plain text (not HTML); you should be able to do this, but if you can't with Yahoo, try a different email provider. Make sure we can see exactly where your code begins and ends, so we can understand what "first line" you're looking at - and if you copy and paste the actual error you get, that would be extremely helpful, too. (Even if it's in Arabic. There'll be parts we can understand.) The second problem is that you're trying to work with non-English text in Python 2.7. This is harder than it needs to be. Install the latest Python (3.4) and use that instead of 2.7; the NLTK module is compatible with 3.2+, so it should work fine. I can't be sure that you're having trouble with bytes vs strings, because I can't see what your code's doing (due to the wrap/indent problem), but in any case, shifting to Python 3 gives you a much better chance of getting things right. All you'll need to do, I suspect, is change your print statements into function calls: # Old style: print "word with highest count: %s" % (fd.max()) # New style: print("word with highest count: %s" % (fd.max())) Easy! And only slightly harder when you send it to a different destination: # Old style: print>>outfile, '%s\t%d' % (t, len(t)) # New style: print('%s\t%d' % (t, len(t)), file=outfile) With those changes, your code will probably (I can't test it) work on Python 3.4. ChrisA From orgnut at yahoo.com Fri Oct 24 22:16:21 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Fri, 24 Oct 2014 19:16:21 -0700 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On 10/24/2014 07:38 AM, Seymore4Head wrote: > I do get the difference. I don't actually use Python 2. I use > CodeSkulptor. I do have Python 3 installed. Actually I have Python 2 > installed but IDLE defaults to Python 3. So it is a pain to actually > load Python 2. > Exactly HOW are you trying to run Idle? A default install of Py2 and Py3 in Windows should have also installed Idle for each version. In my Win7 system, they are BOTH in the standard menu, you should be able to call up either one. OT: Side comment: I rarely use Windows these days, maybe once every two or three months -- I MUCH prefer Linux. Among other reasons its a far better environment for programming. I only have one (active) system with Windows installed, and two others with Linux only. Actually make that three, if you count my Raspberry Pi. :-) -=- Larry -=- From Seymore4Head at Hotmail.invalid Fri Oct 24 22:41:06 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 24 Oct 2014 22:41:06 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Fri, 24 Oct 2014 19:16:21 -0700, Larry Hudson wrote: >On 10/24/2014 07:38 AM, Seymore4Head wrote: > >> I do get the difference. I don't actually use Python 2. I use >> CodeSkulptor. I do have Python 3 installed. Actually I have Python 2 >> installed but IDLE defaults to Python 3. So it is a pain to actually >> load Python 2. >> > >Exactly HOW are you trying to run Idle? A default install of Py2 and Py3 in Windows should have >also installed Idle for each version. In my Win7 system, they are BOTH in the standard menu, >you should be able to call up either one. > >OT: Side comment: I rarely use Windows these days, maybe once every two or three months -- I >MUCH prefer Linux. Among other reasons its a far better environment for programming. I only >have one (active) system with Windows installed, and two others with Linux only. Actually make >that three, if you count my Raspberry Pi. :-) > > -=- Larry -=- I have a directory of my py files. I right click on one of the py files and "open with IDLE" Windows XP If I try to open a py file I have for Python 2 it still opens using IDLE 3. I don't have many py 2 files anyway. From cs at zip.com.au Fri Oct 24 23:05:30 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 25 Oct 2014 14:05:30 +1100 Subject: python student at university of jordan. In-Reply-To: References: Message-ID: <20141025030530.GA87967@cskk.homeip.net> On 25Oct2014 13:06, Chris Angelico wrote: >On Sat, Oct 25, 2014 at 12:47 PM, heba abukaff > wrote: >> i have a trouble using the tokenizer to find the frequency list for URL using arabic text.and iam using python 2.7.2 on winXP,I tried this code but every time i run the code appears error with first line > >I'm seeing two problems here. One of them may not actually be a >problem in your code, but just in how you're posting: your text has >all been rewrapped. Post the exact code, as plain text (not HTML); you >should be able to do this, but if you can't with Yahoo, try a >different email provider. Looking at his post via python-list, he _did_ post in plain text. There's no HTML at all. >Make sure we can see exactly where your code >begins and ends, so we can understand what "first line" you're looking >at - and if you copy and paste the actual error you get, that would be >extremely helpful, too. (Even if it's in Arabic. There'll be parts we >can understand.) This, OTOH, yes. Heba, could you post the error message please? The complete message, including the stack trace lines if any. Cheers, Cameron Simpson From rosuav at gmail.com Fri Oct 24 23:22:14 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 25 Oct 2014 14:22:14 +1100 Subject: python student at university of jordan. In-Reply-To: <20141025030530.GA87967@cskk.homeip.net> References: <20141025030530.GA87967@cskk.homeip.net> Message-ID: On Sat, Oct 25, 2014 at 2:05 PM, Cameron Simpson wrote: >> I'm seeing two problems here. One of them may not actually be a >> problem in your code, but just in how you're posting: your text has >> all been rewrapped. Post the exact code, as plain text (not HTML); you >> should be able to do this, but if you can't with Yahoo, try a >> different email provider. > > > Looking at his post via python-list, he _did_ post in plain text. There's no > HTML at all. Plain text is all that got through to us, but I suspect that possibly he had an HTML version that got stripped somewhere along the way. Either that, or the code that we're looking at really is what's in his .py file, in which case the first line is the version marker - no wonder it's failing. ChrisA From rustompmody at gmail.com Fri Oct 24 23:46:57 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 20:46:57 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> Message-ID: On Saturday, October 25, 2014 5:21:01 AM UTC+5:30, Seymore4Head wrote: > On Fri, 24 Oct 2014 16:27:58 -0700 (PDT), Rustom Mody wrote: > > >On Saturday, October 25, 2014 4:30:47 AM UTC+5:30, Seymore4Head wrote: > >> On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head wrote: > >> > >> name="123-xyz-abc" > >> a=range(10) > >> b=list(range(10)) > >> c=str(list(range(10))) > >> print ("a",(a)) > >> print ("b",(b)) > >> print ("c",(c)) > >> > >> for x in name: > >> if x in a: > >> print ("a",(x)) > >> if x in b: > >> print ("b",(x)) > >> if x in c: > >> print ("c",(x)) > >> > >> B is type list and C is type str. > >> I guess I am still a little too thick. I would expect b and c to > >> work. > > > >Lets simplify the problem a bit. > >Do all the following in interpreter window > > > >>>> name="012" > >>>> b=list(range(3)) > > > >>>> for x in name: print x > > > >>>> for x in b: print x > > > >Same or different? > > > >Now go back to Denis' nice example and put in type(x) > >into each print > > > >Same or different? > > First. The interpreter is not good for me to use even when I am using > Python 3 because I forget to add : and I forget to put () around the > print statements. > What would you say to a person who - Buys a Lambhorgini - Hitches a horse (or bullock) to it - Moans how clumsily slow it is. ?? In case you dont get it: - the interpreter is one of the factors that puts python into the hi-end class. - the bullock/horse class is the C/Java type language where you always need to work through files Here is my list of points of sliding for bullock category to Lambhorgini: http://blog.languager.org/2012/10/functional-programming-lost-booty.html ['Interpreter' is called 'REPL' there] > To keep me from having to correct myself every time I use it, it is > just easier to make a short py file. Yes the intention is right, The implementation is wrong. Programmers consider it a virtue to be lazy. But you have to put it some work to learn to be lazy in an effective way And currently you are being lazy on the wrong front. Hints: 1. A good programmer tries out things at the interpreter ONE LINE AT A TIME 2. What he tries out are usually EXPRESSIONS like eg str(list(range(10))) And not STATEMENTS like if x in name: print x 3. IOW a good programmer rarely needs to type a colon at the interpreter 4. The least useful statement to try at the interpreter is print. From rustompmody at gmail.com Sat Oct 25 00:09:44 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 21:09:44 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> Message-ID: <25c6a468-e596-4a31-856b-bb5fe22c8894@googlegroups.com> On Saturday, October 25, 2014 9:17:12 AM UTC+5:30, Rustom Mody wrote: > 4. The least useful statement to try at the interpreter is print. Yeah this is python2 thinking; in python 3, print is technically an expression. From ben+python at benfinney.id.au Sat Oct 25 00:25:33 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 25 Oct 2014 15:25:33 +1100 Subject: I am out of trial and error again Lists References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> <25c6a468-e596-4a31-856b-bb5fe22c8894@googlegroups.com> Message-ID: <8538ac4vya.fsf@benfinney.id.au> Rustom Mody writes: > On Saturday, October 25, 2014 9:17:12 AM UTC+5:30, Rustom Mody wrote: > > 4. The least useful statement to try at the interpreter is print. > > Yeah this is python2 thinking; in python 3, print is technically an > expression. This is wrong thinking. In Python 3, print is a function. -- \ ?[W]hoever is able to make you absurd is able to make you | `\ unjust.? ?Voltaire | _o__) | Ben Finney From steve+comp.lang.python at pearwood.info Sat Oct 25 00:33:59 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 25 Oct 2014 15:33:59 +1100 Subject: python student at university of jordan. References: Message-ID: <544b2838$0$12975$c3e8da3$5496439d@news.astraweb.com> heba abukaff wrote: > Hi, > my name is heba ibrahim abukaff from jordan ,iam a computer information > system student at university of jordan . i have a trouble using the > tokenizer to find the frequency list for URL using arabic text.and iam > using python 2.7.2 on winXP,I tried this code but every time i run the > code appears error with first line COULD YOU HELP ME. We can only help you if you help us. We cannot guess the error that you get, you have to show us. Copy and paste the complete error message, starting from the word "Traceback" to the end. Given the code you showed: [quote] > import re, codecs import nltk [end quote] Notice the greater-than sign > at the beginning of the "import re, codecs" line? If that greater-than sign is actually in your program, you would get a syntax error: py> > import re, codecs File "", line 1 > import re, codecs ^ SyntaxError: invalid syntax If that is not the error message you are getting, you will need to tell us what error you actually are getting. Regards, -- Steven From steve+comp.lang.python at pearwood.info Sat Oct 25 01:03:16 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 25 Oct 2014 16:03:16 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> Message-ID: <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> alister wrote: > On Fri, 24 Oct 2014 10:20:30 -0700, Dan Stromberg wrote: > >> On Fri, Oct 24, 2014 at 1:38 AM, Steven D'Aprano >> wrote: >>> I don't get why that's considered hard to read. >> >>> So why is it hard to read when the index is a flag? >>> >>> value = [f, g][cond]() >> [Dan] >> It's clear to you, it's clear to me, but is it clear to everyone? I >> very much doubt it. Of course it won't be clear to *everyone* but it should be clear enough to people who are familiar with standard Python idioms. A concrete example should be more obvious than the fake example: title = ('Mr', 'Ms')[person.sex == 'F'] which should be clear to anyone who understands indexing in Python and that True == 1 and False == 0. Although that's probably better written as a dict lookup: title = {'M': 'Mr', 'F': 'Ms'}[person.sex] which is then more easily extended to support intersex and non-traditional[1] gender identities. Better still is to allow the individual to choose their own title (Dr, Prof, Mrs, Miss, Mx, Sir, Dame, etc.) rather than calculate it from their sex, but that's moving away from the point I am making that this idiom isn't some weird and hackish bizarrity. We use list indexing and key lookup all the time, this is just a special case of the same. It's no more hackish than: mapping = {True: "something which is factual", False: "something which people prefer to believe"} value = mapping[flag] [Alister] > I had to mentally step through this before it became apparent what it was > doing, can see places where it could be usefull (a switch replacement) > but it is not instantly obvious Very little code is instantly obvious. Even when you know what the syntax means, you still have to understand the semantics, and sometimes that's far from obvious. > a = if else > > is instantly obvious (at least to a native English speaker anyway) Ha! And yet people have, and continue to, complain *bitterly* about the non-standard ordering of Python's ternary if, compared to C, standard if...else syntax, and English. "If the syntax is like C, then people will use it, or else they will complain that the syntax is incomprehensible." Personally, I don't accept or agree with such complaints. Python's ternary if follows the same syntax as this English variant: "People will use it if the syntax is like C, or else they will complain that the syntax is incomprehensible." Still, English-like though it is, Python's ternary if does violate the expectations of those who expect the condition to come first, as the standard if...else block does. [Dan] >> Also, you've gone to the trouble of def'ing two functions here - you may >> as well do a function for the if/else. Not every one-liner expression needs to go into a function. [1] For Western Christian definitions of traditional. Other cultures have traditionally recognised more than just a binary state of gender and sexuality, e.g. https://en.wikipedia.org/wiki/Hijra_%28South_Asia%29 -- Steven From rosuav at gmail.com Sat Oct 25 01:25:59 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 25 Oct 2014 16:25:59 +1100 Subject: (test) ? a:b In-Reply-To: <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Oct 25, 2014 at 4:03 PM, Steven D'Aprano wrote: > Ha! And yet people have, and continue to, complain *bitterly* about the > non-standard ordering of Python's ternary if, compared to C, standard > if...else syntax, and English. > > "If the syntax is like C, then people will use it, or else they will > complain that the syntax is incomprehensible." > > Personally, I don't accept or agree with such complaints. Python's ternary > if follows the same syntax as this English variant: > > "People will use it if the syntax is like C, or else they will complain that > the syntax is incomprehensible." Partly, I think this is a difference between programming and pure mathematics. In algebra, there's operator precedence, but no order of evaluation; in programming, there's both: https://docs.python.org/3/reference/expressions.html#evaluation-order In English, there's not really a concept of order of evaluation either. "People will use it" doesn't need to be evaluated separately from "if the syntax is like C". But in Python, the if/else operator mucks up the general principle that an expression will be evaluated left-to-right, because it's evaluated middle-to-outer for that one operator. Messing with internal expectations, even if it's following some external logic like English grammar, will confuse people. ChrisA From rustompmody at gmail.com Sat Oct 25 01:40:33 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 22:40:33 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> <25c6a468-e596-4a31-856b-bb5fe22c8894@googlegroups.com> Message-ID: <9dd6db37-5568-405e-8af7-3a28195eec4d@googlegroups.com> On Saturday, October 25, 2014 9:56:02 AM UTC+5:30, Ben Finney wrote: > Rustom Mody writes: > > > On Saturday, October 25, 2014 9:17:12 AM UTC+5:30, Rustom Mody wrote: > > > 4. The least useful statement to try at the interpreter is print. > > > > Yeah this is python2 thinking; in python 3, print is technically an > > expression. > > This is wrong thinking. In Python 3, print is a function. [tl;dr at bottom] Ok I was a bit sloppy -- should have said 'the print' But there was no specific prior use that 'the' would refer to. So one could say (if you like!): | | Python 2 | Python 3 | | print | syntax | function | | print(x) | statement | expression | I was really talking of the second row not the first So much for being legalistic -- An approach which is ultimately not helpful. For one thing function is one kind of expression ie its a subset not a disjoint relation. More important (in this case) its bad pedagogy. Its generally accepted that side-effecting functions are not a good idea -- typically a function that returns something and changes global state. In that sense its best to think of print(x) as syntactically an expression, semantically a statement. Or put differently, the following error is more poorly reported in python3 than in python2 Python 2.7.8 (default, Oct 7 2014, 17:59:21) [GCC 4.9.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 2 + (print 2) File "", line 1 2 + (print 2) ^ SyntaxError: invalid syntax Python 3.4.2 (default, Oct 8 2014, 10:45:20) [GCC 4.9.1] on linux Type "help", "copyright", "credits" or "license" for more information. >>> 2 + (print (2)) 2 Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' ========= tl;dr I dont think all this is very helpful to Seymore From rosuav at gmail.com Sat Oct 25 01:49:12 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 25 Oct 2014 16:49:12 +1100 Subject: I am out of trial and error again Lists In-Reply-To: <9dd6db37-5568-405e-8af7-3a28195eec4d@googlegroups.com> References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> <25c6a468-e596-4a31-856b-bb5fe22c8894@googlegroups.com> <9dd6db37-5568-405e-8af7-3a28195eec4d@googlegroups.com> Message-ID: On Sat, Oct 25, 2014 at 4:40 PM, Rustom Mody wrote: > Its generally accepted that side-effecting functions are not a good idea > -- typically a function that returns something and changes global state. Only in certain circles. Not in Python. There are large numbers of functions with side effects (mutator methods like list.append, anything that needs lots of state like random.random, everything with external effect like I/O, heaps of stuff), and it is most definitely not frowned upon. In Python 3 (or Python 2 with the future directive), print is a function, print() an expression. It's not "semantically a statement". ChrisA From rustompmody at gmail.com Sat Oct 25 01:55:59 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 24 Oct 2014 22:55:59 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> <25c6a468-e596-4a31-856b-bb5fe22c8894@googlegroups.com> <9dd6db37-5568-405e-8af7-3a28195eec4d@googlegroups.com> Message-ID: On Saturday, October 25, 2014 11:20:03 AM UTC+5:30, Chris Angelico wrote: > On Sat, Oct 25, 2014 at 4:40 PM, Rustom Mody wrote: > > Its generally accepted that side-effecting functions are not a good idea > > -- typically a function that returns something and changes global state. > > Only in certain circles. Not in Python. There are large numbers of > functions with side effects (mutator methods like list.append, > anything that needs lots of state like random.random, everything with > external effect like I/O, heaps of stuff), and it is most definitely > not frowned upon. > > In Python 3 (or Python 2 with the future directive), print is a > function, print() an expression. It's not "semantically a statement". Ok So give me a valid (ie useful) use where instead of the usual l=[1,2,3] l.append(4) we have foo(l.append(4)) From rosuav at gmail.com Sat Oct 25 02:03:48 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 25 Oct 2014 17:03:48 +1100 Subject: I am out of trial and error again Lists In-Reply-To: References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> <25c6a468-e596-4a31-856b-bb5fe22c8894@googlegroups.com> <9dd6db37-5568-405e-8af7-3a28195eec4d@googlegroups.com> Message-ID: On Sat, Oct 25, 2014 at 4:55 PM, Rustom Mody wrote: > So give me a valid (ie useful) use where instead of the usual > l=[1,2,3] > l.append(4) > > we have > > foo(l.append(4)) Given that l.append(4) will always return None, there's not a lot of point passing that return value to something, unless you're doing this inside a lambda or something dumb like that. It won't be Pythonic. Your point? ChrisA From orgnut at yahoo.com Sat Oct 25 02:04:00 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Fri, 24 Oct 2014 23:04:00 -0700 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> Message-ID: On 10/24/2014 09:37 AM, Seymore4Head wrote: > import string Not needed, delete it. > def nametonumber(name): > lst=[] > nx=[] > digit=[] Not needed. You create digit as an empty list, them immediately follow by assigning a string to it (NOT a _list_ of characters, but an actual string.) > digit="".join(str(i) for i in range(10)) digit is now the _string_ "0123456789". Actually, a direct assignment here would be easier and shorter; digit = "0123456789" > for x in name: > lst.append(x) lst is now a list of the characters in name. That works, but you can do the same thing with: lst = list(name) > for y in (lst): Parentheses not needed. > if y in lst(range(1,10)): This is the line the traceback is referring to. lst is a list, but the parentheses tell Python you are trying to call it as a function. That is what the "TypeError: 'list' object is not callable" means. Also it seems you are now trying to make a list of the digits 1-9 without the zero. Is this what you want? I don't think so, but if that IS what you want you can do it easier with slicing (look it up, VERY useful): (Remember, digit is already a string of the ten digits, with zero as the first character.) if y in digit[1:]: Otherwise if you do want zero included you simply need: if y in digit: > #if y in "1234567890": > #if y.isdigit(): > #if y in digit: All of those should work, with the zero. > #if y in string.digits: Ok (I think?), but the string module is effectively obsolete -- most of its capabilities have been replaced with newer, better string methods. It is RARELY useful. I have never used it myself so don't know too much about it. It is definitely not needed here, and is why I suggested deleting the import. > nx.append(y) > ... -=- Larry -=- From orgnut at yahoo.com Sat Oct 25 02:46:08 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Fri, 24 Oct 2014 23:46:08 -0700 Subject: I am out of trial and error again Lists In-Reply-To: References: <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> Message-ID: <3IudnRDHO76s2tbJnZ2dnUU7-VednZ2d@giganews.com> On 10/24/2014 12:07 PM, Seymore4Head wrote: > On Fri, 24 Oct 2014 19:40:39 +0100, Mark Lawrence >> How many more times, state what you expect to happen and what actually >> happens. "doesn't work" is useless. Please read this http://sscce.org/ > > Good suggestion. > OK how is this? > It doesn't print what I expect. That is NO different from the useless crap you consistently give us! Tell us EXACTLY WHAT YOU EXPECT!! > Does it print what you expect? Yes it does. But what I expect is different from what you (erroneously) expect. > name="123-xyz-abc" > for x in name: > if x in range(10): x is a character (a one-element string). range(10) is a list of ints. A string will never match an int. BTW, as it is used here, range(10) is for Py2, for Py3 it needs to be list(range(10)). > print ("Range",(x)) > if x in str(range(10)): Once again, find out what str(range(10)) actually is. It is NOT what you think it is. And I'll reiterate what everyone here keeps telling you: USE THE INTERACTIVE MODE to see what really goes on. If you keep resisting this you are making your understanding several hundred times more difficult. > print ("String range",(x)) Sorry for the harsh tone. I'm old, and the curmudgeon is starting to come out in me. -=- Larry -=- From breamoreboy at yahoo.co.uk Sat Oct 25 03:25:29 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 25 Oct 2014 08:25:29 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On 25/10/2014 03:41, Seymore4Head wrote: > On Fri, 24 Oct 2014 19:16:21 -0700, Larry Hudson > wrote: > >> On 10/24/2014 07:38 AM, Seymore4Head wrote: >> >>> I do get the difference. I don't actually use Python 2. I use >>> CodeSkulptor. I do have Python 3 installed. Actually I have Python 2 >>> installed but IDLE defaults to Python 3. So it is a pain to actually >>> load Python 2. >>> >> >> Exactly HOW are you trying to run Idle? A default install of Py2 and Py3 in Windows should have >> also installed Idle for each version. In my Win7 system, they are BOTH in the standard menu, >> you should be able to call up either one. >> >> OT: Side comment: I rarely use Windows these days, maybe once every two or three months -- I >> MUCH prefer Linux. Among other reasons its a far better environment for programming. I only >> have one (active) system with Windows installed, and two others with Linux only. Actually make >> that three, if you count my Raspberry Pi. :-) >> >> -=- Larry -=- > I have a directory of my py files. I right click on one of the py > files and "open with IDLE" Windows XP > > If I try to open a py file I have for Python 2 it still opens using > IDLE 3. > > I don't have many py 2 files anyway. > How about running your Python 2 version of IDLE and opening your files using File->Open or CTRL-O? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From steve+comp.lang.python at pearwood.info Sat Oct 25 03:44:42 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 25 Oct 2014 18:44:42 +1100 Subject: I am out of trial and error again Lists References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> <25c6a468-e596-4a31-856b-bb5fe22c8894@googlegroups.com> <9dd6db37-5568-405e-8af7-3a28195eec4d@googlegroups.com> Message-ID: <544b54ea$0$13011$c3e8da3$5496439d@news.astraweb.com> Rustom Mody wrote: > On Saturday, October 25, 2014 11:20:03 AM UTC+5:30, Chris Angelico wrote: >> On Sat, Oct 25, 2014 at 4:40 PM, Rustom Mody wrote: >> > Its generally accepted that side-effecting functions are not a good >> > idea -- typically a function that returns something and changes global >> > state. >> >> Only in certain circles. Not in Python. There are large numbers of >> functions with side effects (mutator methods like list.append, >> anything that needs lots of state like random.random, everything with >> external effect like I/O, heaps of stuff), and it is most definitely >> not frowned upon. >> >> In Python 3 (or Python 2 with the future directive), print is a >> function, print() an expression. It's not "semantically a statement". > > Ok > So give me a valid (ie useful) use where instead of the usual > l=[1,2,3] > l.append(4) > > we have > > foo(l.append(4)) Your question seems to be non-sequitor. To me, it doesn't appear to have any relationship to Chris' comments. But to answer your question, Ruby has mutator methods like list.append return the list being mutated, to make it easy to chain multiple calls: l.append(4).reverse().sort() That would make it easy and convenient to modify a list immediately pass the modified list to a function and embed it in an expression: # Python's way l.append(4) values = [1, 2, foo(l), 3] # Pseudo-Ruby way values = [1, 2, foo(l.append(4)), 3] Languages where all values are immutable *by definition* have to return a new list, since you can't modify the original, hence they too can easily be embedded in an expression. Many people try to write something like this: old_lists = [a, b, c, d] new_lists = [thelist.append(x) for thelist in old_lists if len(thelist) < 5] only to be unpleasantly surprised to discover than new_lists now contains None instead of the lists. Having methods return a result rather than behave like a procedure is a valid (i.e. useful) design choice. -- Steven From ned at nedbatchelder.com Sat Oct 25 07:58:14 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sat, 25 Oct 2014 07:58:14 -0400 Subject: (test) ? a:b In-Reply-To: <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/25/14 1:03 AM, Steven D'Aprano wrote: > alister wrote: > >> >On Fri, 24 Oct 2014 10:20:30 -0700, Dan Stromberg wrote: >> > >>> >>On Fri, Oct 24, 2014 at 1:38 AM, Steven D'Aprano >>> >> wrote: >>>> >>>I don't get why that's considered hard to read. >>> >> >>>> >>>So why is it hard to read when the index is a flag? >>>> >>> >>>> >>>value = [f, g][cond]() >>> >> > [Dan] >>> >>It's clear to you, it's clear to me, but is it clear to everyone? I >>> >>very much doubt it. > Of course it won't be clear to*everyone* but it should be clear enough to > people who are familiar with standard Python idioms. A concrete example > should be more obvious than the fake example: > > title = ('Mr', 'Ms')[person.sex == 'F'] > > which should be clear to anyone who understands indexing in Python and that > True == 1 and False == 0. You mention "standard Python idioms." I think this style of conditional-via-indexing is becoming quite uncommon, and is no longer one of the standard Python idioms. This is now in the category of "outdated hack." Yes, its meaning is well-defined by the language. But no, its meaning is not immediately apparent to most of today's Python programmers. Of course, opinions obviously differ. -- Ned Batchelder, http://nedbatchelder.com From roland.hedberg at umu.se Sat Oct 25 09:40:05 2014 From: roland.hedberg at umu.se (Roland Hedberg) Date: Sat, 25 Oct 2014 15:40:05 +0200 Subject: Weird connection problem Message-ID: <8622C927-6AAA-4EC9-81B7-E1C899986CD3@adm.umu.se> When I try to access a URL using requests I always get: socket.error: [Errno 104] Connection reset by peer If I try to access the same URL using curl I get no error message instead I get the page. The same result if I use a web browser like Safari. But, if I use python httplib I also get Errno 104. What gives ? Oh, by the way it?s a HTTPS url. ? Roland ?Being able to think like a child is an important attribute of being an adult? - Eddie Izzard From roland.hedberg at umu.se Sat Oct 25 09:47:52 2014 From: roland.hedberg at umu.se (Roland Hedberg) Date: Sat, 25 Oct 2014 15:47:52 +0200 Subject: Weird connection problem In-Reply-To: <8622C927-6AAA-4EC9-81B7-E1C899986CD3@adm.umu.se> References: <8622C927-6AAA-4EC9-81B7-E1C899986CD3@adm.umu.se> Message-ID: <4DBA630E-21AE-4238-8FE6-80AE280CA588@adm.umu.se> Oh, by the way! To make this more interesting :-/ I saw this behavior on a Linux machine (Ubuntu 14.04 LTS) using Python 2.7.6 if I do the same exercise on a Mac OS X machine also with Python 2.7.6 - no problem what so ever. > 25 okt 2014 kl. 08:40 skrev Roland Hedberg : > > When I try to access a URL using requests I always get: > socket.error: [Errno 104] Connection reset by peer > > If I try to access the same URL using curl I get no error message instead I get the page. > The same result if I use a web browser like Safari. > > But, if I use python httplib I also get Errno 104. > > What gives ? > > Oh, by the way it?s a HTTPS url. > > ? Roland > > ?Being able to think like a child is an important attribute of being an adult? - Eddie Izzard > > -- > https://mail.python.org/mailman/listinfo/python-list ? Roland ?Being able to think like a child is an important attribute of being an adult? - Eddie Izzard From joel.goldstick at gmail.com Sat Oct 25 09:48:29 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sat, 25 Oct 2014 09:48:29 -0400 Subject: Weird connection problem In-Reply-To: <8622C927-6AAA-4EC9-81B7-E1C899986CD3@adm.umu.se> References: <8622C927-6AAA-4EC9-81B7-E1C899986CD3@adm.umu.se> Message-ID: On Sat, Oct 25, 2014 at 9:40 AM, Roland Hedberg wrote: > When I try to access a URL using requests I always get: > socket.error: [Errno 104] Connection reset by peer > > If I try to access the same URL using curl I get no error message instead I get the page. > The same result if I use a web browser like Safari. > > But, if I use python httplib I also get Errno 104. > > What gives ? > > Oh, by the way it?s a HTTPS url. > > ? Roland Is this for any url or a specific one? > -- > https://mail.python.org/mailman/listinfo/python-list -- Joel Goldstick http://joelgoldstick.com From roland.hedberg at umu.se Sat Oct 25 10:01:08 2014 From: roland.hedberg at umu.se (Roland Hedberg) Date: Sat, 25 Oct 2014 16:01:08 +0200 Subject: Weird connection problem In-Reply-To: References: <8622C927-6AAA-4EC9-81B7-E1C899986CD3@adm.umu.se> Message-ID: <2F19160C-FE42-4E9A-BBE7-4F4D08095A63@adm.umu.se> It?s a special HTTPS url and searching further it seems to be a SNI problem talked about here: http://stackoverflow.com/questions/18578439/using-requests-with-tls-doesnt-give-sni-support > 25 okt 2014 kl. 08:48 skrev Joel Goldstick : > > On Sat, Oct 25, 2014 at 9:40 AM, Roland Hedberg wrote: >> When I try to access a URL using requests I always get: >> socket.error: [Errno 104] Connection reset by peer >> >> If I try to access the same URL using curl I get no error message instead I get the page. >> The same result if I use a web browser like Safari. >> >> But, if I use python httplib I also get Errno 104. >> >> What gives ? >> >> Oh, by the way it?s a HTTPS url. >> >> ? Roland > > Is this for any url or a specific one? >> -- >> https://mail.python.org/mailman/listinfo/python-list > > > > -- > Joel Goldstick > http://joelgoldstick.com > -- > https://mail.python.org/mailman/listinfo/python-list ? Roland ?Being able to think like a child is an important attribute of being an adult? - Eddie Izzard From ian.g.kelly at gmail.com Sat Oct 25 09:53:37 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 25 Oct 2014 07:53:37 -0600 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Oct 25, 2014 at 5:58 AM, Ned Batchelder wrote: > You mention "standard Python idioms." I think this style of > conditional-via-indexing is becoming quite uncommon, and is no longer one of > the standard Python idioms. This is now in the category of "outdated hack." I think that's probably true. And even in code written for versions of Python than predate the ternary, I think I've seen the idiom "(cond and [if_true] or [if_false])[0]" more often than the one being discussed -- perhaps because it more closely resembles the format of the C ternary From ian.g.kelly at gmail.com Sat Oct 25 10:17:06 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Sat, 25 Oct 2014 08:17:06 -0600 Subject: I am out of trial and error again Lists In-Reply-To: <3IudnRDHO76s2tbJnZ2dnUU7-VednZ2d@giganews.com> References: <3082ee74-3182-4ea5-9851-2b1326e5b34c@googlegroups.com> <9a1l4athfj10h7r3v69ddo95285n9cjlms@4ax.com> <3IudnRDHO76s2tbJnZ2dnUU7-VednZ2d@giganews.com> Message-ID: On Sat, Oct 25, 2014 at 12:46 AM, Larry Hudson wrote: >> name="123-xyz-abc" >> for x in name: >> if x in range(10): > > x is a character (a one-element string). range(10) is a list of ints. A > string will never match an int. BTW, as it is used here, range(10) is for > Py2, for Py3 it needs to be list(range(10)). The last comment is incorrect. You can do membership tests on a Python 3 range object: >>> range(2, 4) range(2, 4) >>> for i in range(5): ... print(i, i in range(2, 4)) ... 0 False 1 False 2 True 3 True 4 False You can also index them: >>> range(50, 100)[37] 87 slice them: >>> range(0, 100, 2)[:25] range(0, 50, 2) get their length: >>> len(range(25, 75)) 50 search them: >>> range(25, 75).index(45) 20 and generally do most operations that you would expect to be able to do with an immutable sequence type, with the exceptions of concatenation and multiplication. And as I observed elsewhere in the thread, such operations are often more efficient on range objects than by constructing and operating on the equivalent lists. From invalid at invalid.invalid Sat Oct 25 11:01:54 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Sat, 25 Oct 2014 15:01:54 +0000 (UTC) Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On 2014-10-24, Denis McMahon wrote: > On Fri, 24 Oct 2014 10:38:31 -0400, Seymore4Head wrote: > >> Thanks everyone for your suggestions. > > Try loading the following in codeskulptor: > > http://www.codeskulptor.org/#user38_j6kGKgeOMr_0.py No. We[1] aren't intested in whatever Python-like language is implemented in codeskulptor. [1] I know I'm being a bit presumptuous writing the the plural first person rather than the signular. If you _are_ interested in codeskulptor "python" then jump in... -- Grant From ryanshuell at gmail.com Sat Oct 25 12:08:06 2014 From: ryanshuell at gmail.com (ryguy7272) Date: Sat, 25 Oct 2014 09:08:06 -0700 (PDT) Subject: Meetup in NYC? Message-ID: <5f291373-2e6f-494a-9ec4-4f00202aa079@googlegroups.com> Are there any Python professionals in or around NYC who can meetup for an hour or two to help me with a few things? I've been trying to run various Python scripts for a few months now, and I'm not having any success with this stuff at all. Basically, everything built into Python works perfectly fine for me. However, whenever I try to run something like numpy or beautifulsoup, or anything like that, I have all kinds of errors. If anyone could meet for an hour or two, in a Starbucks, and go through a few examples of Python code, it would be great!! I can take you out for a few beers afterwards. From mikelbt at gmail.com Sat Oct 25 13:19:10 2014 From: mikelbt at gmail.com (Mike Beatty) Date: Sat, 25 Oct 2014 10:19:10 -0700 (PDT) Subject: Meetup in NYC? In-Reply-To: <5f291373-2e6f-494a-9ec4-4f00202aa079@googlegroups.com> References: <5f291373-2e6f-494a-9ec4-4f00202aa079@googlegroups.com> Message-ID: There's a metope group for Python in NYC and they have project nights/study groups. You should check them out. http://www.meetup.com/nycpython/ On Saturday, October 25, 2014 11:08:31 AM UTC-5, ryguy7272 wrote: > Are there any Python professionals in or around NYC who can meetup for an hour or two to help me with a few things? I've been trying to run various Python scripts for a few months now, and I'm not having any success with this stuff at all. Basically, everything built into Python works perfectly fine for me. However, whenever I try to run something like numpy or beautifulsoup, or anything like that, I have all kinds of errors. > > If anyone could meet for an hour or two, in a Starbucks, and go through a few examples of Python code, it would be great!! I can take you out for a few beers afterwards. From rustompmody at gmail.com Sat Oct 25 13:24:39 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 25 Oct 2014 10:24:39 -0700 (PDT) Subject: I am out of trial and error again Lists In-Reply-To: <544b54ea$0$13011$c3e8da3$5496439d@news.astraweb.com> References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> <25c6a468-e596-4a31-856b-bb5fe22c8894@googlegroups.com> <9dd6db37-5568-405e-8af7-3a28195eec4d@googlegroups.com> <544b54ea$0$13011$c3e8da3$5496439d@news.astraweb.com> Message-ID: <89e60f4f-8fe4-4393-afd1-f9f698d10bac@googlegroups.com> On Saturday, October 25, 2014 1:15:09 PM UTC+5:30, Steven D'Aprano wrote: > Rustom Mody wrote: > > > On Saturday, October 25, 2014 11:20:03 AM UTC+5:30, Chris Angelico wrote: > >> On Sat, Oct 25, 2014 at 4:40 PM, Rustom Mody wrote: > >> > Its generally accepted that side-effecting functions are not a good > >> > idea -- typically a function that returns something and changes global > >> > state. > >> > >> Only in certain circles. Not in Python. There are large numbers of > >> functions with side effects (mutator methods like list.append, > >> anything that needs lots of state like random.random, everything with > >> external effect like I/O, heaps of stuff), and it is most definitely > >> not frowned upon. > >> > >> In Python 3 (or Python 2 with the future directive), print is a > >> function, print() an expression. It's not "semantically a statement". > > > > Ok > > So give me a valid (ie useful) use where instead of the usual > > l=[1,2,3] > > l.append(4) > > > > we have > > > > foo(l.append(4)) > > Your question seems to be non-sequitor. To me, it doesn't appear to have any > relationship to Chris' comments. I am going to leave undisturbed Seymore's thread for whom these nit-picks are unlikely to be helpful Answer in another one From rustompmody at gmail.com Sat Oct 25 13:27:40 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 25 Oct 2014 10:27:40 -0700 (PDT) Subject: Status of side-effecting functions in python Message-ID: Moved from other (Seymore's) thread where this is perhaps not relevant On Saturday, October 25, 2014 1:15:09 PM UTC+5:30, Steven D'Aprano wrote: > Rustom Mody wrote: > > > On Saturday, October 25, 2014 11:20:03 AM UTC+5:30, Chris Angelico wrote: > >> On Sat, Oct 25, 2014 at 4:40 PM, Rustom Mody wrote: > >> > Its generally accepted that side-effecting functions are not a good > >> > idea -- typically a function that returns something and changes global > >> > state. > >> > >> Only in certain circles. Not in Python. There are large numbers of > >> functions with side effects (mutator methods like list.append, > >> anything that needs lots of state like random.random, everything with > >> external effect like I/O, heaps of stuff), and it is most definitely > >> not frowned upon. > >> > >> In Python 3 (or Python 2 with the future directive), print is a > >> function, print() an expression. It's not "semantically a statement". > > > > Ok > > So give me a valid (ie useful) use where instead of the usual > > l=[1,2,3] > > l.append(4) > > > > we have > > > > foo(l.append(4)) > > Your question seems to be non-sequitor. To me, it doesn't appear to have any > relationship to Chris' comments. | Languages like Pascal (many others)... distinguish function which return | results and procedure which do not... | Extract from https://en.wikipedia.org/wiki/Subroutine#Language_support So my point: Whether the language supports it strongly (Pascal' procedures) weakly (C's void functions) more weakly (Python's None returning functions), the beginning programmer needs this concept as a core thinking tool. Pascal makes this easy -- teach the syntax and the concept will get across Python is harder because the concept does not correlate with any specific syntax But its not all that hard unless the teacher is stuck in correlating core concepts and language syntax. A teacher who is so stuck is cheating the student. My version: "print may (3) or may not (2) be an expression. Just always consider it as a statement" Chris version: print() is an expression. Technically Chris is correct. Is it methodologically/pedagogically it is sound? Consider: >From my explanation this: >>> [print(x) for x in [1,2,3]] 1 2 3 [None, None, None] >>> is in "Dont Do!" category whether python (3) allows it or python 2 doesn't. And you "Dont do" because print(x) is a statement -- literally in python 2; morally in python 3 And from here its only a small step to why l.append(4) should never be used except as a statement. Python may not literally have Pascal's procedures; they are morally there if you choose to 'believe' in them. How would Chris inculcate avoidance of code-smells like - foo(l.append(4)) - [print(x) for x in [1,2,3]] ? No idea! I dare say: about print I dont know but [foo(x) for x in lst] and foo is used for effect not return-value is a rather common code-smell in my experience From Seymore4Head at Hotmail.invalid Sat Oct 25 14:42:10 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sat, 25 Oct 2014 14:42:10 -0400 Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Sat, 25 Oct 2014 14:23:44 -0400, Dennis Lee Bieber wrote: >On Fri, 24 Oct 2014 10:38:31 -0400, Seymore4Head > declaimed the following: > >> >>I do get the difference. I don't actually use Python 2. I use >>CodeSkulptor. I do have Python 3 installed. Actually I have Python 2 >>installed but IDLE defaults to Python 3. So it is a pain to actually >>load Python 2. >> > > So don't use Idle... Open up a Windows command shell and invoke Python >without giving a script file to execute. > >C:\Users\Wulfraed\Documents>python >ActivePython 2.7.5.6 (ActiveState Software Inc.) based on >Python 2.7.5 (default, Sep 16 2013, 23:11:01) [MSC v.1500 64 bit (AMD64)] >on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> exit() > >C:\Users\Wulfraed\Documents>python3 >ActivePython 3.3.2.0 (ActiveState Software Inc.) based on >Python 3.3.2 (default, Sep 16 2013, 23:11:39) [MSC v.1600 64 bit (AMD64)] >on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> exit() > >C:\Users\Wulfraed\Documents> > > Note that my default Python is still 2.7, but I also have Python 3.3 >installed, and can access it using "python3" (I can also ensure Python 2.7 >by using "python2") > > >> >>I tried list(range(10) I thought that would work in Python 3. It >>didn't. I spent quite a bit of time last night trying to come up with > > Really? what did it do? SHOW US! > >C:\Users\Wulfraed\Documents>python3 >ActivePython 3.3.2.0 (ActiveState Software Inc.) based on >Python 3.3.2 (default, Sep 16 2013, 23:11:39) [MSC v.1600 64 bit (AMD64)] >on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> list(range(10)) >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>> print(list(range(10))) >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>> repr(list(range(10))) >'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' >>>> > > Recall that "print" is a function in Python 3, so the extra layer of () >are required. > >C:\Users\Wulfraed\Documents>python >ActivePython 2.7.5.6 (ActiveState Software Inc.) based on >Python 2.7.5 (default, Sep 16 2013, 23:11:01) [MSC v.1500 64 bit (AMD64)] >on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> list(range(10)) >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>> print list(range(10)) >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>> print(list(range(10))) >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>> repr(list(range(10))) >'[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]' >>>> > > "Print" doesn't need the (), but they also don't hurt it in Python 2. >(still in Py2) > >>>> range(10) >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>> xrange(10) >xrange(10) >>>> print range(10) >[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>>> print xrange(10) >xrange(10) >>>> exit >Use exit() or Ctrl-Z plus Return to exit >>>> exit() > > Now Py3 > >C:\Users\Wulfraed\Documents>python3 >ActivePython 3.3.2.0 (ActiveState Software Inc.) based on >Python 3.3.2 (default, Sep 16 2013, 23:11:39) [MSC v.1600 64 bit (AMD64)] >on win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> range(10) >range(0, 10) >>>> xrange(10) >Traceback (most recent call last): > File "", line 1, in >NameError: name 'xrange' is not defined >>>> print(range(10)) >range(0, 10) >>>> I am not working on that any more. I have my assignment for this week so I am done with busy work. Thanks for all your help From alister.nospam.ware at ntlworld.com Sat Oct 25 15:49:21 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Sat, 25 Oct 2014 19:49:21 GMT Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <59T2w.961096$xb.245738@fx08.am4> On Sat, 25 Oct 2014 16:03:16 +1100, Steven D'Aprano wrote: > [Alister] >> I had to mentally step through this before it became apparent what it >> was doing, can see places where it could be usefull (a switch >> replacement) but it is not instantly obvious > > Very little code is instantly obvious. Even when you know what the > syntax means, you still have to understand the semantics, and sometimes > that's far from obvious. > > >> a = if else >> >> is instantly obvious (at least to a native English speaker anyway) > > Ha! And yet people have, and continue to, complain *bitterly* about the > non-standard ordering of Python's ternary if, compared to C, standard > if...else syntax, and English. Not Me, I don't program i C & I don't want to it is too low level fro my liking (& I used to program in assembler for a living) -- "You need tender loving care once a week - so that I can slap you into shape." - Ellyn Mustard From ben+python at benfinney.id.au Sat Oct 25 16:45:30 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 26 Oct 2014 07:45:30 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85y4s33ml1.fsf@benfinney.id.au> Steven D'Aprano writes: > Of course it won't be clear to *everyone* but it should be clear > enough to people who are familiar with standard Python idioms. A > concrete example should be more obvious than the fake example: > > title = ('Mr', 'Ms')[person.sex == 'F'] > > which should be clear to anyone who understands indexing in Python and > that True == 1 and False == 0. I consider it an accident of history, and one which should not be necessary to understand Python code. In other words, I consider code which exploits the equality of True with 1, or False with 0, is code with a leaky abstraction and should be fixed. > Although that's probably better written as a dict lookup: > > title = {'M': 'Mr', 'F': 'Ms'}[person.sex] > > which is then more easily extended to support intersex and > non-traditional[1] gender identities. It's true that gender is not a binary, but even if it were, this would be a bad idea. A schema which blurs the distinction between boolean versus integer is a code smell: it speaks to the high likelihood that the ?flag? really represents an entity which will soon have more than two states, and should never have been represented as a boolean. -- \ ?As scarce as truth is, the supply has always been in excess of | `\ the demand.? ?Josh Billings | _o__) | Ben Finney From denismfmcmahon at gmail.com Sat Oct 25 16:51:25 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sat, 25 Oct 2014 20:51:25 +0000 (UTC) Subject: I am out of trial and error again Lists References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> Message-ID: On Sat, 25 Oct 2014 15:01:54 +0000, Grant Edwards wrote: > On 2014-10-24, Denis McMahon wrote: >> On Fri, 24 Oct 2014 10:38:31 -0400, Seymore4Head wrote: >> >>> Thanks everyone for your suggestions. >> >> Try loading the following in codeskulptor: >> >> http://www.codeskulptor.org/#user38_j6kGKgeOMr_0.py > No. I wasn't replying to you, I was replying to S4H. > We[1] aren't intested in whatever Python-like language is implemented in > codeskulptor. However S4H may be, and one thing I can be sure is that if I give him a cs url, he will at least be running the exact same python code I typed in the same python environment, and hence I know what results he should see, namely the same ones I saw. -- Denis McMahon, denismfmcmahon at gmail.com From wolfgang.maier at biologie.uni-freiburg.de Sat Oct 25 17:41:52 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Sat, 25 Oct 2014 23:41:52 +0200 Subject: Status of side-effecting functions in python In-Reply-To: References: Message-ID: On 25.10.2014 19:27, Rustom Mody wrote: > Moved from other (Seymore's) thread where this is perhaps not relevant > > On Saturday, October 25, 2014 1:15:09 PM UTC+5:30, Steven D'Aprano wrote: >> Rustom Mody wrote: >> >>> On Saturday, October 25, 2014 11:20:03 AM UTC+5:30, Chris Angelico wrote: >>>> On Sat, Oct 25, 2014 at 4:40 PM, Rustom Mody wrote: >>>>> Its generally accepted that side-effecting functions are not a good >>>>> idea -- typically a function that returns something and changes global >>>>> state. >>>> >>>> Only in certain circles. Not in Python. There are large numbers of >>>> functions with side effects (mutator methods like list.append, >>>> anything that needs lots of state like random.random, everything with >>>> external effect like I/O, heaps of stuff), and it is most definitely >>>> not frowned upon. >>>> >>>> In Python 3 (or Python 2 with the future directive), print is a >>>> function, print() an expression. It's not "semantically a statement". >>> >>> Ok >>> So give me a valid (ie useful) use where instead of the usual >>> l=[1,2,3] >>> l.append(4) >>> >>> we have >>> >>> foo(l.append(4)) >> >> Your question seems to be non-sequitor. To me, it doesn't appear to have any >> relationship to Chris' comments. > > | Languages like Pascal (many others)... distinguish function which return > | results and procedure which do not... > | Extract from https://en.wikipedia.org/wiki/Subroutine#Language_support > > So my point: Whether the language supports it strongly (Pascal' > procedures) weakly (C's void functions) more weakly (Python's None > returning functions), the beginning programmer needs this concept as a core > thinking tool. > > Pascal makes this easy -- teach the syntax and the concept will get across > Python is harder because the concept does not correlate with any specific syntax > But its not all that hard unless the teacher is stuck in correlating core concepts > and language syntax. > > A teacher who is so stuck is cheating the student. > > My version: > "print may (3) or may not (2) be an expression. Just always consider it as a statement" > > Chris version: print() is an expression. > Technically Chris is correct. Is it methodologically/pedagogically it is sound? > > Consider: > > From my explanation this: > >>>> [print(x) for x in [1,2,3]] > 1 > 2 > 3 > [None, None, None] >>>> > > is in "Dont Do!" category whether python (3) allows it or python 2 doesn't. > And you "Dont do" because print(x) is a statement -- literally in > python 2; morally in python 3 > > And from here its only a small step to why l.append(4) should never > be used except as a statement. Python may not literally have Pascal's procedures; > they are morally there if you choose to 'believe' in them. > > How would Chris inculcate avoidance of code-smells like > - foo(l.append(4)) > - [print(x) for x in [1,2,3]] > As Chris and Steven have pointed out, picking print() as an example does not make too much sense since it returns None. It may be rare to use an expression both for its side-effects and its return value, but, provided you document the intention appropriately, I do not see what would generally be wrong with it. A quick example that's not quite as silly as all your print() ones: >>> with open('longnumber.txt', 'w') as out: print(sum(out.write(str(x)) for x in range(100)), 'characters written.') 190 characters written. From denismfmcmahon at gmail.com Sat Oct 25 18:15:30 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Sat, 25 Oct 2014 22:15:30 +0000 (UTC) Subject: I am out of trial and error again Lists References: Message-ID: On Fri, 24 Oct 2014 20:15:02 -0400, Seymore4Head wrote: > On Wed, 22 Oct 2014 16:30:37 -0400, Seymore4Head > wrote: > > name="012" name is a string of 3 characters > b=list(range(3)) b is a list of 3 numbers > print (name[1]) name[1] is the string "1" > print (b[1]) b[1] is the number 1 > if name[1] == b[1]: > print ("Eureka!") This didn't happen > else: > print ("OK, I get it") This happened -- Denis McMahon, denismfmcmahon at gmail.com From dan at tombstonezero.net Sat Oct 25 18:22:01 2014 From: dan at tombstonezero.net (Dan Sommers) Date: Sat, 25 Oct 2014 22:22:01 +0000 (UTC) Subject: Status of side-effecting functions in python References: Message-ID: On Sat, 25 Oct 2014 23:41:52 +0200, Wolfgang Maier wrote: > ... It may be rare to use an expression both for its side-effects and > its return value ... A lot of concurrency-related operations work that way. In the old days, it was CPU-level Test and Set (or Compare and Set) instructions. These days, we have Python's threading.Lock.acquire. Dan From drsalists at gmail.com Sat Oct 25 18:34:06 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Sat, 25 Oct 2014 15:34:06 -0700 Subject: (test) ? a:b In-Reply-To: <85y4s33ml1.fsf@benfinney.id.au> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <85y4s33ml1.fsf@benfinney.id.au> Message-ID: On Sat, Oct 25, 2014 at 1:45 PM, Ben Finney wrote: > Steven D'Aprano writes: >> title = ('Mr', 'Ms')[person.sex == 'F'] >> >> which should be clear to anyone who understands indexing in Python and >> that True == 1 and False == 0. > > I consider it an accident of history, and one which should not be > necessary to understand Python code. > > In other words, I consider code which exploits the equality of True with > 1, or False with 0, is code with a leaky abstraction and should be > fixed. I don't like the (a, b)[True] thing, but I use the fact that True is 1 and False is 0 sometimes. EG, if I have 3 mutually exclusive command line options, I'll do something like: if option_a + option_b + option_c != 1: sys.stderr.write('{}: -a, -b and -c are mutually exclusive\n'.format(sys.argv[0])) From tjreedy at udel.edu Sat Oct 25 18:48:59 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 25 Oct 2014 18:48:59 -0400 Subject: I am out of trial and error again Lists In-Reply-To: <93qn4a5g5bd93h5rmase56v5li8mkv0inf@4ax.com> References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <93qn4a5g5bd93h5rmase56v5li8mkv0inf@4ax.com> Message-ID: On 10/25/2014 2:23 PM, Dennis Lee Bieber wrote: > On Fri, 24 Oct 2014 10:38:31 -0400, Seymore4Head > declaimed the following: > >> >> I do get the difference. I don't actually use Python 2. I use >> CodeSkulptor. I do have Python 3 installed. Actually I have Python 2 >> installed but IDLE defaults to Python 3. This is wrong. Pythonx.y runs Idlex.y, not vice versa. Seymore installed some version of Python 3 as default, as he should have, and 'Edit with Idle' opens the default version of Python, with its version of Idle. >> So it is a pain to actually load Python 2. Not really, neither on linux or Windows. > So don't use Idle... Since Seymore analysis is wrong, this advice in not the answer. If he is running on Windows, it is dubious in that the Windows console interpreter is a pain to use. > Open up a Windows command shell and invoke Python > without giving a script file to execute. > > C:\Users\Wulfraed\Documents>python python -m idlelib will open the corresponding Idle. So will the Start menu entry or an icon pinned to the taskbar. > C:\Users\Wulfraed\Documents>python3 You must have done something extra to make this work on Windows. -- Terry Jan Reedy From tjreedy at udel.edu Sat Oct 25 18:53:16 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 25 Oct 2014 18:53:16 -0400 Subject: Status of side-effecting functions in python In-Reply-To: References: Message-ID: On 10/25/2014 6:22 PM, Dan Sommers wrote: > On Sat, 25 Oct 2014 23:41:52 +0200, Wolfgang Maier wrote: > >> ... It may be rare to use an expression both for its side-effects and >> its return value ... > > A lot of concurrency-related operations work that way. In the old days, > it was CPU-level Test and Set (or Compare and Set) instructions. These > days, we have Python's threading.Lock.acquire. list.pop and and related set and dict methods. -- Terry Jan Reedy From breamoreboy at yahoo.co.uk Sat Oct 25 19:25:30 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 26 Oct 2014 00:25:30 +0100 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <93qn4a5g5bd93h5rmase56v5li8mkv0inf@4ax.com> Message-ID: On 25/10/2014 23:48, Terry Reedy wrote: > On 10/25/2014 2:23 PM, Dennis Lee Bieber wrote: >> On Fri, 24 Oct 2014 10:38:31 -0400, Seymore4Head >> declaimed the following: >> >>> >>> I do get the difference. I don't actually use Python 2. I use >>> CodeSkulptor. I do have Python 3 installed. Actually I have Python 2 >>> installed but IDLE defaults to Python 3. > > This is wrong. Pythonx.y runs Idlex.y, not vice versa. > Seymore installed some version of Python 3 as default, as he should > have, and 'Edit with Idle' opens the default version of Python, with its > version of Idle. > > >> So it is a pain to actually load Python 2. > > Not really, neither on linux or Windows. > >> So don't use Idle... > > Since Seymore analysis is wrong, this advice in not the answer. > If he is running on Windows, it is dubious in that the Windows console > interpreter is a pain to use. > > > Open up a Windows command shell and invoke Python >> without giving a script file to execute. >> >> C:\Users\Wulfraed\Documents>python > > python -m idlelib will open the corresponding Idle. So will the Start > menu entry or an icon pinned to the taskbar. > >> C:\Users\Wulfraed\Documents>python3 > > You must have done something extra to make this work on Windows. > The Python launcher for Windows should be taken into account here http://legacy.python.org/dev/peps/pep-0397/ -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From ben+python at benfinney.id.au Sat Oct 25 19:53:52 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 26 Oct 2014 10:53:52 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <85y4s33ml1.fsf@benfinney.id.au> Message-ID: <85tx2r3dv3.fsf@benfinney.id.au> Dan Stromberg writes: > EG, if I have 3 mutually exclusive command line options, I'll do > something like: > > if option_a + option_b + option_c != 1: > sys.stderr.write('{}: -a, -b and -c are mutually exclusive\n'.format(sys.argv[0])) That is an excellent illustration of why exploiting this accidental property of True and False leads to obfuscated code. The above test gives me no clue that we're operating on boolean values, nor that we're testing for exclusive options. The error message bears no obvious relation to the test, and if I was tracking down that error message I'd have no hint from the code why the test is written that way. An explanatory comment would be needed, but that's a strong sign IMO that instead the test should be re-written to be much more obvious. -- \ ?Never express yourself more clearly than you are able to | `\ think.? ?Niels Bohr | _o__) | Ben Finney From rosuav at gmail.com Sat Oct 25 20:01:40 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 26 Oct 2014 11:01:40 +1100 Subject: (test) ? a:b In-Reply-To: <85tx2r3dv3.fsf@benfinney.id.au> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <85y4s33ml1.fsf@benfinney.id.au> <85tx2r3dv3.fsf@benfinney.id.au> Message-ID: On Sun, Oct 26, 2014 at 10:53 AM, Ben Finney wrote: > Dan Stromberg writes: > >> EG, if I have 3 mutually exclusive command line options, I'll do >> something like: >> >> if option_a + option_b + option_c != 1: >> sys.stderr.write('{}: -a, -b and -c are mutually exclusive\n'.format(sys.argv[0])) > > That is an excellent illustration of why exploiting this accidental > property of True and False leads to obfuscated code. The above test > gives me no clue that we're operating on boolean values, nor that we're > testing for exclusive options. Would it be more readable thus? if len([opt for opt in (option_a, option_b, option_c) if opt]) != 1: Because that's what it's doing. I think treating bools as numbers is fine. Matter of opinion I guess. ChrisA From breamoreboy at yahoo.co.uk Sat Oct 25 20:09:50 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 26 Oct 2014 01:09:50 +0100 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <85y4s33ml1.fsf@benfinney.id.au> <85tx2r3dv3.fsf@benfinney.id.au> Message-ID: On 26/10/2014 01:01, Chris Angelico wrote: > On Sun, Oct 26, 2014 at 10:53 AM, Ben Finney wrote: >> Dan Stromberg writes: >> >>> EG, if I have 3 mutually exclusive command line options, I'll do >>> something like: >>> >>> if option_a + option_b + option_c != 1: >>> sys.stderr.write('{}: -a, -b and -c are mutually exclusive\n'.format(sys.argv[0])) >> >> That is an excellent illustration of why exploiting this accidental >> property of True and False leads to obfuscated code. The above test >> gives me no clue that we're operating on boolean values, nor that we're >> testing for exclusive options. > > Would it be more readable thus? > > if len([opt for opt in (option_a, option_b, option_c) if opt]) != 1: > > Because that's what it's doing. I think treating bools as numbers is > fine. Matter of opinion I guess. > > ChrisA > Horrible IMHO, it just doesn't fit in my mind set. Still each to their own. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rosuav at gmail.com Sat Oct 25 20:13:08 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 26 Oct 2014 11:13:08 +1100 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <85y4s33ml1.fsf@benfinney.id.au> <85tx2r3dv3.fsf@benfinney.id.au> Message-ID: On Sun, Oct 26, 2014 at 11:09 AM, Mark Lawrence wrote: > Horrible IMHO, it just doesn't fit in my mind set. Still each to their own. Yeah, the comprehension version is way more explicit (though it probably ought to be a set and a set comp, not a tuple and a list comp), and not as good, IMO. But it explains and justifies the original. ChrisA From steve+comp.lang.python at pearwood.info Sat Oct 25 20:10:05 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 26 Oct 2014 11:10:05 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> Message-ID: <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> Ben Finney wrote: > Steven D'Aprano writes: > >> Of course it won't be clear to *everyone* but it should be clear >> enough to people who are familiar with standard Python idioms. A >> concrete example should be more obvious than the fake example: >> >> title = ('Mr', 'Ms')[person.sex == 'F'] >> >> which should be clear to anyone who understands indexing in Python and >> that True == 1 and False == 0. > > I consider it an accident of history, and one which should not be > necessary to understand Python code. > > In other words, I consider code which exploits the equality of True with > 1, or False with 0, is code with a leaky abstraction and should be > fixed. I suspect that Guido and the core developers disagree with you, since they had the opportunity to fix that in Python 3 and didn't. Equating True with 1 and False with 0 is fundamental to many programming languages, but more importantly Boolean Algebra itself normally identifies True with 1 and False with 0. https://en.wikipedia.org/wiki/Boolean_algebra http://mathworld.wolfram.com/BooleanAlgebra.html Admittedly this is only a convention, and you're welcome to invent your own convention, but when doing so you should be aware that Python's convention is mathematically sound and, well, conventional. One example of where treating True and False as 1 and 0 is useful is that it makes counting operations very simple, e.g. counting the number of blank lines: sum(not line.strip() for line in lines) If you reject implicit or explicit bool-to-int conversions: sum(1 if not line.strip() else 0 for line in lines) or for compatibility with Python 2.4: sum({'': 0}.get(line.strip(), 1) for line in lines) which I consider far less obvious than the straightforward summation of True values. Sometimes making things *too* abstract is worse than allowing an abstraction to leak. -- Steven From ben+python at benfinney.id.au Sat Oct 25 21:03:28 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 26 Oct 2014 12:03:28 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <85oasz3an3.fsf@benfinney.id.au> Steven D'Aprano writes: > I suspect that Guido and the core developers disagree with you, since > they had the opportunity to fix that in Python 3 and didn't. That doesn't follow; there are numerous warts in Python 2 that were not fixed in Python 3. As I understand it, the preservation of bool?int equality has more to do with preserving backward compatibility. I agree with the decision, because this isn't an issue which often leads to *incorrect* code. But I maintain that it's an unfortunate and needlessly confusing wart of the language. > One example of where treating True and False as 1 and 0 is useful is > that it makes counting operations very simple, e.g. counting the > number of blank lines: > > sum(not line.strip() for line in lines) > sum(1 if not line.strip() else 0 for line in lines) > sum({'': 0}.get(line.strip(), 1) for line in lines) These all look ludicrous and explain nothing about intent, to my reading. The ?bool? type exists precisely because there is a concept to be represented which is distinct from integers. Using a sum on non-numeric values just cracks the abstraction open needlessly. Once I figure out what is going on, I'm left wondering why the coder chose something so obfuscatory to their intent. This is short and clear and needs no leaking of the underlying bool implementation:: len(True for line in lines if line.strip()) > which I consider far less obvious than the straightforward summation > of True values. Why sum them at all? You aren't interested in them as numbers, you're just asking how many objects meet a criterion. That calls not for ?sum?, but ?len?. There's no need to rely on an underlying ?int? operation just to count objects. The fact that summing them gives the same answer as simply asking how many there are, demonstrates that nothing is gained by peeking into the implementation. The example I give above works exactly as well with no ?int? underlying the ?bool? type at all. -- \ ?The way to build large Python applications is to componentize | `\ and loosely-couple the hell out of everything.? ?Aahz | _o__) | Ben Finney From torriem at gmail.com Sat Oct 25 21:04:52 2014 From: torriem at gmail.com (Michael Torrie) Date: Sat, 25 Oct 2014 19:04:52 -0600 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: <544C48B4.6020107@gmail.com> On 10/22/2014 09:46 PM, Gregory Ewing wrote: > Chris Angelico wrote: >> I've seen much MUCH worse... where multiple conditional >> expressions get combined arithmetically, and then the result used >> somewhere... > > In the days of old-school BASIC it was common to > exploit the fact that boolean expressions evaluated > to 0 or 1 (or -1, depending on your dialect :) to > achieve conditional expressions or other tricks. As far as I can tell, no BASIC dialect I've looked at (DOS and Linux worlds only), has ever had any logical operators like AND (&&), OR (||), and NOT (!). They only appear to have bitwise operators (&,|,~ C equivalent). The fact that comparison operators returned 0 and -1 made the bitwise operators function the same as logical. But you can run into trouble if you tried to use a common python idiom like this: x = read_some_lines() 'returns number of lines read, or zero if none are if not x: print ("I couldn't read any lines") exit(1) Basically any value other than -1 for x would cause the not x to be true. Off topic, and no matter to python programmers. But for BASIC you need to watch out for this. One BASIC dialect introduced a set of functions, istrue() and isfalse() to convert a non-zero truth value to -1, and any falsish value to zero (like maybe an empty string). That way the bitwise operators would always function as logical operators in a conditional expression. From ben+python at benfinney.id.au Sat Oct 25 21:10:43 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 26 Oct 2014 12:10:43 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <85oasz3an3.fsf@benfinney.id.au> Message-ID: <85k33n3ab0.fsf@benfinney.id.au> Ben Finney writes: > This is short and clear and needs no leaking of the underlying bool > implementation:: > > len(True for line in lines if line.strip()) Correction:: len([True for line in lines if line.strip()]) -- \ ?Our task must be to free ourselves from our prison by widening | `\ our circle of compassion to embrace all humanity and the whole | _o__) of nature in its beauty.? ?Albert Einstein | Ben Finney From rosuav at gmail.com Sat Oct 25 21:20:04 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 26 Oct 2014 12:20:04 +1100 Subject: (test) ? a:b In-Reply-To: <544C48B4.6020107@gmail.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <544C48B4.6020107@gmail.com> Message-ID: On Sun, Oct 26, 2014 at 12:04 PM, Michael Torrie wrote: > But you can run > into trouble if you tried to use a common python idiom like this: > > x = read_some_lines() 'returns number of lines read, or zero if none are > if not x: > print ("I couldn't read any lines") > exit(1) > > Basically any value other than -1 for x would cause the not x to be > true. So don't use Python idioms in BASIC. :) Back when I used to write BASIC code, I'd do explicit comparisons with zero for this sort of thing... these days, I'd use Python idioms, but I'd also write Python code :) I think it's indicative that the BASIC code I'm most proud of was consciously getting around language limitations (I wrote a mess of code in assembly language and Q-BASIC to allow my programs to use the mouse), but the Python code I'm most proud of is using the language's strengths. ChrisA From torriem at gmail.com Sat Oct 25 23:05:46 2014 From: torriem at gmail.com (Michael Torrie) Date: Sat, 25 Oct 2014 21:05:46 -0600 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <544C48B4.6020107@gmail.com> Message-ID: <544C650A.2090503@gmail.com> On 10/25/2014 07:20 PM, Chris Angelico wrote: > So don't use Python idioms in BASIC. :) Back when I used to write > BASIC code, I'd do explicit comparisons with zero for this sort of > thing... these days, I'd use Python idioms, but I'd also write Python > code :) > > I think it's indicative that the BASIC code I'm most proud of was > consciously getting around language limitations (I wrote a mess of > code in assembly language and Q-BASIC to allow my programs to use the > mouse), but the Python code I'm most proud of is using the language's > strengths. Hey I did the same thing in Turbo and then later Power BASIC. I have a soft spot for BASIC, and now with FreeBASIC releasing their 1.0 release (object-oriented capabilities and the works), I revisited a bit of my BASIC past. Translated a few programs from Turbo and Power BASIC into the more modern FreeBASIC dialect. But now that that's done, it's back to Python, where I'm going to stay! Python reminds me of the best BASIC had to offer plus a whole lot more. From steve+comp.lang.python at pearwood.info Sun Oct 26 00:15:06 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 26 Oct 2014 15:15:06 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> Message-ID: <544c754b$0$12991$c3e8da3$5496439d@news.astraweb.com> Ben Finney wrote: > Steven D'Aprano writes: > >> I suspect that Guido and the core developers disagree with you, since >> they had the opportunity to fix that in Python 3 and didn't. > > That doesn't follow; there are numerous warts in Python 2 that were not > fixed in Python 3. As I understand it, the preservation of bool?int > equality has more to do with preserving backward compatibility. On reviewing PEP 285, I think it is safe to say that Guido *explicitly* wants bools to be ints, not just for backwards compatibility: 4) Should we strive to eliminate non-Boolean operations on bools in the future, through suitable warnings, so that for example True+1 would eventually (in Python 3000) be illegal? => No. There's a small but vocal minority that would prefer to see "textbook" bools that don't support arithmetic operations at all, but most reviewers agree with me that bools should always allow arithmetic operations. http://legacy.python.org/dev/peps/pep-0285/ > I agree with the decision, because this isn't an issue which often leads > to *incorrect* code. But I maintain that it's an unfortunate and > needlessly confusing wart of the language. That puts you in the small but vocal minority :-) >> One example of where treating True and False as 1 and 0 is useful is >> that it makes counting operations very simple, e.g. counting the >> number of blank lines: >> >> sum(not line.strip() for line in lines) >> sum(1 if not line.strip() else 0 for line in lines) >> sum({'': 0}.get(line.strip(), 1) for line in lines) > > These all look ludicrous and explain nothing about intent, to my > reading. [...] > I'm left wondering why > the coder chose something so obfuscatory to their intent. "Ludicrous" and "obfuscatory". They're awfully strong words. Do you really not see the connection between counting and summing? If so, that would put you in a truly small minority. The connection between adding and counting has been known to Western mathematics since at least the ancient Greeks, if not even earlier, and we teach it to school children. If you have three apples, and I have two apples, then in total we have (count the apples: one two three, four five) five apples. Pre-schoolers learn this. I'm sure it's not too difficult for programmers. > This is short and clear and needs no leaking of the underlying bool > implementation:: > > len(True for line in lines if line.strip()) I see that in a later email you discovered your unfortunate bug in this, and corrected it to this: len([True for line in lines if line.strip()]) Alas, you missed the bigger bug: I'm counting *blank lines*, not non-blank lines. You need a `not` in there. You mentioned intent before. I wonder what your intention is, to needlessly build a potentially gigantic list of identical values, only to then throw the list away. Could be worse; you might have written [True for line in lines if not line.strip()].count(True) Since the list items exist only to be counted, the actual item used makes no difference. You could use any value at all, or even a different value each time: len([random.random() for line in lines if not line.strip()]) What is your reason for the choice of True as the tally marker? It doesn't clarify your intent, or make it more obvious that you're counting the number of non-empty lines. If you wanted to suggest a tally: len(['/' for line in lines if not line.strip()]) at least looks like a tally: //// makes four. Using a bool doesn't make this any clearer, and you don't even have the excuse that it's efficient, because it isn't. Let's get rid of the list comp and write a straightforward translation: temp = [] for line in lines: if not line.strip(): temp.append(True) result = len(temp) del temp I don't consider that sensible code at all. Why waste time building the temporary list when all we want is a counter? result = 0 for line in lines: if not line.strip(): result += 1 which can be simplified to: result = 0 for line in lines: result += not line.strip() I agree with you that this breaks the abstraction "bools are abstract enumerations, not ints", but that abstraction is not part of Python. If I objected to code like this: types = [int, str, list, dict] for t in types: do_something_with(t) on the basis that we shouldn't treat types as values, because that breaks the abstraction that "types are not values, they're a different kind of thing known only to the compiler" (as in Java), I expect that you would have no hesitation in telling me that my objection was invalid. Making types be non-values may, or may not, be a reasonable programming model, but it's not Python's programming model. In Python, types are themselves objects and first-class values. Objecting to Python code because it violates a norm from some other language is, frankly, silly. The abstraction "bools are abstract enumerations different from ints" may be a reasonable abstraction, but it's not part of Python's programming model [...] >> which I consider far less obvious than the straightforward summation >> of True values. > > Why sum them at all? You aren't interested in them as numbers, you're > just asking how many objects meet a criterion. That calls not for ?sum?, > but ?len?. There's no need to rely on an underlying ?int? operation just > to count objects. A length (in the sense of the discrete count of the number of items) is fundamentally a sum of ones. That is what counting *is*. > The fact that summing them gives the same answer as simply asking how > many there are, demonstrates that nothing is gained by peeking into the > implementation. The example I give above works exactly as well with no > ?int? underlying the ?bool? type at all. And if you were programming in a language where bools were not a sub-type of int, perhaps your code might be preferred. But even then, why build an unnecessarily large list, only to throw it away unused apart from counting the items? You can just count the items as they appear. Even in some other hypothetical language with abstract bools, say, Pascal, I'd write it as: sum(1 for line in lines if not line.strip()) rather than build a full list that I don't care about. -- Steven From rosuav at gmail.com Sun Oct 26 00:34:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 26 Oct 2014 15:34:42 +1100 Subject: (test) ? a:b In-Reply-To: <544c754b$0$12991$c3e8da3$5496439d@news.astraweb.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <544c754b$0$12991$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Oct 26, 2014 at 3:15 PM, Steven D'Aprano wrote: > Since the list items exist only to be counted, the actual item used makes no > difference. You could use any value at all, or even a different value each > time: > > len([random.random() for line in lines if not line.strip()]) > > What is your reason for the choice of True as the tally marker? It doesn't > clarify your intent, or make it more obvious that you're counting the > number of non-empty lines. Personally, I'd use the original value. When you're counting something, it's common to count that thing, rather than some stand-in. len([line for line in lines if not line.strip()]) But that's no better than anything else. The only significance is that it feels more like counting a filtered portion of the list. ChrisA From steve+comp.lang.python at pearwood.info Sun Oct 26 02:12:21 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 26 Oct 2014 17:12:21 +1100 Subject: Side-effects [was Re: I am out of trial and error again Lists] References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> <25c6a468-e596-4a31-856b-bb5fe22c8894@googlegroups.com> <9dd6db37-5568-405e-8af7-3a28195eec4d@googlegroups.com> Message-ID: <544c90c6$0$12986$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Sat, Oct 25, 2014 at 4:40 PM, Rustom Mody > wrote: >> Its generally accepted that side-effecting functions are not a good idea >> -- typically a function that returns something and changes global state. > > Only in certain circles. Not in Python. There are large numbers of > functions with side effects (mutator methods like list.append, > anything that needs lots of state like random.random, everything with > external effect like I/O, heaps of stuff), and it is most definitely > not frowned upon. Hmmm. You might be overstating it a tad. You are absolutely correct that Python is not a strict functional language with no side-effects. However, mutator methods on a class don't change global state, they change the state of an instance. Even random.random and friends don't change global state, they change a (hidden) instance, and you can create your own instances when needed. That gives you the convenience of pseudo-global state while still allowing the flexibility of having separate instances. Even global variables in Python are global to the module, not global to the entire application. So although Python code isn't entirely side-effect free, the general advice to avoid writing code that relies on global state and operates via side-effect still applies. To take an extreme example, we do this: print(len(something)) not this: LEN_ARGUMENT = something len() print(LEN_RESULT) We *could* write code like that in Python, but as a general rule we don't. If we did, it would be frowned upon. I would say that Python is a pragmatic language which uses whatever idiom seems best at the time, but over all it prefers mutable state for compound objects, prefers immutable state for scalar objects (like numbers), and discourages the unnecessary use of global mutable state. -- Steven From rosuav at gmail.com Sun Oct 26 02:42:06 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 26 Oct 2014 17:42:06 +1100 Subject: Side-effects [was Re: I am out of trial and error again Lists] In-Reply-To: <544c90c6$0$12986$c3e8da3$5496439d@news.astraweb.com> References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> <25c6a468-e596-4a31-856b-bb5fe22c8894@googlegroups.com> <9dd6db37-5568-405e-8af7-3a28195eec4d@googlegroups.com> <544c90c6$0$12986$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Oct 26, 2014 at 5:12 PM, Steven D'Aprano wrote: > However, mutator methods on a class don't change global state, they change > the state of an instance. Even random.random and friends don't change > global state, they change a (hidden) instance, and you can create your own > instances when needed. That gives you the convenience of pseudo-global > state while still allowing the flexibility of having separate instances. > Even global variables in Python are global to the module, not global to the > entire application. True, but they do still change state; I oversimplified a bit, but certainly there are plenty of functions that change state in some way, and are not frowned upon. Module level variables really are global, though. You can't easily and conveniently reinstantiate a module in Python; if you "import random; random.seed(1234)", you can confidently expect that some other module that uses random.random will be affected. Sure, there are ways around that, but that's true of any form of global state - for a start, it's usually "process level" state, in that spawning a new process will isolate one from another. The only thing that isn't truly global is the namespace; I can write "x = {}" and you can write "x = []" and they don't collide. They're still global (process-level), it's just that they're "foo.x" and "bar.x" and are thus distinct. > I would say that Python is a pragmatic > language which uses whatever idiom seems best at the time, but over all it > prefers mutable state for compound objects, prefers immutable state for > scalar objects (like numbers), and discourages the unnecessary use of > global mutable state. It's not really compound vs scalar, but yes, I agree. Practicality beats purity, on so many levels. Functions with side effects aren't considered some sort of weird beast that we have to permit for the sake of I/O; they're a fundamental part of the language. ChrisA From shieldfire at gmail.com Sun Oct 26 03:22:52 2014 From: shieldfire at gmail.com (Martin S) Date: Sun, 26 Oct 2014 08:22:52 +0100 Subject: Newbie suggestion: nice tutorial Message-ID: Even after having written three small tool for calculating chess ratings, I felt that I severly lacked a proper understanding of what the BEEP I was actually doing. So I looked at our standard bookshop at work, found a book that I thought neat only to discover that our work account has been cancelled... So it was back to the internet - and this one seems pretty comprehensive and understandable: http://www.diveintopython3.net/ It doesn't cover the latest point version of Python (it's still Python 3), but I hope it doesn't matter much? Regards, Martin S From ben+python at benfinney.id.au Sun Oct 26 03:40:59 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 26 Oct 2014 18:40:59 +1100 Subject: Dive Into Python 3, good tutorial (was: Newbie suggestion: nice tutorial) References: Message-ID: <85d29f2s8k.fsf@benfinney.id.au> Martin S writes: > So it was back to the internet - and this one seems pretty > comprehensive and understandable: > > http://www.diveintopython3.net/ Yes, Mark Pilgrim wrote this originally for Python 2, and it was one of the best even then. The revised edition for Python 3 is highly recommended. > It doesn't cover the latest point version of Python (it's still Python > 3), but I hope it doesn't matter much? You're right, it is still a good tutorial. Unfortunately, the primary author has disappeared . Fortunately, the work is free software, so every recipient already has full permission to improve it and share the result. Does anyone know of an active project maintaining this great resource and releasing newer versions? -- \ ?If you do not trust the source do not use this program.? | `\ ?Microsoft Vista security dialogue | _o__) | Ben Finney From wxjmfauth at gmail.com Sun Oct 26 03:45:49 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sun, 26 Oct 2014 00:45:49 -0700 (PDT) Subject: Status of side-effecting functions in python In-Reply-To: References: Message-ID: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> Le samedi 25 octobre 2014 23:42:42 UTC+2, Wolfgang Maier a ?crit?: > > As Chris and Steven have pointed out, picking print() as an example does > not make too much sense since it returns None. This is precisely the Rusy's point. Why does "print" returns something when such a function/statement should in fact returns nothing, not even a "void", a "nil", a "None". > > A quick example that's not quite as silly as all your print() ones: > > >>> with open('longnumber.txt', 'w') as out: > print(sum(out.write(str(x)) for x in range(100)), 'characters written.') > > > 190 characters written. Ditto for .write(). Why should it return "something" ? >>> with open('z.txt', 'w') as f: ... f.write('abc') ... 3 From steve+comp.lang.python at pearwood.info Sun Oct 26 05:39:43 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sun, 26 Oct 2014 20:39:43 +1100 Subject: When to use assert References: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com> <5447d20c$0$12997$c3e8da3$5496439d@news.astraweb.com> <544a049c$0$13011$c3e8da3$5496439d@news.astraweb.com> Message-ID: <544cc160$0$12991$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > On Fri, Oct 24, 2014 at 6:49 PM, Steven D'Aprano > wrote: >> addresses = [get_address(name) for name in database] >> assert all(address for address in addresses) >> # ... much later on ... >> for i, address in enumerate(addresses): >> if some_condition(): >> addresses[i] = modify(address) >> assert addresses[i] >> >> >> will either identify the culprit, or at least prove that neither >> get_address() nor modify() are to blame. Because you're using an >> assertion, it's easy to leave the asserts in place forever, and disable >> them by passing -O to the Python interpreter in production. > > The first assertion is fine, assuming that the emptiness of your > address corresponds to falsiness as defined in Python. (This could be > safe to assume, if the address is an object that knows how to boolify > itself.) The second assertion then proves that modify() isn't > returning nothing, but that might be better done by sticking the > assertion into modify itself. Sure. If you can modify the function, getting it to check it's own post-condition is a good strategy. But you might not be able to do that. Perhaps you don't have the source code, or its from a third-party library and you don't want to have to keep hacking your copy every time it's updated, or you're calling an external library written in Java. (And yes, there are work-arounds for those scenarios too. Aren't choices wonderful?) > And that's what I'm talking about: checking a function's postcondition > with an assert implies putting that assertion after every call, There's no rule that you have to use an assertion after *every* call to a function. If you can check the post-condition inside the function, that's great. If you can't, then use your judgement. More asserts are not necessarily better, just as more unit tests are not necessarily better. You have to make a value judgement based on how much you trust the code, trust your own skills, trust your colleagues who will be maintaining the code in your absence, versus the maximum density of asserts per line of other code. > and > anything that you have to do every time you call a function belongs > inside that function. Imagine writing this kind of defensive code, and > then having lots of places that call modify()... and missing the > assert in some of them. Can you trust what you're getting back? Well, if the function is perfect, then adding more assertions won't uncover bugs that aren't there. And if the function is buggy, then adding more assertions will increase the likelihood that you'll discover those bugs earlier rather than later. How much do you trust the function? One test is better than no tests at all, but a thousand tests is not necessarily better than ten. The same applies to assertions. One might say that assertions can be considered tests that automatically run every time you run your code (in debugging mode), rather than needing to remember to run a special test program. In the absence of correctness proofs for your code, anything you do (unit tests, assertions, regression tests, etc.) is just a statistically sampling of all the potential paths your code might take, hoping to capture bugs. As any statistician will tell you, eventually you will reach the point of diminishing returns, where adding more samples isn't worth the cost. That point will depend on the cost in programmer effort, the performance implications, and your confidence in the code. >> [Aside: it would be nice if Python did it the other way around, and >> [require >> a --debugging switch to turn assertions on. Oh well.] > > Maybe. But unless someone actually tests that their assertions are > being run, there's the risk that they're flying blind and assuming > that it's all happening. There'll be all these lovely "checked > comments"... or so people think. Nobody ever runs the app with > --debugging, so nobody ever sees anything. Absolutely. And if you write unit tests but never actually run them, the same thing applies. You need a process that actually runs the code in debugging mode, and/or runs the tests. Or if the unit tests all pass but don't actually do anything useful? def test_critical_code_path(self): # Make sure application works correctly. self.assertTrue(True) Do I have to link to the DailyWTF showing that some people actually do write tests like this? Sure, why not :-) http://thedailywtf.com/articles/Productive-Testing Bad programmers can screw up anything. >> Assertions and test suites are complementary, not in opposition, like >> belt and braces. Assertions insure that the code branch will be tested if >> it is ever exercised, something test suites can't in general promise. >> Here's a toy example: >> >> def some_function(value): >> import random >> random.seed(value) >> if random.random() == 0.25000375: >> assert some_condition >> else: >> pass >> >> >> Try writing a unit test that guarantees to test the some_condition >> branch :-) >> >> [Actually, it's not that hard, if you're willing to monkey-patch the >> [random >> module. But you may have reasons for wanting to avoid such drastic >> measures.] > > Easy. You craft a test case that passes the right argument, and then > have the test case test itself. You will want to have a script that > figures out what seed value to use: The Mersenne Twister isn't cryptographically strong, but even so, I'm pretty sure that it is computationally infeasible unless you get amazingly lucky. Given 624 sequential random values, it is possible to predict all subsequent values. But predicting what seed will produce a specific value is probably ... difficult. But feel free to try it: > def find_seed(value): > import random > for seed in range(1000000): # Restrict to not-too-many tries > random.seed(seed) > if random.random() == value: return seed > > I didn't say it'd be efficient to run, but hey, it's easy. Using the same logic, it's "easy" to break sha512 checksums. Just iterate over all possible files the same size as the target file until you find one which has the same checksum. > I've no > idea how many bits of internal state the default Python RNGs use, A *lot*. import random random.getstate() Enjoy :-) > But actually, it would be really simple to monkey-patch. Like I said :-) But just because you can monkey-patch, doesn't mean you will. Perhaps you have a policy not to, or just don't like doing so because you're still recovering from the pain of working with Ruby developers. http://devblog.avdi.org/2008/02/23/why-monkeypatching-is-destroying-ruby/ > And in any > non-toy situation, there's probably something more significant being > tested here... unless you really are probing a random number generator > or something, in which case you probably know more about its > internals. > >> I like this style: >> >> assert x in (a, b, c) >> if x == a: >> do_this() >> elif x == b: >> do_that() >> else: >> assert x == c >> do_something_else() > > If all your branches are simple function calls, I'd be happy with a > KeyError instead of an AssertionError or RuntimeError. > > {a:do_this, b:do_that, c:do_something_else}[x]() Nah, can't do that, because the "that's an old hack and an obsolete Python idiom, you have to use nested ternary ifs" crowd will get angry at you. *wink* Translating a chain of if...elif to a dict lookup is a good, hopefully not obsolete, Python idiom. But it doesn't work so well when the blocks are blocks of code, and it fails completely if any of the blocks contains a return, break or continue. [...] >>>> Or is that insufficiently paranoid? >>> >>> With good tests, you're probably fine. >> >> Is it possible to be too paranoid when it comes to tests? > > Yeah, it is. I was actually trying to be funny. Sorry for the fail. -- Steven From rosuav at gmail.com Sun Oct 26 05:51:19 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sun, 26 Oct 2014 20:51:19 +1100 Subject: When to use assert In-Reply-To: <544cc160$0$12991$c3e8da3$5496439d@news.astraweb.com> References: <528871d5$0$29975$c3e8da3$5496439d@news.astraweb.com> <4d46b9b6-3ab9-45bc-afe9-55da4d0fe76c@googlegroups.com> <54470c17$0$12985$c3e8da3$5496439d@news.astraweb.com> <5447d20c$0$12997$c3e8da3$5496439d@news.astraweb.com> <544a049c$0$13011$c3e8da3$5496439d@news.astraweb.com> <544cc160$0$12991$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sun, Oct 26, 2014 at 8:39 PM, Steven D'Aprano wrote: > In the absence of correctness proofs for your code, anything you do (unit > tests, assertions, regression tests, etc.) is just a statistically sampling > of all the potential paths your code might take, hoping to capture bugs. As > any statistician will tell you, eventually you will reach the point of > diminishing returns, where adding more samples isn't worth the cost. That > point will depend on the cost in programmer effort, the performance > implications, and your confidence in the code. That's about the size of it, I guess. How much testing versus how much time actually spent coding? I'm pretty sure a lot of my code has the wrong ratio... I'm just not sure, for a lot of the code, which direction it's wrong :) ChrisA From nicholascannon1 at gmail.com Sun Oct 26 06:06:54 2014 From: nicholascannon1 at gmail.com (Nicholas Cannon) Date: Sun, 26 Oct 2014 03:06:54 -0700 (PDT) Subject: Sample sqlite databases for use in python Message-ID: Hello I am making a data management program and although i can make my own databases I would like a couple sample ones to check out. Of course I searched on google for sample db's and I downloaded some but they are not working and I keep getting: File is not a database or encrypted The error is not exactly like that but it does say that it may be encrypted or not a database. I want the end user to take a database and load it in to my program but I dont wont this happening even if the file is a sqlite3 one as well. From __peter__ at web.de Sun Oct 26 07:03:12 2014 From: __peter__ at web.de (Peter Otten) Date: Sun, 26 Oct 2014 12:03:12 +0100 Subject: Sample sqlite databases for use in python References: Message-ID: Nicholas Cannon wrote: > Hello I am making a data management program and although i can make my own > databases I would like a couple sample ones to check out. Of course I > searched on google for sample db's and I downloaded some but they are not > working and I keep getting: > File is not a database or encrypted > > The error is not exactly like that but it does say that it may be > encrypted or not a database. Always cut and paste the actual error message. > I want the end user to take a database and > load it in to my program but I dont wont this happening even if the file > is a sqlite3 one as well. If my crystal ball is working you are experiencing the same problem as https://mail.python.org/pipermail/tutor/2013-July/097022.html From phd at phdru.name Sun Oct 26 09:41:35 2014 From: phd at phdru.name (Oleg Broytman) Date: Sun, 26 Oct 2014 14:41:35 +0100 Subject: SQLObject 1.6.1 Message-ID: <20141026134135.GC30627@phdru.name> Hello! I'm pleased to announce version 1.6.1, the first bugfix release of branch 1.6 of SQLObject. What's new in SQLObject ======================= * Allow unicode in .orderBy(u'-column'). Contributor for this release is Andrew Trusty. For a more complete list, please see the news: http://sqlobject.org/News.html What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: https://pypi.python.org/pypi/SQLObject/1.6.1 News and changes: http://sqlobject.org/News.html Oleg. -- Oleg Broytman http://phdru.name/ phd at phdru.name Programmers don't die, they just GOSUB without RETURN. From dan at tombstonezero.net Sun Oct 26 09:41:23 2014 From: dan at tombstonezero.net (Dan Sommers) Date: Sun, 26 Oct 2014 13:41:23 +0000 (UTC) Subject: Status of side-effecting functions in python References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> Message-ID: On Sun, 26 Oct 2014 00:45:49 -0700, wxjmfauth wrote: > Ditto for .write(). Why should it return "something" ? > >>>> with open('z.txt', 'w') as f: > ... f.write('abc') > ... > 3 OTOH, why shouldn't it return something? In this case, it returns the length of the string written. This value is analogous to the value returned by the underlying OS function (at least on a POSIX-like system, where write(2) returns the number of bytes written). This value can be useful for detecting when things have gone wrong; e.g., disk full, network down, pipe broken, etc. Practicality definitely beats purity. At one time, on a huge project, millions of lines of C and assembly code, we had a local guideline *not* to write void functions. The idea was to return something that might be useful later, even if it seemed unlikely now. A simple success flag was sufficient; as functions grew, often did their failure modes. Dan From jon+usenet at unequivocal.co.uk Sun Oct 26 10:14:36 2014 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Sun, 26 Oct 2014 14:14:36 +0000 (UTC) Subject: Lazy-evaluation lists/dictionaries Message-ID: I have a need, in a Python C extension I am writing, for lists and dictionaries with "lazy evaluation" - by which I mean that at least some of the values in the lists/dictionaries are "proxy objects" which, rather than returning as themselves, should return the thing they are a proxy for when retrieved. This is because retrieving the proxied objects is expensive and only a small minority of them will actually be accessed, so retrieving them all before they are actually accessed is massively inefficient. With object attributes, this can be easily done with the descriptor protocol and having properties which look like simple objects but actually cause a method to be invoked when they are accessed. However there doesn't seem to be any equivalent way of doing this for retrieving items from lists or dictionaries - unfortunately, the method implementations of list() and dict() are full of direct accesses to the underlying data pointers rather than indirecting through obj->tp_as_mapping->mp_subscript or whatever. Is there any better way to do this other than simply re-implementing these types from scratch, emulating all their methods and operations? (i.e. using UserList/UserDict). I was under the impression that that sort of thing was supposed to have gone since Python 2.2 or so. From rustompmody at gmail.com Sun Oct 26 10:53:34 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 26 Oct 2014 07:53:34 -0700 (PDT) Subject: Status of side-effecting functions in python In-Reply-To: References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> Message-ID: <039de590-0be6-44a9-b12b-956bbafbab7b@googlegroups.com> On Sunday, October 26, 2014 7:11:43 PM UTC+5:30, Dan Sommers wrote: > At one time, on a huge project, millions of lines of C and assembly > code, we had a local guideline *not* to write void functions. The idea > was to return something that might be useful later, even if it seemed > unlikely now. A simple success flag was sufficient; as functions grew, > often did their failure modes. Well C and Python are completely different in this respect. In C it is the norm to return the status in the return value and the actual return value in pointer parameters. Or even worse in pointer parameters + globals: think of most of the system calls and errno. This low-level messiness is in fact one of the compulsions that have driven preference and development of higher level languages like python. Here failure-mode has dedicated syntax -- exceptions. This conduces to a more DRY, less error-prone setup. - Normal mode in the normal functional call-return style - Failure mode in the except (for caller); raise (for callee) clauses. Note that my comment was: > Its generally accepted that side-effecting functions are not a good idea > -- typically a function that returns something and changes global state. So I am not talking of merely global (or non-local) variable side-effecting functions/methods which is normal in imperative programming, but ones that do BOTH - both changing global state - returning useful results in the return value While this may be called a code-smell, in C like languages it is close to unavoidable. In python its more avoidable and therefore more smelly (to my nose at least!) Yeah I note Terry's examples of list.pop etc. I guess one could say that these are instances of practicality beats purity. However note the context where this thread arose. A beginning programmer having a hard time distinguishing: - Values and effects - Expressions and statements - Immutable and mutable data-structures - Functions and Procedures My claim is that until then, he should not be trying to write code like that. From rustompmody at gmail.com Sun Oct 26 11:14:03 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 26 Oct 2014 08:14:03 -0700 (PDT) Subject: Finding my way around help Message-ID: Context: I will be showing the way around to some experienced programmers new to python. Do >>> help() Among other things I get: | Enter the name of any module, keyword, or topic to get help on writing | Python programs and using Python modules. To quit this help utility and | return to the interpreter, just type "quit". However I find it returns to the normal REPL with just a return; no quit. I would have expected a special help REPL to keep running till I give quit. What gives? Also I tried >>> help(help) This shows the docstring for class _Helper(builtins.object) However if I do this >>> from pydoc import help >>> help(help) I get more useful help. Seems the wrong way round... Above is true for 2.7 and 3.4. From wxjmfauth at gmail.com Sun Oct 26 12:26:53 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Sun, 26 Oct 2014 09:26:53 -0700 (PDT) Subject: Status of side-effecting functions in python In-Reply-To: References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> Message-ID: <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> Le dimanche 26 octobre 2014 14:41:43 UTC+1, Dan Sommers a ?crit?: > On Sun, 26 Oct 2014 00:45:49 -0700, wxjmfauth wrote: > > > Ditto for .write(). Why should it return "something" ? > > > >>>> with open('z.txt', 'w') as f: > > ... f.write('abc') > > ... > > 3 > > OTOH, why shouldn't it return something? In this case, it returns the > length of the string written. This value is analogous to the value > returned by the underlying OS function (at least on a POSIX-like system, > where write(2) returns the number of bytes written). This value can be > useful for detecting when things have gone wrong; e.g., disk full, > network down, pipe broken, etc. Practicality definitely beats purity. > > At one time, on a huge project, millions of lines of C and assembly > code, we had a local guideline *not* to write void functions. The idea > was to return something that might be useful later, even if it seemed > unlikely now. A simple success flag was sufficient; as functions grew, > often did their failure modes. > > Dan Yes and no. If something goes wrong in a .write() method, is not Python supposed to raise an error? (!) From marko at pacujo.net Sun Oct 26 12:50:58 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Sun, 26 Oct 2014 18:50:58 +0200 Subject: Status of side-effecting functions in python References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> Message-ID: <87bnoy93m5.fsf@elektro.pacujo.net> wxjmfauth at gmail.com: > Yes and no. If something goes wrong in a .write() method, > is not Python supposed to raise an error? (!) We have multiple cases: 1. write succeeds with all of the given bytes 2. write succeeds with some but not all of the given bytes 3. write cannot at the moment write any bytes 4. an I/O error has taken place Cases 1 and 2 are reported through positive return values in POSIX system calls. Cases 3 and 4 are reported as errors. Arguably 2 and 3 are related cases. Python imitates POSIX, but *could* take a different tack. For example, * always return with an exception carrying the number of bytes written * return with None in case 1 and with an exception otherwise * return with the number of bytes in 1, 2 and 3 and exception in 4 The POSIX way is justified with symmetry: read() distinguishes EAGAIN from 0 (end of file). One could argue that POSIX got it the wrong way. EOF should be an exception ("EEOF") and 0 should be used instead of EAGAIN. However, the POSIX practice works in C and Python. Marko From nicholas.cole at gmail.com Sun Oct 26 13:00:16 2014 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Sun, 26 Oct 2014 17:00:16 +0000 Subject: XML Patch Message-ID: Hi All, I'm looking for a python library that can parse XML Documents and create xml-aware "diff" files, and then use those to patch documents. In other words, I'd like something similar to the Google diff-match-patch tools, but something which is XML aware. I can see several projects on Pypi that can generate some form of xml diff, but I can't seem to see anything that can also do the patching side of things. Does anyone have any recommendations? Best wishes, Nicholas From joel.goldstick at gmail.com Sun Oct 26 13:13:46 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Sun, 26 Oct 2014 13:13:46 -0400 Subject: XML Patch In-Reply-To: References: Message-ID: On Sun, Oct 26, 2014 at 1:00 PM, Nicholas Cole wrote: > Hi All, > > I'm looking for a python library that can parse XML Documents and > create xml-aware "diff" files, and then use those to patch documents. > In other words, I'd like something similar to the Google > diff-match-patch tools, but something which is XML aware. > > I can see several projects on Pypi that can generate some form of xml > diff, but I can't seem to see anything that can also do the patching > side of things. > > Does anyone have any recommendations? > > Best wishes, > > Nicholas > -- > https://mail.python.org/mailman/listinfo/python-list Could you use git? -- Joel Goldstick http://joelgoldstick.com From stefan_ml at behnel.de Sun Oct 26 14:30:38 2014 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 26 Oct 2014 19:30:38 +0100 Subject: XML Patch In-Reply-To: References: Message-ID: Nicholas Cole schrieb am 26.10.2014 um 18:00: > I'm looking for a python library that can parse XML Documents and > create xml-aware "diff" files, and then use those to patch documents. > In other words, I'd like something similar to the Google > diff-match-patch tools, but something which is XML aware. > > I can see several projects on Pypi that can generate some form of xml > diff, but I can't seem to see anything that can also do the patching > side of things. Is there a use case for this? Stefan From timothy.c.delaney at gmail.com Sun Oct 26 16:36:09 2014 From: timothy.c.delaney at gmail.com (Tim Delaney) Date: Mon, 27 Oct 2014 07:36:09 +1100 Subject: Lazy-evaluation lists/dictionaries In-Reply-To: References: Message-ID: On 27 October 2014 01:14, Jon Ribbens wrote: > I have a need, in a Python C extension I am writing, for lists and > dictionaries with "lazy evaluation" - by which I mean that at least > some of the values in the lists/dictionaries are "proxy objects" > which, rather than returning as themselves, should return the thing > they are a proxy for when retrieved. This is because retrieving > the proxied objects is expensive and only a small minority of them > will actually be accessed, so retrieving them all before they are > actually accessed is massively inefficient. > Why not put proxy objects into the list/dict? Have a look at the weakref module for an API that may be suitable for such proxy objects (if you used the same API, that would also allow you to transparently use weakrefs in your lists/dicts). Tim Delaney -------------- next part -------------- An HTML attachment was scrubbed... URL: From ned at nedbatchelder.com Sun Oct 26 16:45:12 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Sun, 26 Oct 2014 16:45:12 -0400 Subject: (-1)**1000 In-Reply-To: <544d5499$0$41762$c3e8da3$5d8fb80f@news.astraweb.com> References: <54476a77$0$21664$426a74cc@news.free.fr> <544d5499$0$41762$c3e8da3$5d8fb80f@news.astraweb.com> Message-ID: On 10/26/14 4:07 PM, Tony the Tiger wrote: > On Wed, 22 Oct 2014 10:27:34 +0200, ast wrote: > >> If i am writing (-1)**1000 on a python program, will the interpreter do >> (-1)*(-1)*...*(-1) or something clever ? > > Even vs. odd. It ought to know. I would assume from a set of defined > rules how math works. There is such a thing as an optimization that isn't worthwhile to perform, simply because it's expected to provide so little benefit. The language implementors have to trade off the cost of adding the optimization to the implementation, against the possible benefit people would get from it. Benefit in this case would have to include a guess as to how often real programs would hit the optimization case. -- Ned Batchelder, http://nedbatchelder.com From vb.gheorghiu at gmail.com Sun Oct 26 17:00:30 2014 From: vb.gheorghiu at gmail.com (Viorica Gheorghiu) Date: Sun, 26 Oct 2014 23:00:30 +0200 Subject: Test driven programming, was Re: VB to Python migration Message-ID: -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun Oct 26 17:12:46 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 26 Oct 2014 17:12:46 -0400 Subject: (test) ? a:b In-Reply-To: <544c754b$0$12991$c3e8da3$5496439d@news.astraweb.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <544c754b$0$12991$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 10/26/2014 12:15 AM, Steven D'Aprano wrote: > Ben Finney wrote: > >> Steven D'Aprano writes: >> >>> I suspect that Guido and the core developers disagree with you, since >>> they had the opportunity to fix that in Python 3 and didn't. >> >> That doesn't follow; there are numerous warts in Python 2 that were not >> fixed in Python 3. As I understand it, the preservation of bool?int >> equality has more to do with preserving backward compatibility. > > On reviewing PEP 285, I think it is safe to say that Guido *explicitly* > wants bools to be ints, not just for backwards compatibility: > > 4) Should we strive to eliminate non-Boolean operations on bools > in the future, through suitable warnings, so that for example > True+1 would eventually (in Python 3000) be illegal? > > => No. > > There's a small but vocal minority that would prefer to see > "textbook" bools that don't support arithmetic operations at > all, but most reviewers agree with me that bools should always > allow arithmetic operations. > > http://legacy.python.org/dev/peps/pep-0285/ Thank you for digging this up. I was one of the 'most reviewers'. Even though filter now returns an iterator, so that one can write sum(1 for _ in filter(None, iterable_of_bools)) without creating an unneeded itermediate list, I still prefer sum(iterable_of_bools) for efficiency not only for the machine but also for me writing and reading. [snip of fine disquisition on the subject to which I have nothing to add] -- Terry Jan Reedy From tjreedy at udel.edu Sun Oct 26 17:44:51 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 26 Oct 2014 17:44:51 -0400 Subject: I am out of trial and error again Lists In-Reply-To: References: <2412654f-ac5e-4678-8956-afc4e27affb3@googlegroups.com> <93qn4a5g5bd93h5rmase56v5li8mkv0inf@4ax.com> Message-ID: On 10/26/2014 1:08 AM, Dennis Lee Bieber wrote: > On Sat, 25 Oct 2014 18:48:59 -0400, Terry Reedy > declaimed the following: > >>> C:\Users\Wulfraed\Documents>python3 >> >> You must have done something extra to make this work on Windows. > > Possibly hand-edited my system PATH -- I've got a rather nasty one > (inserting line breaks)... I was referring to the existence of 'python3' (and 'python2'). I presume these are created by the ActiveState installer that you said you used. There are not created by the PSF Windows installer. It instead creates 'py' linked to the new launcher; 'py -2' and 'py -3' launch the latest available python 2 or python3. -- Terry Jan Reedy From roy at panix.com Sun Oct 26 17:56:51 2014 From: roy at panix.com (Roy Smith) Date: Sun, 26 Oct 2014 17:56:51 -0400 Subject: Status of side-effecting functions in python References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> Message-ID: In article <683c84d8-d916-4b63-b4b2-92cd2763e260 at googlegroups.com>, wxjmfauth at gmail.com wrote: > Le dimanche 26 octobre 2014 14:41:43 UTC+1, Dan Sommers a ?crit?: > > On Sun, 26 Oct 2014 00:45:49 -0700, wxjmfauth wrote: > > > > > Ditto for .write(). Why should it return "something" ? > > > > > >>>> with open('z.txt', 'w') as f: > > > ... f.write('abc') > > > ... > > > 3 > > > > OTOH, why shouldn't it return something? In this case, it returns the > > length of the string written. This value is analogous to the value > > returned by the underlying OS function (at least on a POSIX-like system, > > where write(2) returns the number of bytes written). This value can be > > useful for detecting when things have gone wrong; e.g., disk full, > > network down, pipe broken, etc. Practicality definitely beats purity. > > > > At one time, on a huge project, millions of lines of C and assembly > > code, we had a local guideline *not* to write void functions. The idea > > was to return something that might be useful later, even if it seemed > > unlikely now. A simple success flag was sufficient; as functions grew, > > often did their failure modes. > > > > Dan > > Yes and no. If something goes wrong in a .write() method, > is not Python supposed to raise an error? (!) Define "wrong". It is not an error for a write() call to consume fewer bytes than were requested. How would you expect this to be handled in Python? Raise DataPartiallyWrittenError? From tjreedy at udel.edu Sun Oct 26 18:11:03 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 26 Oct 2014 18:11:03 -0400 Subject: Newbie suggestion: nice tutorial In-Reply-To: References: Message-ID: On 10/26/2014 3:22 AM, Martin S wrote: > So it was back to the internet - and this one seems pretty > comprehensive and understandable: > > http://www.diveintopython3.net/ > > It doesn't cover the latest point version of Python (it's still Python > 3), but I hope it doesn't matter much? I expect not. The book appears to have been written at the time of 3.1. There was no new syntax (but some stdlib improvements) in 3.2. 3.3 brought an improved unicode implementation and 'yield from'. You likely do not need to know about 'yield from' unless you use coroutines with the 3.4 asyncio module. I expect nearly all the beginner code in the book should still work. -- Terry Jan Reedy From tjreedy at udel.edu Sun Oct 26 18:41:57 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 26 Oct 2014 18:41:57 -0400 Subject: Lazy-evaluation lists/dictionaries In-Reply-To: References: Message-ID: On 10/26/2014 10:14 AM, Jon Ribbens wrote: > I have a need, in a Python C extension I am writing, for lists and > dictionaries with "lazy evaluation" - by which I mean that at least > some of the values in the lists/dictionaries are "proxy objects" > which, rather than returning as themselves, should return the thing > they are a proxy for when retrieved. This is because retrieving > the proxied objects is expensive and only a small minority of them > will actually be accessed, so retrieving them all before they are > actually accessed is massively inefficient. > > With object attributes, this can be easily done with the descriptor > protocol and having properties which look like simple objects but > actually cause a method to be invoked when they are accessed. However > there doesn't seem to be any equivalent way of doing this for > retrieving items from lists or dictionaries - unfortunately, the > method implementations of list() and dict() are full of direct > accesses to the underlying data pointers rather than indirecting > through obj->tp_as_mapping->mp_subscript or whatever. > > Is there any better way to do this other than simply re-implementing > these types from scratch, emulating all their methods and operations? > (i.e. using UserList/UserDict). I was under the impression that that > sort of thing was supposed to have gone since Python 2.2 or so. We considered dropping UserDict and UserList for 3.0 but kept them in collections for cases in which subclassing does not work. -- Terry Jan Reedy From drsalists at gmail.com Sun Oct 26 20:12:29 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Sun, 26 Oct 2014 17:12:29 -0700 Subject: id == vs is Message-ID: Are the following two expressions the same? x is y Id(x) == id(y) ? I ported some Java code to Python, and it was using Java's idea of equality (via ==) in some places. Right now, I have a suite of unit tests working using the second expression above, but I'm thinking about switching to the first. Thanks! From python at mrabarnett.plus.com Sun Oct 26 20:20:24 2014 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 27 Oct 2014 00:20:24 +0000 Subject: id == vs is In-Reply-To: References: Message-ID: <544D8FC8.8080601@mrabarnett.plus.com> On 2014-10-27 00:12, Dan Stromberg wrote: > Are the following two expressions the same? > > x is y > > Id(x) == id(y) > > ? > Yes. > I ported some Java code to Python, and it was using Java's idea of > equality (via ==) in some places. Right now, I have a suite of unit > tests working using the second expression above, but I'm thinking > about switching to the first. > > Thanks! > From joshua at landau.ws Sun Oct 26 20:20:01 2014 From: joshua at landau.ws (Joshua Landau) Date: Mon, 27 Oct 2014 00:20:01 +0000 Subject: id == vs is In-Reply-To: References: Message-ID: On 27 October 2014 00:12, Dan Stromberg wrote: > Are the following two expressions the same? > > x is y > > Id(x) == id(y) Much of the time, but not all the time. The obvious exception is if "id" is redefined, but that one's kind of boring. The real thing to watch out for is if the object that "x" points to is garbage collected before "y" is evaluated: nothing = "!" id("hello" + nothing) == id("hello" + nothing) #>>> True ("hello" + nothing) is ("hello" + nothing) #>>> False Since in the first case the ("hello" + nothing) gets garbage collected, CPython is allowed to re-use its id. If instead you assign them outside of the expression: nothing = "!" x = "hello" + nothing y = "hello" + nothing id(x) == id(y) #>>> False the collection cannot happen. Note that in this case CPython is allowed to deduplicate these strings anyway (although in this case it does not), so using "is" here is not safe. From ethan at stoneleaf.us Sun Oct 26 20:24:48 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 26 Oct 2014 17:24:48 -0700 Subject: id == vs is In-Reply-To: <544D9084.1010103@stoneleaf.us> References: <544D9084.1010103@stoneleaf.us> Message-ID: <544D90D0.8080807@stoneleaf.us> On 10/26/2014 05:23 PM, Ethan Furman wrote: > On 10/26/2014 05:12 PM, Dan Stromberg wrote: >> Are the following two expressions the same? >> >> x is y >> >> Id(x) == id(y) >> >> ? Listen to MRAB, ignore me. That is all. -- ~Ethan~ From ethan at stoneleaf.us Sun Oct 26 20:23:32 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Sun, 26 Oct 2014 17:23:32 -0700 Subject: id == vs is In-Reply-To: References: Message-ID: <544D9084.1010103@stoneleaf.us> On 10/26/2014 05:12 PM, Dan Stromberg wrote: > Are the following two expressions the same? > > x is y > > Id(x) == id(y) > > ? Nope. If the value if `id(x)` is not interned, then the two value could be different objects that still represent the same value. -- ~Ethan~ From ben+python at benfinney.id.au Sun Oct 26 20:38:13 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 27 Oct 2014 11:38:13 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <544c754b$0$12991$c3e8da3$5496439d@news.astraweb.com> Message-ID: <854muq2vpm.fsf@benfinney.id.au> Steven D'Aprano writes: > Do you really not see the connection between counting and summing? Connection? Of course. But I also see a huge distinction. I'm surprised you could misunderstand my position to the extent you think such a question needs to be asked. The difference between ?sum these values? versus ?count these values? is important. That's at the root of why I find it confusingly wrong to sum True or False values. Do you really not see the distinction between counting and summing? The question is just as silly that way. > If you have three apples, and I have two apples, then in total we have > (count the apples: one two three, four five) five apples. If you have three apples in one basket, and I have two apples in one basket, ?sum the baskets? is quite a different operation from ?count the baskets?. [3, 2] What is the sum of those values? How many values are there? The distinction between those is why I find it unhelpful to express ?how many values?? with ?sum them?. > Alas, you missed the bigger bug: I'm counting *blank lines*, not > non-blank lines. You need a `not` in there. Which is, shall we say, not incompatible with the position that the ?count the matches by summing bools? method is an unclear expression of intent :-) -- \ ?Sittin' on the fence, that's a dangerous course / You can even | `\ catch a bullet from the peace-keeping force? ?Dire Straits, | _o__) _Once Upon A Time In The West_ | Ben Finney From python at mrabarnett.plus.com Sun Oct 26 20:41:26 2014 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 27 Oct 2014 00:41:26 +0000 Subject: id == vs is In-Reply-To: <544D90D0.8080807@stoneleaf.us> References: <544D9084.1010103@stoneleaf.us> <544D90D0.8080807@stoneleaf.us> Message-ID: <544D94B5.80502@mrabarnett.plus.com> On 2014-10-27 00:24, Ethan Furman wrote: > On 10/26/2014 05:23 PM, Ethan Furman wrote: >> On 10/26/2014 05:12 PM, Dan Stromberg wrote: >>> Are the following two expressions the same? >>> >>> x is y >>> >>> Id(x) == id(y) >>> >>> ? > > Listen to MRAB, ignore me. > > That is all. > Well, apart of Joshua's qualifications, that is! :-) From ben+python at benfinney.id.au Sun Oct 26 20:40:24 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 27 Oct 2014 11:40:24 +1100 Subject: id == vs is References: Message-ID: <85zjci1h1j.fsf@benfinney.id.au> Dan Stromberg writes: > Are the following two expressions the same? > > x is y > > Id(x) == id(y) It depends what you mean by ?the same?. Do they give the same result? Sometimes yes, sometimes no. It depends on what the types of the values are. Do they express the same intent? Always no. The first queries object identity, the second queries object equality. -- \ ?Ridicule is the only weapon which can be used against | `\ unintelligible propositions.? ?Thomas Jefferson, 1816-07-30 | _o__) | Ben Finney From python at mrabarnett.plus.com Sun Oct 26 21:40:29 2014 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 27 Oct 2014 01:40:29 +0000 Subject: (test) ? a:b In-Reply-To: <854muq2vpm.fsf@benfinney.id.au> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <544c754b$0$12991$c3e8da3$5496439d@news.astraweb.com> <854muq2vpm.fsf@benfinney.id.au> Message-ID: <544DA28D.6020202@mrabarnett.plus.com> On 2014-10-27 00:38, Ben Finney wrote: > Steven D'Aprano writes: > >> Do you really not see the connection between counting and summing? > > Connection? Of course. But I also see a huge distinction. I'm surprised > you could misunderstand my position to the extent you think such a > question needs to be asked. > > The difference between ?sum these values? versus ?count these values? is > important. That's at the root of why I find it confusingly wrong to sum > True or False values. > > Do you really not see the distinction between counting and summing? > > The question is just as silly that way. > >> If you have three apples, and I have two apples, then in total we have >> (count the apples: one two three, four five) five apples. > > If you have three apples in one basket, and I have two apples in one > basket, ?sum the baskets? is quite a different operation from ?count the > baskets?. > > [3, 2] > > What is the sum of those values? > > How many values are there? > Those are ints. The question is whether you can sum bools. Python's way is to say that it's counting how many True there are. Sometimes it's useful; pragmatism beats purity, and all that. > The distinction between those is why I find it unhelpful to express ?how > many values?? with ?sum them?. > >> Alas, you missed the bigger bug: I'm counting *blank lines*, not >> non-blank lines. You need a `not` in there. > > Which is, shall we say, not incompatible with the position that the > ?count the matches by summing bools? method is an unclear expression of > intent :-) > From denismfmcmahon at gmail.com Sun Oct 26 21:47:40 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Mon, 27 Oct 2014 01:47:40 +0000 (UTC) Subject: id == vs is References: Message-ID: On Sun, 26 Oct 2014 17:12:29 -0700, Dan Stromberg wrote: > Are the following two expressions the same? > > x is y > > Id(x) == id(y) No, although if "Id" and "id" were the same function, they might be equivalent in some cases. -- Denis McMahon, denismfmcmahon at gmail.com From joshua at landau.ws Sun Oct 26 21:55:01 2014 From: joshua at landau.ws (Joshua Landau) Date: Mon, 27 Oct 2014 01:55:01 +0000 Subject: (test) ? a:b In-Reply-To: <85oasz3an3.fsf@benfinney.id.au> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <85oasz3an3.fsf@benfinney.id.au> Message-ID: On 26 October 2014 01:03, Ben Finney wrote: > Steven D'Aprano writes: > >> I suspect that Guido and the core developers disagree with you, since >> they had the opportunity to fix that in Python 3 and didn't. > > That doesn't follow; there are numerous warts in Python 2 that were not > fixed in Python 3. As I understand it, the preservation of bool?int > equality has more to do with preserving backward compatibility. Guido van Rossum answered Jul 28 '11 at 21:20, http://stackoverflow.com/questions/3174392/is-it-pythonic-to-use-bools-as-ints > False==0 and True==1, and there's nothing wrong with that. From rustompmody at gmail.com Sun Oct 26 22:19:39 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 26 Oct 2014 19:19:39 -0700 (PDT) Subject: (test) ? a:b In-Reply-To: <544c754b$0$12991$c3e8da3$5496439d@news.astraweb.com> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <544c754b$0$12991$c3e8da3$5496439d@news.astraweb.com> Message-ID: <82b3ae24-ee75-488c-99dc-a2e7adbc6e6d@googlegroups.com> On Sunday, October 26, 2014 9:45:22 AM UTC+5:30, Steven D'Aprano wrote: > http://legacy.python.org/dev/peps/pep-0285/ > Ben Finney wrote: > > > > I agree with the decision, because this isn't an issue which often leads > > to *incorrect* code. But I maintain that it's an unfortunate and > > needlessly confusing wart of the language. > > That puts you in the small but vocal minority :-) I'm sure that as the author of stats module you know of 'sampling error'! Hint: There are two rather different populations to consider here for drawing the sample - pythonistas - textbook-istas Analogous to another oft-seen argument -- variables. A python variable is time-varying (like most programming languages) A python variable is not a mathematical variable. Historically: 1st HLL was FORTRAN which first introduced variables in trying to come closer to math (note the name FORmula TRANslator) Fortran's approximation was quite a good attempt for 1957. Less and less so as people understood the consequences. Until 1978 its creator was awarded for his creation and in his acceptance apologized for his mistakes -- Section 4 http://web.stanford.edu/class/cs242/readings/backus.pdf tl;dr People make mistakes. Mistakes can be corrected ================== Of course 1. There are the logical operators and, xor 2. Put them into a certain config -- half-adder https://en.wikipedia.org/wiki/Adder_%28electronics%29#Half_adder 3. [Keep reading down]. .. full-adder 4. Ripple-carry adder : : 5. ALU ie Arithmetic Logic Unit IOW arithmetic/logic distinctions are fuzzy. "Distinctions are fuzzy" ? "Should not be made" [In my book!] From ben+python at benfinney.id.au Sun Oct 26 22:28:38 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 27 Oct 2014 13:28:38 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <85oasz3an3.fsf@benfinney.id.au> Message-ID: <85vbn61c15.fsf@benfinney.id.au> Joshua Landau writes: > Guido van Rossum answered Jul 28 '11 at 21:20, > http://stackoverflow.com/questions/3174392/is-it-pythonic-to-use-bools-as-ints > > False==0 and True==1, and there's nothing wrong with that. Guido is incorrect. I've already stated what's wrong. That's different from saying I want to change how Python behaves *now*, of course. But to say ?there's nothing wrong with that? dismisses the problems without addressing them. Guido isn't perfect, so that's okay. -- \ ?Telling pious lies to trusting children is a form of abuse, | `\ plain and simple.? ?Daniel Dennett, 2010-01-12 | _o__) | Ben Finney From Seymore4Head at Hotmail.invalid Sun Oct 26 22:27:18 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 26 Oct 2014 22:27:18 -0400 Subject: Classes and the command line Message-ID: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> I am trying to learn classes. I am currently using Python 2.7 at the command line. If you try to type commands at the command line and make the slightest mistake you have to start over. I was trying to copy and paste these instructions into the command prompt. http://en.wikibooks.org/wiki/Python_Programming/Classes >>> class Foo: ... def setx(self, x): ... self.x = x ... def bar(self): ... print self.x There is really no way to do that without pasting line by line is there and adding deleting spaces? And if you use spaces and tabs, they are not the same. http://imgur.com/a/XTkAm From rustompmody at gmail.com Sun Oct 26 22:38:28 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 26 Oct 2014 19:38:28 -0700 (PDT) Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <85oasz3an3.fsf@benfinney.id.au> Message-ID: On Monday, October 27, 2014 7:59:04 AM UTC+5:30, Ben Finney wrote: > Joshua Landau writes: > > > Guido van Rossum answered Jul 28 '11 at 21:20, > > http://stackoverflow.com/questions/3174392/is-it-pythonic-to-use-bools-as-ints > > > False==0 and True==1, and there's nothing wrong with that. > > Guido is incorrect. I've already stated what's wrong. > > That's different from saying I want to change how Python behaves *now*, > of course. But to say "there's nothing wrong with that" dismisses the > problems without addressing them. Guido isn't perfect, so that's okay. Yes; thats my position also (here and in general). Language changes can be (hugely) disruptive. The cost/benefit of disruption/improvement is always to be considered Does not mean the choices are perfect. In particular, when introducing a beginner, its best if teachers are upfront about goofups. It helps everyone. Helps... - the noob who is saved from self-flagellating "Am I a fool?" - helps the python ecosystem: "These guys are straightforward; dont cover up their mistakes" - etc -- eg noob's future employer From joshua at landau.ws Sun Oct 26 22:43:16 2014 From: joshua at landau.ws (Joshua Landau) Date: Mon, 27 Oct 2014 02:43:16 +0000 Subject: (test) ? a:b In-Reply-To: <85vbn61c15.fsf@benfinney.id.au> References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <85oasz3an3.fsf@benfinney.id.au> <85vbn61c15.fsf@benfinney.id.au> Message-ID: On 27 October 2014 02:28, Ben Finney wrote: > Joshua Landau writes: > >> Guido van Rossum answered Jul 28 '11 at 21:20, >> http://stackoverflow.com/questions/3174392/is-it-pythonic-to-use-bools-as-ints >> > False==0 and True==1, and there's nothing wrong with that. > > Guido is incorrect. I've already stated what's wrong. You were arguing about what Guido thinks. I'm pretty sure Guido gets first say in that, regardless of whether anyone agrees with him. Regardless, I feel you're making this out as a black and white issue. Guido isn't incorrect, he just has a different opinion. Designing a language and calling things "wrong" or "right" gets you Haskell. You can discuss the advantages of each approach without drawing lines in the sand. Although if you do want a language like Haskell, there are a few great choices to chose from. From ben+python at benfinney.id.au Sun Oct 26 22:56:22 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 27 Oct 2014 13:56:22 +1100 Subject: (test) ? a:b References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <7d2ea3c1-504e-4f5c-8338-501b1483df38@googlegroups.com> <878uk6x5nd.fsf@elektro.pacujo.net> <544a1016$0$13000$c3e8da3$5496439d@news.astraweb.com> <544b2f15$0$12978$c3e8da3$5496439d@news.astraweb.com> <544c3bde$0$12988$c3e8da3$5496439d@news.astraweb.com> <85oasz3an3.fsf@benfinney.id.au> <85vbn61c15.fsf@benfinney.id.au> Message-ID: <85r3xu1aqx.fsf@benfinney.id.au> Joshua Landau writes: > On 27 October 2014 02:28, Ben Finney wrote: > > Guido is incorrect. I've already stated what's wrong. > > You were arguing about what Guido thinks. I don't know where I did that; to my knowledge, this is the first time I've mentioned Guido, and it's in rebuttal to his authority on the issue of whether ?there's nothing wrong with? bool-as-a-special-int. (On the separate issue of whether Guido is an authority on how Python will behave, I haven't even commented. To be clear: yes, he is the BDFL and therefore is authoritative on that issue.) > Regardless, I feel you're making this out as a black and white issue. There either is something problematic with a behaviour, or there isn't. The *degree* of wrongness can vary. I'm merely pointing out that, in this case, it's non-zero. -- \ ?I must say that I find television very educational. The minute | `\ somebody turns it on, I go to the library and read a book.? | _o__) ?Groucho Marx | Ben Finney From Seymore4Head at Hotmail.invalid Sun Oct 26 22:57:38 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 26 Oct 2014 22:57:38 -0400 Subject: Python tutorials Message-ID: Python tutorials http://anandology.com/python-practice-book/object_oriented_programming.html This is a good one....but it gets too deep too fast. This is the best thing I have read so far to help me understand classes. What I would like to see is more examples of computing before starting on drawing examples. I have to practice the first few steps of a dance before trying the whole thing. For anyone here that might have an interest in making tutorials, using something useful as an example instead of using foo and bar helps me a lot towards understanding the concept too. From ben+python at benfinney.id.au Sun Oct 26 23:06:11 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 27 Oct 2014 14:06:11 +1100 Subject: Classes and the command line References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> Message-ID: <85mw8i1aak.fsf@benfinney.id.au> Seymore4Head writes: > I am trying to learn classes. > I am currently using Python 2.7 at the command line. (I think you mean ?the interactive Python interpreter?, or just ?the Python shell?.) Since you are learning Python, I will strongly recommend you ignore Python 2 unless it becomes unavoidable. Instead, learn Python 3 primarily; it is much better because it omits a bunch of legacy behaviour you don't need. > If you try to type commands at the [interactive shell] and make the > slightest mistake you have to start over. Right. There is line-by-line history, and editing enabled with the ?readline? plug-in. (This is an advantage of using a programmer-friendly operating system, which MS Windows sadly is not.) > I was trying to copy and paste these instructions into the > [interactive Python shell]. > > http://en.wikibooks.org/wiki/Python_Programming/Classes > >>> class Foo: > ... def setx(self, x): > ... self.x = x > ... def bar(self): > ... print self.x > > There is really no way to do that without pasting line by line is > there and adding deleting spaces? And if you use spaces and tabs, > they are not the same. Right on all counts. The interactive Python shell is good for very quickly experimenting and demonstrating how Python actually behaves, statement by statement. But as you point out, it is not a good choice for anything more complex. It is a good learning and debugging tool. When you start to write larger units of code, like a class or a function, you can trade immediacy for flexibility: write your code into a text editor, save it to a file ?foo.py?, then run that code at a separate OS command prompt by invoking ?python foo.py? in the terminal. That way, you can continue to adjust and tweak the code as you learn how your changes affect the code. You do need to keep invoking the actions separately ? edit the file, save the file, run the file with Python ? but this is what's needed when you want to run a program more than once anyway, so it's a good step to take. Find a good, *general-purpose* programmer's editor. Preferably licensed under free software terms, with a strong community supporting it, and available on all major platforms for when you switch to a decent programmer-friendly operating system. -- \ ?When you go in for a job interview, I think a good thing to | `\ ask is if they ever press charges.? ?Jack Handey | _o__) | Ben Finney From cs at zip.com.au Sun Oct 26 22:36:11 2014 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 27 Oct 2014 13:36:11 +1100 Subject: id == vs is In-Reply-To: <544D94B5.80502@mrabarnett.plus.com> References: <544D94B5.80502@mrabarnett.plus.com> Message-ID: <20141027023611.GA40189@cskk.homeip.net> On 27Oct2014 00:41, MRAB wrote: >On 2014-10-27 00:24, Ethan Furman wrote: >>On 10/26/2014 05:23 PM, Ethan Furman wrote: >>>On 10/26/2014 05:12 PM, Dan Stromberg wrote: >>>>Are the following two expressions the same? >>>> >>>>x is y >>>> >>>>Id(x) == id(y) >>>> >>>>? >> >>Listen to MRAB, ignore me. >>That is all. >> >Well, apart of Joshua's qualifications, that is! :-) Let's make it clear for the OP, since this thread seems to have wandered into the realms of the confusing, for what is a basic question. The short answer is "yes". The longer answer is: if nobody else is fiddling with "x" and "y" and if id() is the normal builtin python "id" function Then yes. The "is" test is more direct and less subject to iffiness because the longer expression using id() leaves more scope/time for things to change, and of course "id" itself can be rebound to something weird. Cheers, Cameron Simpson The significant problems we face cannot be solved at the same level of thinking we were at when we created them. - Albert Einstein From rustompmody at gmail.com Sun Oct 26 23:05:43 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 26 Oct 2014 20:05:43 -0700 (PDT) Subject: Classes and the command line In-Reply-To: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> Message-ID: On Monday, October 27, 2014 8:00:04 AM UTC+5:30, Seymore4Head wrote: > I am trying to learn classes. > I am currently using Python 2.7 at the command line. Why not idle? And if in general you are at python 3, why 2.7 here? There are enough factor to learn ( and get confused)! Please dont add new ones gratuitously! > If you try to type commands at the command line and make the slightest > mistake you have to start over. > I was trying to copy and paste these instructions into the command > prompt. > > http://en.wikibooks.org/wiki/Python_Programming/Classes > >>> class Foo: > ... def setx(self, x): > ... self.x = x > ... def bar(self): > ... print self.x > > There is really no way to do that without pasting line by line is > there and adding deleting spaces? And if you use spaces and tabs, > they are not the same. > > http://imgur.com/a/XTkAm Let me repeat and elaborate what I have already told you -- - you should write mostly expressions at the interpreter prompt - you should write definitions in the file Rough distinctions: 1. Things like 1+2, lst.append(3) etc are expressions 2. Things like assignment, if, while are statements 3. class and def statements are special; and called definitions Notes a. theres an inclusion 1 'sits inside' 2 'sits inside' 3 b. Its easiest if you try 1 in the interpreter; 3 in the python file c. 2 is a bit clumsy. Short ones can be tried at the interpreter Longer than 3 (max 4) lines should go into files. May require a bit of thought how to package a statement into a definition to try out d. 2 is clumsy in files for a different reason; you will need to write prints judiciously e. Since def itself goes into class, if youve not yet worked out a comfortable 'tryin-out' model, stay with defs for now In short: For a while people here have been advising you "Use the Interpreter" Now I will add slightly to that: Use the interpreter in idle, along with a python file From rosuav at gmail.com Sun Oct 26 23:10:01 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 27 Oct 2014 14:10:01 +1100 Subject: Classes and the command line In-Reply-To: <85mw8i1aak.fsf@benfinney.id.au> References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> <85mw8i1aak.fsf@benfinney.id.au> Message-ID: On Mon, Oct 27, 2014 at 2:06 PM, Ben Finney wrote: > Right. There is line-by-line history, and editing enabled with the > ?readline? plug-in. (This is an advantage of using a programmer-friendly > operating system, which MS Windows sadly is not.) You can get block-by-block history by using Idle. I find that fairly convenient for manipulating class/function definitions. ChrisA From ben+python at benfinney.id.au Sun Oct 26 23:13:56 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 27 Oct 2014 14:13:56 +1100 Subject: id == vs is References: <85zjci1h1j.fsf@benfinney.id.au> Message-ID: <85ioj619xn.fsf@benfinney.id.au> Ben Finney writes: > Dan Stromberg writes: > > Are the following two expressions the same? [?] > > It depends what you mean by ?the same?. My apologies, I mis-read the question. My answers were for a different question (one you didn't ask). Please ignore that. -- \ ?If you ever reach total enlightenment while you're drinking a | `\ beer, I bet it makes beer shoot out your nose.? ?Jack Handey | _o__) | Ben Finney From rustompmody at gmail.com Sun Oct 26 23:18:37 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 26 Oct 2014 20:18:37 -0700 (PDT) Subject: Classes and the command line In-Reply-To: References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> <85mw8i1aak.fsf@benfinney.id.au> Message-ID: <0d42e474-a864-4155-b602-e4659899fffd@googlegroups.com> On Monday, October 27, 2014 8:40:48 AM UTC+5:30, Chris Angelico wrote: > On Mon, Oct 27, 2014 at 2:06 PM, Ben Finney wrote: > > Right. There is line-by-line history, and editing enabled with the > > "readline" plug-in. (This is an advantage of using a programmer-friendly > > operating system, which MS Windows sadly is not.) > > You can get block-by-block history by using Idle. I find that fairly > convenient for manipulating class/function definitions. > > ChrisA Umm... Nice! A bit inconsistent in that the '...' does not appear. But thats good; makes copy|cut-pasting from interpreter to file a mostly trivial operation. From rosuav at gmail.com Sun Oct 26 23:24:55 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 27 Oct 2014 14:24:55 +1100 Subject: Classes and the command line In-Reply-To: <0d42e474-a864-4155-b602-e4659899fffd@googlegroups.com> References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> <85mw8i1aak.fsf@benfinney.id.au> <0d42e474-a864-4155-b602-e4659899fffd@googlegroups.com> Message-ID: On Mon, Oct 27, 2014 at 2:18 PM, Rustom Mody wrote: > On Monday, October 27, 2014 8:40:48 AM UTC+5:30, Chris Angelico wrote: >> On Mon, Oct 27, 2014 at 2:06 PM, Ben Finney wrote: >> > Right. There is line-by-line history, and editing enabled with the >> > "readline" plug-in. (This is an advantage of using a programmer-friendly >> > operating system, which MS Windows sadly is not.) >> >> You can get block-by-block history by using Idle. I find that fairly >> convenient for manipulating class/function definitions. >> >> ChrisA > > Umm... Nice! > A bit inconsistent in that the '...' does not appear. > But thats good; makes copy|cut-pasting from interpreter to file > a mostly trivial operation. It's inconsistent only because the default sys.ps2 is those dots, which aren't necessary in Idle. You could make it consistent by simply changing sys.ps2. ChrisA From rustompmody at gmail.com Sun Oct 26 23:30:08 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Sun, 26 Oct 2014 20:30:08 -0700 (PDT) Subject: Classes and the command line In-Reply-To: <0d42e474-a864-4155-b602-e4659899fffd@googlegroups.com> References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> <85mw8i1aak.fsf@benfinney.id.au> <0d42e474-a864-4155-b602-e4659899fffd@googlegroups.com> Message-ID: <7bfbcd4d-65a4-4608-b0cc-f13292d1a918@googlegroups.com> On Monday, October 27, 2014 8:48:52 AM UTC+5:30, Rustom Mody wrote: > On Monday, October 27, 2014 8:40:48 AM UTC+5:30, Chris Angelico wrote: > > On Mon, Oct 27, 2014 at 2:06 PM, Ben Finney wrote: > > > Right. There is line-by-line history, and editing enabled with the > > > "readline" plug-in. (This is an advantage of using a programmer-friendly > > > operating system, which MS Windows sadly is not.) > > > > You can get block-by-block history by using Idle. I find that fairly > > convenient for manipulating class/function definitions. > > > > ChrisA > > Umm... Nice! > A bit inconsistent in that the '...' does not appear. > But thats good; makes copy|cut-pasting from interpreter to file > a mostly trivial operation. No not quite so nice... Does not respect the current indent level :-( [which an emacs 'rectangle' copy-paste will] From Seymore4Head at Hotmail.invalid Sun Oct 26 23:28:40 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 26 Oct 2014 23:28:40 -0400 Subject: Classes and the command line References: Message-ID: Your message showed up as unavailable on my server I have to cut and paste Google Groups to reply. (I am going to change news servers probably tomorrow to try to fix that) So the quoting is going to be bad. ---- Why not idle? And if in general you are at python 3, why 2.7 here? There are enough factor to learn ( and get confused)! Please don't add new ones gratuitously! ------- I am taking two courses in Python 2 so I think I am going to forget using Python 3 until I finish the courses. One of the course instructors suggests we try the command like way. Your other explanations on the distinctions are helpful, but for now I am going with Python 2. Final answer. :) (A few more weeks) They are teaching Python 2. I have to use Python 2 to learn it. Thanks I am going to be flexible on IDLE in the near future, but I wanted to try it the old fashion way. I already know using IDLE is better, but I am not sure using IDLE will invoke Python 2 and I am not sure how to change that at the moment. From Seymore4Head at Hotmail.invalid Sun Oct 26 23:32:08 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 26 Oct 2014 23:32:08 -0400 Subject: Classes and the command line References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> Message-ID: On Mon, 27 Oct 2014 14:06:11 +1100, Ben Finney wrote: >Seymore4Head writes: > >> I am trying to learn classes. >> I am currently using Python 2.7 at the command line. > >(I think you mean ?the interactive Python interpreter?, or just ?the >Python shell?.) > >Since you are learning Python, I will strongly recommend you ignore >Python 2 unless it becomes unavoidable. > At the moment, it is unavoidable. The instructors are teaching Python 2 so I have to learn Python 2, for now. >Instead, learn Python 3 primarily; it is much better because it omits a >bunch of legacy behaviour you don't need. > >> If you try to type commands at the [interactive shell] and make the >> slightest mistake you have to start over. > >Right. There is line-by-line history, and editing enabled with the >?readline? plug-in. (This is an advantage of using a programmer-friendly >operating system, which MS Windows sadly is not.) > >> I was trying to copy and paste these instructions into the >> [interactive Python shell]. >> >> http://en.wikibooks.org/wiki/Python_Programming/Classes >> >>> class Foo: >> ... def setx(self, x): >> ... self.x = x >> ... def bar(self): >> ... print self.x >> >> There is really no way to do that without pasting line by line is >> there and adding deleting spaces? And if you use spaces and tabs, >> they are not the same. > >Right on all counts. > >The interactive Python shell is good for very quickly experimenting and >demonstrating how Python actually behaves, statement by statement. But >as you point out, it is not a good choice for anything more complex. It >is a good learning and debugging tool. > >When you start to write larger units of code, like a class or a >function, you can trade immediacy for flexibility: write your code into >a text editor, save it to a file ?foo.py?, then run that code at a >separate OS command prompt by invoking ?python foo.py? in the terminal. > >That way, you can continue to adjust and tweak the code as you learn how >your changes affect the code. You do need to keep invoking the actions >separately ? edit the file, save the file, run the file with Python ? >but this is what's needed when you want to run a program more than once >anyway, so it's a good step to take. > >Find a good, *general-purpose* programmer's editor. Preferably licensed >under free software terms, with a strong community supporting it, and >available on all major platforms for when you switch to a decent >programmer-friendly operating system. I am actually using Notepad some too. Thanks From Seymore4Head at Hotmail.invalid Sun Oct 26 23:33:40 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Sun, 26 Oct 2014 23:33:40 -0400 Subject: Classes and the command line References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> <85mw8i1aak.fsf@benfinney.id.au> Message-ID: On Mon, 27 Oct 2014 14:10:01 +1100, Chris Angelico wrote: >On Mon, Oct 27, 2014 at 2:06 PM, Ben Finney wrote: >> Right. There is line-by-line history, and editing enabled with the >> ?readline? plug-in. (This is an advantage of using a programmer-friendly >> operating system, which MS Windows sadly is not.) > >You can get block-by-block history by using Idle. I find that fairly >convenient for manipulating class/function definitions. > >ChrisA Thanks BTW I am using XP some and Win7 some too. From ganesh1pal at gmail.com Mon Oct 27 00:49:19 2014 From: ganesh1pal at gmail.com (Ganesh Pal) Date: Mon, 27 Oct 2014 10:19:19 +0530 Subject: Python Fabric on Windows : Message-ID: Hi Team , Iam new to Fabric and Iam using the fab command-line tool to run a set of task on Linux clients. I just started coding and Iam pretty new to fabric, Iam hoping I will be able to launch my fabric scripts from both Windows and Linux Machine . Installing Cygwin might help in windows case I guess. please suggest if you foresee problems using fabric on Windows and also suggest an alternative to this if available. . Regards, Ganesh -------------- next part -------------- An HTML attachment was scrubbed... URL: From diyaraik at gmail.com Mon Oct 27 01:12:09 2014 From: diyaraik at gmail.com (Diya Rai) Date: Sun, 26 Oct 2014 22:12:09 -0700 (PDT) Subject: 403 forbidden error In-Reply-To: <82d4292e-10de-4d47-882e-bab75777fbfe@googlegroups.com> References: <82d4292e-10de-4d47-882e-bab75777fbfe@googlegroups.com> Message-ID: <04b6b33f-885e-4e4a-b458-b258b34fbb90@googlegroups.com> On Wednesday, October 22, 2014 5:07:00 PM UTC+5:30, Diya Rai wrote: > Hai, > > Could anyone please help me to resolve 403 forbidden error while logging into an application. > > Following is the error details: > > Traceback (most recent call last): > File "./example6.py", line 18, in > response = urllib2.urlopen(req) > File "/usr/lib/python2.7/urllib2.py", line 126, in urlopen > return _opener.open(url, data, timeout) > File "/usr/lib/python2.7/urllib2.py", line 406, in open > response = meth(req, response) > File "/usr/lib/python2.7/urllib2.py", line 519, in http_response > 'http', request, response, code, msg, hdrs) > File "/usr/lib/python2.7/urllib2.py", line 444, in error > return self._call_chain(*args) > File "/usr/lib/python2.7/urllib2.py", line 378, in _call_chain > result = func(*args) > File "/usr/lib/python2.7/urllib2.py", line 527, in http_error_default > raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) > urllib2.HTTPError: HTTP Error 403: FORBIDDEN > > > Sorry if the question is not relevant as im new to python. > > > Regards, > Diya Thanks Chris Angelico and Dennis Lee Bieber for replying. Username and password is correct. Its a simple login script. import urllib import httplib2 http = httplib2.Http() url = 'http://localhost/login_ajax' body = {'email': 'xyz at google.com', 'password': '*******'} headers = {'Content-type': 'application/x-www-form-urlencoded'} response, content = http.request(url, 'POST', headers=headers, body=urllib.urlencode(body)) print response This is the part of the code which im trying to execute. We are trying to load test a web application through python script, currently checking the login part. Thanks in advance, Diya From rosuav at gmail.com Mon Oct 27 01:34:41 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 27 Oct 2014 16:34:41 +1100 Subject: 403 forbidden error In-Reply-To: <04b6b33f-885e-4e4a-b458-b258b34fbb90@googlegroups.com> References: <82d4292e-10de-4d47-882e-bab75777fbfe@googlegroups.com> <04b6b33f-885e-4e4a-b458-b258b34fbb90@googlegroups.com> Message-ID: On Mon, Oct 27, 2014 at 4:12 PM, Diya Rai wrote: > This is the part of the code which im trying to execute. We are trying to load test a web application through python script, currently checking the login part. > Does it work when you log in using a web browser? If so, grab a browser with debugging facilities (Firefox with Firebug, or Chrome with its F12 box, or something), do the login, and have a look at exactly what request headers are being sent. Then compare with what your script is doing. Once you have the two side by side, you can progressively work through it until you figure out which header makes the difference - maybe your script isn't sending Host, or maybe you need a cookie from a previous request, or maybe it's actually checking the Referer and rejecting if it isn't right. Could be all sorts of things. Good luck! Might be a tedious job, or might be the first thing you try. ChrisA From diyaraik at gmail.com Mon Oct 27 01:56:43 2014 From: diyaraik at gmail.com (Diya Rai) Date: Sun, 26 Oct 2014 22:56:43 -0700 (PDT) Subject: 403 forbidden error In-Reply-To: References: <82d4292e-10de-4d47-882e-bab75777fbfe@googlegroups.com> <04b6b33f-885e-4e4a-b458-b258b34fbb90@googlegroups.com> Message-ID: On Monday, October 27, 2014 11:05:04 AM UTC+5:30, Chris Angelico wrote: > On Mon, Oct 27, 2014 at 4:12 PM, Diya Rai wrote: > > This is the part of the code which im trying to execute. We are trying to load test a web application through python script, currently checking the login part. > > > > Does it work when you log in using a web browser? If so, grab a > browser with debugging facilities (Firefox with Firebug, or Chrome > with its F12 box, or something), do the login, and have a look at > exactly what request headers are being sent. Then compare with what > your script is doing. Once you have the two side by side, you can > progressively work through it until you figure out which header makes > the difference - maybe your script isn't sending Host, or maybe you > need a cookie from a previous request, or maybe it's actually checking > the Referer and rejecting if it isn't right. Could be all sorts of > things. > > Good luck! Might be a tedious job, or might be the first thing you try. > > ChrisA Thanks a lot ChrisA It works fine while logging in through browser. Im using firefox, and have checked the headers with firebug. I tried passing all the headers and it works while passing the cookie header. My question is whether is it the correct way to try or can i write python script in such a way that it can handle it automatically. Currently for checking login page, it would be fine.But when we go for testing registration page it become tedious. I would also like to get your opinion on load testing with python script. Thanks in advance, Diya From stefan_ml at behnel.de Mon Oct 27 03:28:10 2014 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 27 Oct 2014 08:28:10 +0100 Subject: XML Patch In-Reply-To: References: Message-ID: Hi, please keep this on-list. Nicholas Cole schrieb am 26.10.2014 um 22:43: > On Sun, Oct 26, 2014 at 6:30 PM, Stefan Behnel wrote: >> Nicholas Cole schrieb am 26.10.2014 um 18:00: >>> I'm looking for a python library that can parse XML Documents and >>> create xml-aware "diff" files, and then use those to patch >>> documents. In other words, I'd like something similar to the Google >>> diff-match-patch tools, but something which is XML aware. >>> >>> I can see several projects on Pypi that can generate some form of >>> xml diff, but I can't seem to see anything that can also do the >>> patching side of things. >> >> Is there a use case for this? > > Yes - I want to store a series of XML diffs/patches and be able to > generate documents by applying them. Could you be a little more specific? There are lots of ways to generate XML, but I never heard of anyone who wanted to do this based on diffs between other documents. What kind of document differences are you talking about here? Stefan From nicholas.cole at gmail.com Mon Oct 27 03:49:14 2014 From: nicholas.cole at gmail.com (Nicholas Cole) Date: Mon, 27 Oct 2014 07:49:14 +0000 Subject: XML Patch In-Reply-To: References: Message-ID: On Mon, Oct 27, 2014 at 7:28 AM, Stefan Behnel wrote: > Hi, > > please keep this on-list. Sorry about that. Wrong button! [snip] >> Yes - I want to store a series of XML diffs/patches and be able to >> generate documents by applying them. > > Could you be a little more specific? There are lots of ways to generate > XML, but I never heard of anyone who wanted to do this based on diffs > between other documents. What kind of document differences are you talking > about here? I don't think the specific documents matter, and I don't think it's a unique use-case. Here's Microsoft talking about XML diff and patching (including a hypothetical example): http://msdn.microsoft.com/en-gb/library/aa302294.aspx There's a tool here to do it: http://xmlpatch.sourceforge.net I'd just really like to be able to do something similar in Python. Best wishes, N. From nomail at invalid.com Mon Oct 27 04:01:31 2014 From: nomail at invalid.com (ast) Date: Mon, 27 Oct 2014 09:01:31 +0100 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> <544775ca$0$2146$426a74cc@news.free.fr> Message-ID: <544dfbdf$0$2148$426a74cc@news.free.fr> "Mark Lawrence" a ?crit dans le message de news:mailman.15070.1413978605.18130.python-list at python.org... > Also would you please access this list via https://mail.python.org/mailman/listinfo/python-list or > read and action this https://wiki.python.org/moin/GoogleGroupsPython to prevent us seeing double > line spacing and single line paragraphs, thanks. Hi I read the last document but it seems that it is intended for those who post messages through Google Groups. I am using a usenet client so i should not be affected It seems that he double blank lines spacing comes from buscacio, not me regards From nomail at invalid.com Mon Oct 27 04:16:26 2014 From: nomail at invalid.com (ast) Date: Mon, 27 Oct 2014 09:16:26 +0100 Subject: Callback functions arguments Message-ID: <544dff5d$0$2073$426a74cc@news.free.fr> Hi In this web site at example n?5 http://fsincere.free.fr/isn/python/cours_python_tkinter.php A program is using the "Scale" widget from tkinter module. Here is a piece of code: Valeur = StringVar() echelle = Scale(Mafenetre, from_=-100, to=100, resolution=10, \ orient=HORIZONTAL, length=300, width=20, label="Offset", \ tickinterval=20, variable=Valeur, command=maj) The "maj" callback function is: def maj(nouvelleValeur): print(nouvelleValeur) When the user move the scale with the mouse, the new position is supposed to be printed on the python shell. The "maj" function has an argument "nouvelleValeur" but no argument is passed through the Scale widget. So how the hell Python knows that it has to pass parameter "Valeur" to the "maj" function ? thx From martin at libtec.org Sat Oct 25 08:42:12 2014 From: martin at libtec.org (Martin) Date: Sat, 25 Oct 2014 15:42:12 +0300 Subject: asyncio: setting file permissions of a Unix socket? Message-ID: <20141025124212.GB27107@localhost> Hi! :) I'm using the asyncio.Protocol interface to build a server which binds to a unix socket file. I want other system users to connect to the unix socket, so to communicate with the server. Where should I set the permissions of the file? The problem is that the socket file is created when the programs starts listening for the connections. Because of this, I can't change the file permission before a connection is made. At the same time, a connection can't happen because of the file permissions. Currently, I workaround this with os.umask(0o000). But I also want to make other files later with default permissions. So I have to revert the umask, but where? I can only do this in the client connection code, which is out of place. Bellow is what I've done. Can you suggest a better way? I wish to avoid permission fixing code like os.umask() for every connection. Maybe I shouldn't use asyncio.Protocol in the first place? Thank you! :) Example code: #! /usr/bin/env python3 import os import asyncio class ExampleServer(asyncio.Protocol): def __init__(self): os.umask(0o002) # This is my workaround. Can I avoid this? # if not umask_restored: # An alternative workaround. # os.umask(0o002) def connection_made(self, transport): self.transport = transport def data_received(self, data): print("Data: ", data) self.transport.write(b"OK, bye!\n") self.transport.close() def main(): socket_filepath = "/tmp/example-server.socket" loop = asyncio.get_event_loop() server_coroutine = loop.create_unix_server(ExampleServer, socket_filepath) server = loop.run_until_complete(server_coroutine) os.umask(0o000) # This is my workaround. try: loop.run_forever() except KeyboardInterrupt: print("exit") finally: server.close() loop.close() os.remove(socket_filepath) if __name__ == "__main__": main() From __peter__ at web.de Mon Oct 27 04:52:33 2014 From: __peter__ at web.de (Peter Otten) Date: Mon, 27 Oct 2014 09:52:33 +0100 Subject: Callback functions arguments References: <544dff5d$0$2073$426a74cc@news.free.fr> Message-ID: ast wrote: > Hi > > In this web site at example n?5 > http://fsincere.free.fr/isn/python/cours_python_tkinter.php > > A program is using the "Scale" widget from tkinter module. > Here is a piece of code: > > Valeur = StringVar() > > echelle = Scale(Mafenetre, from_=-100, to=100, resolution=10, \ > orient=HORIZONTAL, length=300, width=20, label="Offset", \ > tickinterval=20, variable=Valeur, command=maj) > > The "maj" callback function is: > > def maj(nouvelleValeur): > print(nouvelleValeur) > > When the user move the scale with the mouse, the new position > is supposed to be printed on the python shell. > > The "maj" function has an argument "nouvelleValeur" but no > argument is passed through the Scale widget. > > So how the hell Python knows that it has to pass parameter > "Valeur" to the "maj" function ? Python doesn't "know" it has to pass an argument, it just does it. Change the callback to def maj(): print("no args") and you'll get an error. If I were to guess > echelle = Scale(Mafenetre, from_=-100, to=100, resolution=10, \ > orient=HORIZONTAL, length=300, width=20, label="Offset", \ > tickinterval=20, variable=Valeur, command=maj) you probably are misled by the 'command=maj' part in the above line. This means that the function is passed and is different from command=maj() where the *result* of the function is passed. Here's a self-contained example that may clear things up for you: >>> def call_them(one, two): ... one(1) ... two(2, 3) ... >>> def square(a): ... print(a, "*", a, "=", a*a) ... >>> def product(a, b): ... print(a, "*", b, "=", a*b) ... >>> call_them(square, product) 1 * 1 = 1 2 * 3 = 6 >>> call_them(product, product) Traceback (most recent call last): File "", line 1, in File "", line 2, in call_them TypeError: product() missing 1 required positional argument: 'b' call_them() expects that one() takes 1 argument and two() takes 2 arguments. If the user passes a function that expects a different number of arguments a TypeError is raised. From greg.ewing at canterbury.ac.nz Mon Oct 27 05:04:02 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Mon, 27 Oct 2014 22:04:02 +1300 Subject: (test) ? a:b In-Reply-To: References: <54476af8$0$21651$426a74cc@news.free.fr> <7839376e-fc27-4299-ae63-4ddf17ef9a8a@googlegroups.com> Message-ID: Michael Torrie wrote: > As far as I can tell, no BASIC dialect I've looked at (DOS and Linux > worlds only), has ever had any logical operators like AND (&&), OR (||), > and NOT (!). They only appear to have bitwise operators (&,|,~ C > equivalent). The fact that comparison operators returned 0 and -1 made > the bitwise operators function the same as logical. Applesoft used 0 and 1, so its NOT definitely wasn't bitwise on the whole number. I can't remember what its AND and OR did for numbers other than 0 or 1 (if I even thought to try it), but since it did all arithmetic in floating point, I suspect they were logical rather than bitwise. -- Greg From jeanmichel at sequans.com Mon Oct 27 06:19:17 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 27 Oct 2014 11:19:17 +0100 (CET) Subject: Callback functions arguments In-Reply-To: <544dff5d$0$2073$426a74cc@news.free.fr> Message-ID: <1664309009.1365379.1414405157389.JavaMail.root@sequans.com> ----- Original Message ----- > From: "ast" > To: python-list at python.org > Sent: Monday, 27 October, 2014 9:16:26 AM > Subject: Callback functions arguments > > Hi > > In this web site at example n?5 > http://fsincere.free.fr/isn/python/cours_python_tkinter.php > > A program is using the "Scale" widget from tkinter module. > Here is a piece of code: > > Valeur = StringVar() > > echelle = Scale(Mafenetre, from_=-100, to=100, resolution=10, \ > orient=HORIZONTAL, length=300, width=20, label="Offset", \ > tickinterval=20, variable=Valeur, command=maj) > > The "maj" callback function is: > > def maj(nouvelleValeur): > print(nouvelleValeur) > > When the user move the scale with the mouse, the new position > is supposed to be printed on the python shell. > > The "maj" function has an argument "nouvelleValeur" but no > argument is passed through the Scale widget. > > So how the hell Python knows that it has to pass parameter > "Valeur" to the "maj" function ? > > thx The Scale object is performing the call, hence it will be the Scale object that will call your maj function with a "nouvelleValeur" parameter. When you write command=maj, you pass the function, but you don't call it. That's the purpose of a callback. You provide a function and it get called by the object you've been giving the function to. The Scale object should be documented and should provide with the callback signature. See http://effbot.org/zone/tkinter-callbacks.htm JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From michael at stroeder.com Mon Oct 27 06:19:26 2014 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 27 Oct 2014 11:19:26 +0100 Subject: asyncio: setting file permissions of a Unix socket? In-Reply-To: References: Message-ID: Martin wrote: > I'm using the asyncio.Protocol interface to build a server which binds > to a unix socket file. I want other system users to connect to the > unix socket, so to communicate with the server. > > Where should I set the permissions of the file? You should start the demon with a strict umask and set the permissions after the socket is created. Deriving from SocketServer.UnixStreamServer I'm overriding the server_bind() method: class MyServer(SocketServer.UnixStreamServer): [..] def server_bind(self): """Override server_bind to set socket options.""" self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) self.socket.settimeout(SOCKET_TIMEOUT) try: os.unlink(self.server_address) except OSError: if os.path.exists(self.server_address): raise SocketServer.UnixStreamServer.server_bind(self) os.chmod(self.server_address,int(SOCKET_PERMISSIONS,8)) return # server_bind() Ciao, Michael. From jeanmichel at sequans.com Mon Oct 27 06:26:01 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 27 Oct 2014 11:26:01 +0100 (CET) Subject: Classes and the command line In-Reply-To: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> Message-ID: <67123747.1366001.1414405561571.JavaMail.root@sequans.com> ----- Original Message ----- > From: "Seymore4Head" > To: python-list at python.org > Sent: Monday, 27 October, 2014 3:27:18 AM > Subject: Classes and the command line > > I am trying to learn classes. > I am currently using Python 2.7 at the command line. > If you try to type commands at the command line and make the > slightest > mistake you have to start over. > I was trying to copy and paste these instructions into the command > prompt. > > http://en.wikibooks.org/wiki/Python_Programming/Classes > >>> class Foo: > ... def setx(self, x): > ... self.x = x > ... def bar(self): > ... print self.x > > There is really no way to do that without pasting line by line is > there and adding deleting spaces? And if you use spaces and tabs, > they are not the same. You could use Ipython http://ipython.org/, if you're familiar with the python shell you won't get lost as it's quite the same with a lot of features added. One of them is the %paste magic function, it will paste your clipboard taking care of the indentation for you. JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From alister.nospam.ware at ntlworld.com Mon Oct 27 07:17:17 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Mon, 27 Oct 2014 11:17:17 GMT Subject: Classes and the command line References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> Message-ID: <1Rp3w.1$7w2.0@fx01.am4> On Sun, 26 Oct 2014 23:32:08 -0400, Seymore4Head wrote: > On Mon, 27 Oct 2014 14:06:11 +1100, Ben Finney > wrote: > >>Seymore4Head writes: >> >>> I am trying to learn classes. >>> I am currently using Python 2.7 at the command line. >> >>(I think you mean ?the interactive Python interpreter?, or just ?the >>Python shell?.) >> >>Since you are learning Python, I will strongly recommend you ignore >>Python 2 unless it becomes unavoidable. >> > At the moment, it is unavoidable. The instructors are teaching Python 2 > so I have to learn Python 2, for now. > >>Instead, learn Python 3 primarily; it is much better because it omits a >>bunch of legacy behaviour you don't need. >> >>> If you try to type commands at the [interactive shell] and make the >>> slightest mistake you have to start over. >> >>Right. There is line-by-line history, and editing enabled with the >>?readline? plug-in. (This is an advantage of using a programmer- friendly >>operating system, which MS Windows sadly is not.) >> >>> I was trying to copy and paste these instructions into the >>> [interactive Python shell]. >>> >>> http://en.wikibooks.org/wiki/Python_Programming/Classes >>> >>> class Foo: >>> ... def setx(self, x): >>> ... self.x = x ... def bar(self): >>> ... print self.x >>> >>> There is really no way to do that without pasting line by line is >>> there and adding deleting spaces? And if you use spaces and tabs, >>> they are not the same. >> >>Right on all counts. >> >>The interactive Python shell is good for very quickly experimenting and >>demonstrating how Python actually behaves, statement by statement. But >>as you point out, it is not a good choice for anything more complex. It >>is a good learning and debugging tool. >> >>When you start to write larger units of code, like a class or a >>function, you can trade immediacy for flexibility: write your code into >>a text editor, save it to a file ?foo.py?, then run that code at a >>separate OS command prompt by invoking ?python foo.py? in the terminal. >> >>That way, you can continue to adjust and tweak the code as you learn how >>your changes affect the code. You do need to keep invoking the actions >>separately ? edit the file, save the file, run the file with Python ? >>but this is what's needed when you want to run a program more than once >>anyway, so it's a good step to take. >> >>Find a good, *general-purpose* programmer's editor. Preferably licensed >>under free software terms, with a strong community supporting it, and >>available on all major platforms for when you switch to a decent >>programmer-friendly operating system. > > I am actually using Notepad some too. > > Thanks notepad is not a programmer friendly editor personally I like Geany as it is nice and basic but still offers a lot of programmer friendly features such as syntax highlighting, a small terminal window which I use to run the interactive terminal for testing quick one-liners & pressing f5 will save & run the current file being edited. www.geany.org Notepad+ is also often suggested along with many other programmer editors/ Integrated development environments (IDE). I would advise you keep away from the more complex IDE's for now as you do not want to overload your learning requirements. -- Who the mad would destroy, first they make Gods. -- Bernard Levin From rosuav at gmail.com Mon Oct 27 07:33:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 27 Oct 2014 22:33:18 +1100 Subject: Classes and the command line In-Reply-To: <1Rp3w.1$7w2.0@fx01.am4> References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> <1Rp3w.1$7w2.0@fx01.am4> Message-ID: On Mon, Oct 27, 2014 at 10:17 PM, alister wrote: > Notepad+ is also often suggested along with many other programmer editors/ > Integrated development environments (IDE). That would be Notepad++, and yes, it's fairly well recommended. It's based on the same edit component as SciTE, another good editor (and the one I use). ChrisA From steve+comp.lang.python at pearwood.info Mon Oct 27 07:30:57 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Mon, 27 Oct 2014 22:30:57 +1100 Subject: Status of side-effecting functions in python References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> Message-ID: <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> Roy Smith wrote: >> Yes and no. If something goes wrong in a .write() method, >> is not Python supposed to raise an error? (!) > > Define "wrong". It is not an error for a write() call to consume fewer > bytes than were requested. It's not? I'm asking a genuine question here, not a rhetorical one. I would expect that if I ask to write 2 bytes, and only 1 byte is written, that absolutely is an error. Under what circumstances is it okay for write() to throw data away? > How would you expect this to be handled in Python? Raise > DataPartiallyWrittenError? I would expect it to raise an IOError, most likely with one of the following error codes: * errno.EIO (physical input/output error) * errno.EFBIG (file is too large) * errno.ENOSPC (no space left on device, disk is full) -- Steven From rosuav at gmail.com Mon Oct 27 07:44:12 2014 From: rosuav at gmail.com (Chris Angelico) Date: Mon, 27 Oct 2014 22:44:12 +1100 Subject: Status of side-effecting functions in python In-Reply-To: <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Mon, Oct 27, 2014 at 10:30 PM, Steven D'Aprano wrote: > Roy Smith wrote: > >>> Yes and no. If something goes wrong in a .write() method, >>> is not Python supposed to raise an error? (!) >> >> Define "wrong". It is not an error for a write() call to consume fewer >> bytes than were requested. > > It's not? I'm asking a genuine question here, not a rhetorical one. I would > expect that if I ask to write 2 bytes, and only 1 byte is written, that > absolutely is an error. Under what circumstances is it okay for write() to > throw data away? > >> How would you expect this to be handled in Python? Raise >> DataPartiallyWrittenError? > > I would expect it to raise an IOError, most likely with one of the following > error codes: > > * errno.EIO (physical input/output error) > > * errno.EFBIG (file is too large) > > * errno.ENOSPC (no space left on device, disk is full) You're assuming the condition, whatever it is, is permanent. The most common reason for write() to be temporarily unable to write everything is a non-blocking socket, pipe, or somesuch. It writes as much as it can, tells you how much that is, and lets you buffer the rest or deal with it in whatever other way you choose. If it is permanent, though, then yes, it should tell you. But what if you ask it to write a megabyte, it writes half of it, and then finds that there's no space on the disk? Should it: 1) Back out the write and raise an exception? 2) Write part of the data and raise an exception? 3) Write part of the data and NOT raise an exception? All three make sense. The third one is an option only if it's documented as being able to tell you about partial writes. The second has a problem in that you can't necessarily communicate "this is how much I wrote" properly while also signalling the exception (imagine if one function calls write() more than once, and it doesn't catch any exceptions, just lets them bubble up). And backing out a write isn't always possible. So what's to do? ChrisA From roy at panix.com Mon Oct 27 09:17:34 2014 From: roy at panix.com (Roy Smith) Date: Mon, 27 Oct 2014 09:17:34 -0400 Subject: id == vs is References: <544D94B5.80502@mrabarnett.plus.com> Message-ID: In article , Cameron Simpson wrote: > The "is" test is more direct and less subject to iffiness because the longer > expression using id() leaves more scope/time for things to change, and of > course "id" itself can be rebound to something weird. Not to mention that Python is case-sensitive and in the code as presented by the OP: >>>>Id(x) == id(y) those are two different functions :-) From roy at panix.com Mon Oct 27 09:28:37 2014 From: roy at panix.com (Roy Smith) Date: Mon, 27 Oct 2014 09:28:37 -0400 Subject: Status of side-effecting functions in python References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <544e2cf2$0$13009$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > Roy Smith wrote: > > >> Yes and no. If something goes wrong in a .write() method, > >> is not Python supposed to raise an error? (!) > > > > Define "wrong". It is not an error for a write() call to consume fewer > > bytes than were requested. > > It's not? I'm asking a genuine question here, not a rhetorical one. I would > expect that if I ask to write 2 bytes, and only 1 byte is written, that > absolutely is an error. Under what circumstances is it okay for write() to > throw data away? It's not throwing away data. The write() call returns a count of how many bytes is consumed, so you can present the rest of them again in a later write() call (assuming that makes sense to do for your application). In some cases, the underlying hardware (or network protocol) may be unable to handle the number of bytes you requested, or may fail in mid-transmission. Imagine a serial link. You tell it to write 100 bytes. It starts sending them down the line and after 20 bytes, the connection fails. What should write() do in that case? It hasn't written all the data, so it needs to let you know that. It also has written *some* of the data, so it needs to let you know that too. What you do with that information is up to you, but it clearly needs to return a richer status indication than just success/failure. From Seymore4Head at Hotmail.invalid Mon Oct 27 09:34:48 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Mon, 27 Oct 2014 09:34:48 -0400 Subject: Classes and the command line References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> Message-ID: <7fis4a5v735gnnmlqeqqo8roit0f236n2h@4ax.com> On Sun, 26 Oct 2014 23:32:08 -0400, Seymore4Head wrote: >On Mon, 27 Oct 2014 14:06:11 +1100, Ben Finney > wrote: > >>Seymore4Head writes: >> >>> I am trying to learn classes. >>> I am currently using Python 2.7 at the command line. >> >>(I think you mean ?the interactive Python interpreter?, or just ?the >>Python shell?.) >> >>Since you are learning Python, I will strongly recommend you ignore >>Python 2 unless it becomes unavoidable. >> >At the moment, it is unavoidable. The instructors are teaching Python >2 so I have to learn Python 2, for now. > >>Instead, learn Python 3 primarily; it is much better because it omits a >>bunch of legacy behaviour you don't need. >> >>> If you try to type commands at the [interactive shell] and make the >>> slightest mistake you have to start over. >> >>Right. There is line-by-line history, and editing enabled with the >>?readline? plug-in. (This is an advantage of using a programmer-friendly >>operating system, which MS Windows sadly is not.) >> >>> I was trying to copy and paste these instructions into the >>> [interactive Python shell]. >>> >>> http://en.wikibooks.org/wiki/Python_Programming/Classes >>> >>> class Foo: >>> ... def setx(self, x): >>> ... self.x = x >>> ... def bar(self): >>> ... print self.x >>> >>> There is really no way to do that without pasting line by line is >>> there and adding deleting spaces? And if you use spaces and tabs, >>> they are not the same. >> >>Right on all counts. >> >>The interactive Python shell is good for very quickly experimenting and >>demonstrating how Python actually behaves, statement by statement. But >>as you point out, it is not a good choice for anything more complex. It >>is a good learning and debugging tool. >> >>When you start to write larger units of code, like a class or a >>function, you can trade immediacy for flexibility: write your code into >>a text editor, save it to a file ?foo.py?, then run that code at a >>separate OS command prompt by invoking ?python foo.py? in the terminal. >> >>That way, you can continue to adjust and tweak the code as you learn how >>your changes affect the code. You do need to keep invoking the actions >>separately ? edit the file, save the file, run the file with Python ? >>but this is what's needed when you want to run a program more than once >>anyway, so it's a good step to take. >> >>Find a good, *general-purpose* programmer's editor. Preferably licensed >>under free software terms, with a strong community supporting it, and >>available on all major platforms for when you switch to a decent >>programmer-friendly operating system. > >I am actually using Notepad some too. > >Thanks I meant Notepad ++ From invalid at invalid.invalid Mon Oct 27 10:22:38 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 27 Oct 2014 14:22:38 +0000 (UTC) Subject: Status of side-effecting functions in python References: Message-ID: On 2014-10-25, Wolfgang Maier wrote: > It may be rare to use an expression both for its side-effects and its > return value, It's actually quite common. For example: f = open("filename") d = f.readline() In both of those lines, the side effects and return values are equally vital. The same applies to reading from a queue, popping from a stack, etc. -- Grant Edwards grant.b.edwards Yow! This PORCUPINE knows at his ZIPCODE ... And he has gmail.com "VISA"!! From invalid at invalid.invalid Mon Oct 27 10:45:39 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Mon, 27 Oct 2014 14:45:39 +0000 (UTC) Subject: Status of side-effecting functions in python References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> Message-ID: On 2014-10-27, Steven D'Aprano wrote: > Roy Smith wrote: > >>> Yes and no. If something goes wrong in a .write() method, >>> is not Python supposed to raise an error? (!) >> >> Define "wrong". It is not an error for a write() call to consume fewer >> bytes than were requested. > > It's not? I'm asking a genuine question here, not a rhetorical one. No. Under Unix/Posix a write() call may _always_ write fewer bytes than requested. It may be that the device/pipe/file whatever has filled and blocking is disabled. It may be that the device has decided that, at the moment, it can only handle a certain amount of data for some other reason. For example: Let's say you're writing to a network connection that must segment data, and you try to write more than will fit in the current segment. The write() call may fill the segment, send the segment, and "refuse" the rest of the data -- requiring that you make a subsequent write() with the remaining data (at which point it will start a new segment). Or, it may be because the system call was interrupted by something completely unrelated to your program, the write() call, or the "thing" to which you're writing [and it was more convenient for whoever wrote the OS to do a partial write than it was to try to resume the write]. If you really want to make sure that all bytes get written, you _must_ put all write() calls in a loop that checks the return value and keeps re-writing any unwritten data. And to answer your next question: yes, Unix application programmers have been complaining about that (perhaps justifiably) since 1970. -- Grant Edwards grant.b.edwards Yow! I have a TINY BOWL in at my HEAD gmail.com From jldunn2000 at gmail.com Mon Oct 27 10:49:14 2014 From: jldunn2000 at gmail.com (loial) Date: Mon, 27 Oct 2014 07:49:14 -0700 (PDT) Subject: Web services from python Message-ID: <9e861944-85b7-4cd2-8472-e9867dd5cfc0@googlegroups.com> What is the best package to use with python 2.6 to access Web services. Is it ZSI? Can anyone recommend a good tutorial, preferably with a sandbox web service? From jon+usenet at unequivocal.co.uk Mon Oct 27 11:03:49 2014 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Mon, 27 Oct 2014 15:03:49 +0000 (UTC) Subject: Lazy-evaluation lists/dictionaries References: Message-ID: On 2014-10-26, Terry Reedy wrote: > On 10/26/2014 10:14 AM, Jon Ribbens wrote: >> Is there any better way to do this other than simply re-implementing >> these types from scratch, emulating all their methods and operations? >> (i.e. using UserList/UserDict). I was under the impression that that >> sort of thing was supposed to have gone since Python 2.2 or so. > > We considered dropping UserDict and UserList for 3.0 but kept them in > collections for cases in which subclassing does not work. It seems on further investigation to be hard/impossible to subclass Python classes from C extensions. I've gone with subclassing dict, and reimplementing most of its methods. It helps that I only need it to be read-only. It's a pity there's no protocol for 'dynamic' lists/dicts though. From emmanueloje at gmail.com Mon Oct 27 11:10:04 2014 From: emmanueloje at gmail.com (emmanueloje at gmail.com) Date: Mon, 27 Oct 2014 08:10:04 -0700 (PDT) Subject: Anyone know the solution Message-ID: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> Write a program that reads the contents of the two files into two separate lists. The user should be able to enter a boy's name, a girl's name or both, and the application will display messages indicating whether the names were among the most popular. THIS IS THE LIST OF BOY NAMES Jacob Michael Joshua Matthew Daniel Christopher Andrew Ethan Joseph William Anthony David Alexander Nicholas Ryan Tyler James John Jonathan Noah Brandon Christian Dylan Samuel Benjamin Zachary Nathan Logan Justin Gabriel Jose Austin Kevin Elijah Caleb Robert Thomas Jordan Cameron Jack Hunter Jackson Angel Isaiah Evan Isaac Mason Luke Jason Gavin Jayden Aaron Connor Aiden Aidan Kyle Juan Charles Luis Adam Lucas Brian Eric Adrian Nathaniel Sean Alex Carlos Bryan Ian Owen Jesus Landon Julian Chase Cole Diego Jeremiah Steven Sebastian Xavier Timothy Carter Wyatt Brayden Blake Hayden Devin Cody Richard Seth Dominic Jaden Antonio Miguel Liam Patrick Carson Jesse Tristan Alejandro Henry Victor Trevor Bryce Jake Riley Colin Jared Jeremy Mark Caden Garrett Parker Marcus Vincent Kaleb Kaden Brady Colton Kenneth Joel Oscar Josiah Jorge Cooper Ashton Tanner Eduardo Paul Edward Ivan Preston Maxwell Alan Levi Stephen Grant Nicolas Omar Dakota Alexis George Collin Eli Spencer Gage Max Cristian Ricardo Derek Micah Brody Francisco Nolan Ayden Dalton Shane Peter Damian Jeffrey Brendan Travis Fernando Peyton Conner Andres Javier Giovanni Shawn Braden Jonah Cesar Bradley Emmanuel Manuel Edgar Erik Mario Edwin Johnathan Devon Erick Wesley Oliver Trenton Hector Malachi Jalen Raymond Gregory Abraham Elias Leonardo Sergio Donovan Colby Marco Bryson Martin THIS IS THE LIST OF GIRLS NAME Emily Madison Emma Olivia Hannah Abigail Isabella Samantha Elizabeth Ashley Alexis Sarah Sophia Alyssa Grace Ava Taylor Brianna Lauren Chloe Natalie Kayla Jessica Anna Victoria Mia Hailey Sydney Jasmine Julia Morgan Destiny Rachel Ella Kaitlyn Megan Katherine Savannah Jennifer Alexandra Allison Haley Maria Kaylee Lily Makayla Brooke Mackenzie Nicole Addison Stephanie Lillian Andrea Zoe Faith Kimberly Madeline Alexa Katelyn Gabriella Gabrielle Trinity Amanda Kylie Mary Paige Riley Jenna Leah Sara Rebecca Michelle Sofia Vanessa Jordan Angelina Caroline Avery Audrey Evelyn Maya Claire Autumn Jocelyn Ariana Nevaeh Arianna Jada Bailey Brooklyn Aaliyah Amber Isabel Danielle Mariah Melanie Sierra Erin Molly Amelia Isabelle Madelyn Melissa Jacqueline Marissa Shelby Angela Leslie Katie Jade Catherine Diana Aubrey Mya Amy Briana Sophie Gabriela Breanna Gianna Kennedy Gracie Peyton Adriana Christina Courtney Daniela Kathryn Lydia Valeria Layla Alexandria Natalia Angel Laura Charlotte Margaret Cheyenne Mikayla Miranda Naomi Kelsey Payton Ana Alicia Jillian Daisy Mckenzie Ashlyn Caitlin Sabrina Summer Ruby Rylee Valerie Skylar Lindsey Kelly Genesis Zoey Eva Sadie Alexia Cassidy Kylee Kendall Jordyn Kate Jayla Karen Tiffany Cassandra Juliana Reagan Caitlyn Giselle Serenity Alondra Lucy Kiara Bianca Crystal Erica Angelica Hope Chelsea Alana Liliana Brittany Camila Makenzie Veronica Lilly Abby Jazmin Adrianna Karina Delaney Ellie Jasmin From jon+usenet at unequivocal.co.uk Mon Oct 27 11:11:48 2014 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Mon, 27 Oct 2014 15:11:48 +0000 (UTC) Subject: Lazy-evaluation lists/dictionaries References: Message-ID: On 2014-10-26, Tim Delaney wrote: > On 27 October 2014 01:14, Jon Ribbens wrote: >> I have a need, in a Python C extension I am writing, for lists and >> dictionaries with "lazy evaluation" - by which I mean that at least >> some of the values in the lists/dictionaries are "proxy objects" >> which, rather than returning as themselves, should return the thing >> they are a proxy for when retrieved. This is because retrieving >> the proxied objects is expensive and only a small minority of them >> will actually be accessed, so retrieving them all before they are >> actually accessed is massively inefficient. > > Why not put proxy objects into the list/dict? That's precisely what I am doing. The point is that when they are retrieved they need to be resolved into the genuine objects. > Have a look at the weakref module for an API that may be suitable > for such proxy objects (if you used the same API, that would also > allow you to transparently use weakrefs in your lists/dicts). Hmm, the idea behind that appears to be to create a proxy that emulates every possible method of every conceivable type. My method of only emulating the list and dict methods seems to be somewhat simpler for my purpose ;-) From marko at pacujo.net Mon Oct 27 11:14:58 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Mon, 27 Oct 2014 17:14:58 +0200 Subject: Status of side-effecting functions in python References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> Message-ID: <87bnoxv91p.fsf@elektro.pacujo.net> Grant Edwards : > If you really want to make sure that all bytes get written, you _must_ > put all write() calls in a loop that checks the return value and keeps > re-writing any unwritten data. > > And to answer your next question: yes, Unix application programmers > have been complaining about that (perhaps justifiably) since 1970. I wouldn't have it any other way. Now, I have confused the discussion with some misinformation myself. Python2's file.write() doesn't return a value but pushes the whole string out. Python3's file.write() returns the number of *characters* written. I don't know if the number can ever be different from the total number of characters in the string. In POSIX, a write(2) system call on file blocks until all bytes have been passed on to the file system. The only exception (no pun intended) I know is the reception of a signal. Even then, I'm not sure Linux file systems ever cut writes short because of signals. I think the lack of nonblocking file access in Linux is one of the OS's main shortcomings. Python's sockets and pipes don't have write methods. Marko From alister.nospam.ware at ntlworld.com Mon Oct 27 11:21:59 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Mon, 27 Oct 2014 15:21:59 GMT Subject: Anyone know the solution References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> Message-ID: On Mon, 27 Oct 2014 08:10:04 -0700, emmanueloje wrote: > Write a program that reads the contents of the two files into two > separate lists. The user should be able to enter a boy's name, a girl's > name or both, and the application will display messages indicating > whether the names were among the most popular. > Your tutor for a start & I think I could probably get one working in an hour or so without too much difficulty. What do you have? we do not do homework for you here. if you have some code that doesn't work as expected we may assist -- semper en excretus From joel.goldstick at gmail.com Mon Oct 27 11:20:29 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Mon, 27 Oct 2014 11:20:29 -0400 Subject: Anyone know the solution In-Reply-To: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> Message-ID: 2014-10-27 11:10 GMT-04:00 : > Write a program that reads the contents of the two files into two separate lists. The user should be able to enter a boy's name, a girl's name or both, and the application will display messages indicating whether the names were among the most popular. > > THIS IS THE LIST OF BOY NAMES > Jacob > Michael > Joshua > Matthew > Daniel > Christopher > Andrew > Ethan > Joseph > William > Anthony > David > Alexander > Nicholas > Ryan > Tyler > James > John > Jonathan > Noah > Brandon > Christian > Dylan > Samuel > Benjamin > Zachary > Nathan > Logan > Justin > Gabriel > Jose > Austin > Kevin > Elijah > Caleb > Robert > Thomas > Jordan > Cameron > Jack > Hunter > Jackson > Angel > Isaiah > Evan > Isaac > Mason > Luke > Jason > Gavin > Jayden > Aaron > Connor > Aiden > Aidan > Kyle > Juan > Charles > Luis > Adam > Lucas > Brian > Eric > Adrian > Nathaniel > Sean > Alex > Carlos > Bryan > Ian > Owen > Jesus > Landon > Julian > Chase > Cole > Diego > Jeremiah > Steven > Sebastian > Xavier > Timothy > Carter > Wyatt > Brayden > Blake > Hayden > Devin > Cody > Richard > Seth > Dominic > Jaden > Antonio > Miguel > Liam > Patrick > Carson > Jesse > Tristan > Alejandro > Henry > Victor > Trevor > Bryce > Jake > Riley > Colin > Jared > Jeremy > Mark > Caden > Garrett > Parker > Marcus > Vincent > Kaleb > Kaden > Brady > Colton > Kenneth > Joel > Oscar > Josiah > Jorge > Cooper > Ashton > Tanner > Eduardo > Paul > Edward > Ivan > Preston > Maxwell > Alan > Levi > Stephen > Grant > Nicolas > Omar > Dakota > Alexis > George > Collin > Eli > Spencer > Gage > Max > Cristian > Ricardo > Derek > Micah > Brody > Francisco > Nolan > Ayden > Dalton > Shane > Peter > Damian > Jeffrey > Brendan > Travis > Fernando > Peyton > Conner > Andres > Javier > Giovanni > Shawn > Braden > Jonah > Cesar > Bradley > Emmanuel > Manuel > Edgar > Erik > Mario > Edwin > Johnathan > Devon > Erick > Wesley > Oliver > Trenton > Hector > Malachi > Jalen > Raymond > Gregory > Abraham > Elias > Leonardo > Sergio > Donovan > Colby > Marco > Bryson > Martin > > THIS IS THE LIST OF GIRLS NAME > Emily > Madison > Emma > Olivia > Hannah > Abigail > Isabella > Samantha > Elizabeth > Ashley > Alexis > Sarah > Sophia > Alyssa > Grace > Ava > Taylor > Brianna > Lauren > Chloe > Natalie > Kayla > Jessica > Anna > Victoria > Mia > Hailey > Sydney > Jasmine > Julia > Morgan > Destiny > Rachel > Ella > Kaitlyn > Megan > Katherine > Savannah > Jennifer > Alexandra > Allison > Haley > Maria > Kaylee > Lily > Makayla > Brooke > Mackenzie > Nicole > Addison > Stephanie > Lillian > Andrea > Zoe > Faith > Kimberly > Madeline > Alexa > Katelyn > Gabriella > Gabrielle > Trinity > Amanda > Kylie > Mary > Paige > Riley > Jenna > Leah > Sara > Rebecca > Michelle > Sofia > Vanessa > Jordan > Angelina > Caroline > Avery > Audrey > Evelyn > Maya > Claire > Autumn > Jocelyn > Ariana > Nevaeh > Arianna > Jada > Bailey > Brooklyn > Aaliyah > Amber > Isabel > Danielle > Mariah > Melanie > Sierra > Erin > Molly > Amelia > Isabelle > Madelyn > Melissa > Jacqueline > Marissa > Shelby > Angela > Leslie > Katie > Jade > Catherine > Diana > Aubrey > Mya > Amy > Briana > Sophie > Gabriela > Breanna > Gianna > Kennedy > Gracie > Peyton > Adriana > Christina > Courtney > Daniela > Kathryn > Lydia > Valeria > Layla > Alexandria > Natalia > Angel > Laura > Charlotte > Margaret > Cheyenne > Mikayla > Miranda > Naomi > Kelsey > Payton > Ana > Alicia > Jillian > Daisy > Mckenzie > Ashlyn > Caitlin > Sabrina > Summer > Ruby > Rylee > Valerie > Skylar > Lindsey > Kelly > Genesis > Zoey > Eva > Sadie > Alexia > Cassidy > Kylee > Kendall > Jordyn > Kate > Jayla > Karen > Tiffany > Cassandra > Juliana > Reagan > Caitlyn > Giselle > Serenity > Alondra > Lucy > Kiara > Bianca > Crystal > Erica > Angelica > Hope > Chelsea > Alana > Liliana > Brittany > Camila > Makenzie > Veronica > Lilly > Abby > Jazmin > Adrianna > Karina > Delaney > Ellie > Jasmin > -- > https://mail.python.org/mailman/listinfo/python-list The answer to you question is Yes. -- Joel Goldstick http://joelgoldstick.com From chaselton at gmail.com Mon Oct 27 11:54:46 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Mon, 27 Oct 2014 10:54:46 -0500 Subject: Build Question: How to Add -Wl,--option Before Objects In Setup.py? Message-ID: I need to add a linker option to the command(s) run by setup.py when building various objects. I'm not familiar with Python at all, so I basically copied and modified a line from one area of the script to another ext_modules=[Extension('_struct', ['_struct.c'], extra_link_args = ['Wl,--allow-shlib-undefined'])], *snip* Unfortunately this seems to append the option to the end of the command line. What's the best (fastest) way to add it before the object being built (objectname.o)? From trsexgl at gmail.com Mon Oct 27 12:01:57 2014 From: trsexgl at gmail.com (umatrp@gmail.com) Date: Mon, 27 Oct 2014 09:01:57 -0700 (PDT) Subject: A bug? Message-ID: I use python 3.4.0 version. In the course of developing / running a python program, I have encountered a problem. I have reproduced below a simple program to bring it out. >>> d = [[0]*3]*4 >>> dd = [1,2,3,4,5,6,7,8,9,10,11,12] >>> for i in range(4): ... for j in range(3): d[i][j] = dd[i*3+j] ... >>> d [[10, 11, 12], [10, 11, 12], [10, 11, 12], [10, 11, 12]] >>> d is not transferred to dd as expected? Of course I can use 'append' & do my job (less elegantly though). From wolfgang.maier at biologie.uni-freiburg.de Mon Oct 27 12:17:57 2014 From: wolfgang.maier at biologie.uni-freiburg.de (Wolfgang Maier) Date: Mon, 27 Oct 2014 17:17:57 +0100 Subject: A bug? In-Reply-To: References: Message-ID: On 10/27/2014 05:01 PM, umatrp at gmail.com wrote: > I use python 3.4.0 version. In the course of developing / running a python program, I have encountered a problem. I have reproduced below a simple program to bring it out. > > >>>> d = [[0]*3]*4 >>>> dd = [1,2,3,4,5,6,7,8,9,10,11,12] >>>> for i in range(4): > ... for j in range(3): d[i][j] = dd[i*3+j] > ... >>>> d > [[10, 11, 12], [10, 11, 12], [10, 11, 12], [10, 11, 12]] >>>> > d is not transferred to dd as expected? > Of course I can use 'append' & do my job (less elegantly though). > See https://docs.python.org/3/library/stdtypes.html?highlight=list#common-sequence-operations under Note 2 . Also asked and answered multiple times at stackoverflow, e.g., http://stackoverflow.com/questions/6688223/ From ian.g.kelly at gmail.com Mon Oct 27 12:26:01 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Mon, 27 Oct 2014 10:26:01 -0600 Subject: A bug? In-Reply-To: References: Message-ID: On Mon, Oct 27, 2014 at 10:17 AM, Wolfgang Maier wrote: > See > https://docs.python.org/3/library/stdtypes.html?highlight=list#common-sequence-operations > under Note 2 . > > Also asked and answered multiple times at stackoverflow, e.g., > http://stackoverflow.com/questions/6688223/ Also see https://docs.python.org/3/faq/programming.html#how-do-i-create-a-multidimensional-list (probably a better resource than that footnote). From kiuhnm03 at yahoo.it Mon Oct 27 13:16:43 2014 From: kiuhnm03 at yahoo.it (kiuhnm03 at yahoo.it) Date: Mon, 27 Oct 2014 10:16:43 -0700 (PDT) Subject: memory, PE files, etc... Message-ID: <49c92881-e8bf-4e80-9e4d-8b88c0d12133@googlegroups.com> Hi! I'd like to write one or more scripts that analyze processes in memory on Windows 7. I used to do these things in C++ by using native Win32 API calls. How should I proceed in python? Any pointers? From mail at timgolden.me.uk Mon Oct 27 13:23:17 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 27 Oct 2014 17:23:17 +0000 Subject: memory, PE files, etc... In-Reply-To: <49c92881-e8bf-4e80-9e4d-8b88c0d12133@googlegroups.com> References: <49c92881-e8bf-4e80-9e4d-8b88c0d12133@googlegroups.com> Message-ID: <544E7F85.3030707@timgolden.me.uk> On 27/10/2014 17:16, kiuhnm03 at yahoo.it wrote: > Hi! I'd like to write one or more scripts that analyze processes in > memory on Windows 7. I used to do these things in C++ by using native > Win32 API calls. How should I proceed in python? Any pointers? > psutil is definitely your friend: https://github.com/giampaolo/psutil Although WMI can be quite handy too, depending on what you're trying to do: http://timgolden.me.uk/python/wmi/ TJG From hjgreenberg at gmail.com Mon Oct 27 14:23:16 2014 From: hjgreenberg at gmail.com (Harvey Greenberg) Date: Mon, 27 Oct 2014 11:23:16 -0700 (PDT) Subject: variable attribute name Message-ID: <6fc1feb3-651e-49e9-8a5d-66dc0599a754@googlegroups.com> I want to let the name of an attribute be the string value of a variable. Here is some code: class Object(object): pass A = Object() s = 'attr' A. = 1 The last line denotes the variable value by (not a python form). What I want is to have A.attr = 1, but 'attr' determined by the value of s. Please advise. From larry.martell at gmail.com Mon Oct 27 14:32:37 2014 From: larry.martell at gmail.com (Larry Martell) Date: Mon, 27 Oct 2014 14:32:37 -0400 Subject: variable attribute name In-Reply-To: <6fc1feb3-651e-49e9-8a5d-66dc0599a754@googlegroups.com> References: <6fc1feb3-651e-49e9-8a5d-66dc0599a754@googlegroups.com> Message-ID: On Mon, Oct 27, 2014 at 2:23 PM, Harvey Greenberg wrote: > I want to let the name of an attribute be the string value of a variable. Here is some code: > > class Object(object): pass > A = Object() > s = 'attr' > A. = 1 > > The last line denotes the variable value by (not a python form). What I want is to have A.attr = 1, but 'attr' determined by the value of s. Please advise. setattr(A, s, 1) From kiuhnm03 at yahoo.it Mon Oct 27 15:11:18 2014 From: kiuhnm03 at yahoo.it (kiuhnm03 at yahoo.it) Date: Mon, 27 Oct 2014 12:11:18 -0700 (PDT) Subject: memory, PE files, etc... In-Reply-To: References: <49c92881-e8bf-4e80-9e4d-8b88c0d12133@googlegroups.com> Message-ID: On Monday, October 27, 2014 6:24:19 PM UTC+1, Tim Golden wrote: > psutil is definitely your friend: > > https://github.com/giampaolo/psutil > > Although WMI can be quite handy too, depending on what you're trying to do: > > http://timgolden.me.uk/python/wmi/ > > TJG Thanks for answering. I don't know if psutil is what I'm looking for. What I need to do is more related to debugging than to administration. Let's say I want to search for a sequence of bytes in the .text section of a given module. Can I do that with psutil? Maybe I should buy this book: http://www.amazon.com/Gray-Hat-Python-Programming-Engineers/dp/1593271921 From ned at nedbatchelder.com Mon Oct 27 15:48:31 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Mon, 27 Oct 2014 15:48:31 -0400 Subject: variable attribute name In-Reply-To: References: <6fc1feb3-651e-49e9-8a5d-66dc0599a754@googlegroups.com> Message-ID: On 10/27/14 2:32 PM, Larry Martell wrote: > On Mon, Oct 27, 2014 at 2:23 PM, Harvey Greenberg wrote: >> I want to let the name of an attribute be the string value of a variable. Here is some code: >> >> class Object(object): pass >> A = Object() >> s = 'attr' >> A. = 1 >> >> The last line denotes the variable value by (not a python form). What I want is to have A.attr = 1, but 'attr' determined by the value of s. Please advise. > > setattr(A, s, 1) > Larry's code will work for you. If you are making many attributes like this, you might be better off just using a dictionary in the first place: a = {} a[s] = 1 -- Ned Batchelder, http://nedbatchelder.com From nad at acm.org Mon Oct 27 16:39:32 2014 From: nad at acm.org (Ned Deily) Date: Mon, 27 Oct 2014 13:39:32 -0700 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? References: Message-ID: In article , Cyd Haselton wrote: > I need to add a linker option to the command(s) run by setup.py when > building various objects. I'm not familiar with Python at all, so I > basically copied and modified a line from one area of the script to > another > > > ext_modules=[Extension('_struct', ['_struct.c'], extra_link_args = > ['Wl,--allow-shlib-undefined'])], > *snip* > > Unfortunately this seems to append the option to the end of the > command line. What's the best (fastest) way to add it before the > object being built (objectname.o)? It depends on what system and build tools that you are using and that the Python you are using was built with but, in general on most POSIX-like systems, one way to do it should be to supply it via an LDFLAGS environment variable. The safest approach would be to get the default value of LDFLAGS for this Python instance, append your additional values to it, and pass it back into the setup.py build. You can do that all in one line: LDFLAGS="$(python -c 'import sysconfig;print(sysconfig.get_config_var("LDFLAGS"))') -Wl,--allow-shlib-undefined" python setup.py build -- Ned Deily, nad at acm.org From pecore at pascolo.net Mon Oct 27 17:26:21 2014 From: pecore at pascolo.net (giacomo boffi) Date: Mon, 27 Oct 2014 22:26:21 +0100 Subject: I am out of trial and error again Lists References: <185ea3d5-71d3-4009-8afe-4f0c2b6bbf30@googlegroups.com> Message-ID: <877fzl432a.fsf@pascolo.net> Rustom Mody writes: > What would you say to a person who > - Buys a Lambhorgini I'd say: "Don't buy a Lambhorgini from that nice guy you met at a party, but buy a Lamborghini by an authorized dealer" ;-) -- I was a kid when Lamborghini launched the Miura! From kiuhnm03 at yahoo.it Mon Oct 27 18:38:15 2014 From: kiuhnm03 at yahoo.it (kiuhnm03 at yahoo.it) Date: Mon, 27 Oct 2014 15:38:15 -0700 (PDT) Subject: different behavior from idle/pycharm and shell Message-ID: <4417873a-f05f-43b9-9803-1226b1b4ddda@googlegroups.com> Consider this code: --- from ctypes import * user32 = windll.user32 user32.MessageBoxA(0, 'ok', 'ok', 0) --- If I run it in idle or from pycharm, the messagebox shows 'o' instead of 'ok', but if I run it from shell, it shows 'ok' like it should. The same happens with msvcrt.printf(). Why? From sohcahtoa82 at gmail.com Mon Oct 27 18:49:59 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Mon, 27 Oct 2014 15:49:59 -0700 (PDT) Subject: different behavior from idle/pycharm and shell In-Reply-To: <4417873a-f05f-43b9-9803-1226b1b4ddda@googlegroups.com> References: <4417873a-f05f-43b9-9803-1226b1b4ddda@googlegroups.com> Message-ID: On Monday, October 27, 2014 3:38:31 PM UTC-7, kiuh... at yahoo.it wrote: > Consider this code: > > --- > from ctypes import * > > user32 = windll.user32 > user32.MessageBoxA(0, 'ok', 'ok', 0) > --- > > If I run it in idle or from pycharm, the messagebox shows 'o' instead of 'ok', but if I run it from shell, it shows 'ok' like it should. > The same happens with msvcrt.printf(). > Why? If I had to take a guess, in the shell, it is encoding the string characters as single bytes as expected, but in Idle or PyCharm, it is encoding them as WCHARs, which are two-bytes wide. Two things to try: 1. Change the call to MessageBoxW and see if it works in Idle/PyCharm. Note that this will probably break the call from the shell. 2. Try a string longer than two characters and see what you get. From python at mrabarnett.plus.com Mon Oct 27 18:55:21 2014 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 27 Oct 2014 22:55:21 +0000 Subject: different behavior from idle/pycharm and shell In-Reply-To: <4417873a-f05f-43b9-9803-1226b1b4ddda@googlegroups.com> References: <4417873a-f05f-43b9-9803-1226b1b4ddda@googlegroups.com> Message-ID: <544ECD59.9090501@mrabarnett.plus.com> On 2014-10-27 22:38, kiuhnm03 at yahoo.it wrote: > Consider this code: > > --- > from ctypes import * > > user32 = windll.user32 > user32.MessageBoxA(0, 'ok', 'ok', 0) > --- > > If I run it in idle or from pycharm, the messagebox shows 'o' instead of 'ok', but if I run it from shell, it shows 'ok' like it should. > The same happens with msvcrt.printf(). > Why? > You didn't say whether you're using Python 2 or Python 3, but it looks like you're using Python 3. There are 2 forms of the MessageBox function, one with the suffix 'A', which uses bytestrings, and one with the suffix 'W', which uses Unicode strings. In Python 3, the str class is a Unicode string, so you'll want the MessageBoxW function: from ctypes import * user32 = windll.user32 user32.MessageBoxW(0, 'ok', 'ok', 0) Also, the msvcrt.printf function expects a bytestring. From kiuhnm03 at yahoo.it Mon Oct 27 19:14:25 2014 From: kiuhnm03 at yahoo.it (kiuhnm03 at yahoo.it) Date: Mon, 27 Oct 2014 16:14:25 -0700 (PDT) Subject: different behavior from idle/pycharm and shell In-Reply-To: References: <4417873a-f05f-43b9-9803-1226b1b4ddda@googlegroups.com> Message-ID: <0ef8347f-6c83-4d1e-95d4-69e308adefdf@googlegroups.com> On Monday, October 27, 2014 11:55:44 PM UTC+1, MRAB wrote: > On 2014-10-27 22:38, kiuhnm wrote: > > Consider this code: > > > > --- > > from ctypes import * > > > > user32 = windll.user32 > > user32.MessageBoxA(0, 'ok', 'ok', 0) > > --- > > > > If I run it in idle or from pycharm, the messagebox shows 'o' instead of 'ok', but if I run it from shell, it shows 'ok' like it should. > > The same happens with msvcrt.printf(). > > Why? > > > You didn't say whether you're using Python 2 or Python 3, but it looks > like you're using Python 3. > > There are 2 forms of the MessageBox function, one with the suffix 'A', > which uses bytestrings, and one with the suffix 'W', which uses Unicode > strings. > > In Python 3, the str class is a Unicode string, so you'll want the > MessageBoxW function: > > from ctypes import * > > user32 = windll.user32 > user32.MessageBoxW(0, 'ok', 'ok', 0) > > Also, the msvcrt.printf function expects a bytestring. Yes, you're right. Thank you both. From chaselton at gmail.com Mon Oct 27 19:20:36 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Mon, 27 Oct 2014 18:20:36 -0500 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? In-Reply-To: References: Message-ID: On Mon, Oct 27, 2014 at 3:39 PM, Ned Deily wrote: > In article > , > Cyd Haselton wrote: >> I need to add a linker option to the command(s) run by setup.py when >> building various objects. I'm not familiar with Python at all, so I >> basically copied and modified a line from one area of the script to >> another >> >> >> ext_modules=[Extension('_struct', ['_struct.c'], extra_link_args = >> ['Wl,--allow-shlib-undefined'])], >> *snip* >> >> Unfortunately this seems to append the option to the end of the >> command line. What's the best (fastest) way to add it before the >> object being built (objectname.o)? > > It depends on what system and build tools that you are using and that > the Python you are using was built with but, in general on most > POSIX-like systems, one way to do it should be to supply it via an > LDFLAGS environment variable. The safest approach would be to get the > default value of LDFLAGS for this Python instance, append your > additional values to it, and pass it back into the setup.py build. You > can do that all in one line: > > LDFLAGS="$(python -c 'import > sysconfig;print(sysconfig.get_config_var("LDFLAGS"))') > -Wl,--allow-shlib-undefined" python setup.py build > > -- > Ned Deily, > nad at acm.org > I'm building python on an Android device in the KBOX environment...which simulates a Unix type filesystem. Python isn't installed; I'm building from sources (2.7.8) with GCC 4.8.0 and make. The problem with the LDFLAGS approach is that some of the libraries that must be linked (-lc -ldl) do not need the --allow-shlib-undefined option...it's only the lpython2.7 that does. Any way to do this? Cyd Haselton From denismfmcmahon at gmail.com Mon Oct 27 20:20:06 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 28 Oct 2014 00:20:06 +0000 (UTC) Subject: Anyone know the solution References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> Message-ID: On Mon, 27 Oct 2014 08:10:04 -0700, emmanueloje wrote: > Write a program that reads the contents of the two files into two > separate lists. Yep, know how to do that > The user should be able to enter a boy's name, a girl's > name or both Yep, know how to do that > and the application will display messages > indicating whether the names were among the most popular. Nope, not sure how to do that, please define the algorithm for determining a "most popular name" Determining if the name is in either of the lists is easy, know how to do that, but I'm not sure from your problem description if that's your definition of a "most popular name" or not. -- Denis McMahon, denismfmcmahon at gmail.com From wuwei23 at gmail.com Mon Oct 27 20:33:05 2014 From: wuwei23 at gmail.com (alex23) Date: Tue, 28 Oct 2014 10:33:05 +1000 Subject: Anyone know the solution In-Reply-To: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> Message-ID: On 28/10/2014 1:10 AM, emmanueloje at gmail.com wrote: > Write a program that reads the contents of the two files into two separate lists. The user should be able to enter a boy's name, a girl's name or both, and the application will display messages indicating whether the names were among the most popular. This is actually a trick question. This is a classic unsolvable problem in computer science, known as the Dual Baskets problem. It is NP-complete, meaning that there is no easy solution. It requires brute-forcing and can take an indefinite period of time to complete, if at all. The correct answer is "Not possible". From denismfmcmahon at gmail.com Mon Oct 27 20:36:53 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Tue, 28 Oct 2014 00:36:53 +0000 (UTC) Subject: A bug? References: Message-ID: On Mon, 27 Oct 2014 09:01:57 -0700, umatrp at gmail.com wrote: > I use python 3.4.0 version. In the course of developing / running a > python program, I have encountered a problem. I have reproduced below a > simple program to bring it out. > > >>>> d = [[0]*3]*4 dd = [1,2,3,4,5,6,7,8,9,10,11,12] >>>> for i in range(4): > ... for j in range(3): d[i][j] = dd[i*3+j] > ... >>>> d > [[10, 11, 12], [10, 11, 12], [10, 11, 12], [10, 11, 12]] >>>> > d is not transferred to dd as expected? > Of course I can use 'append' & do my job (less elegantly though). Not sure if this is elegant or not: d = [[list(range(1,13))[i*3+j] for j in range(3)] for i in range(4)] but it seems to be a one-line solution for what you're trying to do. -- Denis McMahon, denismfmcmahon at gmail.com From rustompmody at gmail.com Mon Oct 27 21:12:17 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 27 Oct 2014 18:12:17 -0700 (PDT) Subject: A bug? In-Reply-To: References: Message-ID: On Tuesday, October 28, 2014 6:07:14 AM UTC+5:30, Denis McMahon wrote: > On Mon, 27 Oct 2014 09:01:57 -0700, umatrp wrote: > > I use python 3.4.0 version. In the course of developing / running a > > python program, I have encountered a problem. I have reproduced below a > > simple program to bring it out. > >>>> d = [[0]*3]*4 dd = [1,2,3,4,5,6,7,8,9,10,11,12] > >>>> for i in range(4): > > ... for j in range(3): d[i][j] = dd[i*3+j] > > ... > >>>> d > > [[10, 11, 12], [10, 11, 12], [10, 11, 12], [10, 11, 12]] > > d is not transferred to dd as expected? > > Of course I can use 'append' & do my job (less elegantly though). > Not sure if this is elegant or not: > d = [[list(range(1,13))[i*3+j] for j in range(3)] for i in range(4)] > but it seems to be a one-line solution for what you're trying to do. Neat More generally for d being a 2-D reshape of dd (which may be anything as long as the size matches) >>> dd = [1,2,3,4,5,6,7,8,9,10,11,12] >>> d=[[dd[i*3+j] for j in range(3)] for i in range(4)] >>> d [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] From rosuav at gmail.com Mon Oct 27 21:25:47 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 28 Oct 2014 12:25:47 +1100 Subject: A bug? In-Reply-To: References: Message-ID: On Tue, Oct 28, 2014 at 12:12 PM, Rustom Mody wrote: > More generally for d being a 2-D reshape of dd (which may be anything > as long as the size matches) > >>>> dd = [1,2,3,4,5,6,7,8,9,10,11,12] >>>> d=[[dd[i*3+j] for j in range(3)] for i in range(4)] >>>> d > [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] The inner comprehension should surely be a slice: >>> [dd[i*3:i*3+3] for i in range(4)] [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] ChrisA From joshua at landau.ws Mon Oct 27 21:29:28 2014 From: joshua at landau.ws (Joshua Landau) Date: Tue, 28 Oct 2014 01:29:28 +0000 Subject: A bug? In-Reply-To: References: Message-ID: On 28 October 2014 00:36, Denis McMahon wrote: > > d = [[list(range(1,13))[i*3+j] for j in range(3)] for i in range(4)] A quick note. Ranges (even 2.7's xrange) are all indexable. The cast to a list isn't needed. From rustompmody at gmail.com Mon Oct 27 22:13:02 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 27 Oct 2014 19:13:02 -0700 (PDT) Subject: A bug? In-Reply-To: References: Message-ID: <90cc19d7-a888-49aa-8005-15903e031f4a@googlegroups.com> On Tuesday, October 28, 2014 6:56:10 AM UTC+5:30, Chris Angelico wrote: > On Tue, Oct 28, 2014 at 12:12 PM, Rustom Mody wrote: > > More generally for d being a 2-D reshape of dd (which may be anything > > as long as the size matches) > > > >>>> dd = [1,2,3,4,5,6,7,8,9,10,11,12] > >>>> d=[[dd[i*3+j] for j in range(3)] for i in range(4)] > >>>> d > > [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] > > The inner comprehension should surely be a slice: > > >>> [dd[i*3:i*3+3] for i in range(4)] > [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] Sweet! [Something for my class today] Looks even better this way: >>> dd = range(1,13) >>> [dd[i*3:i*3+3] for i in range(4)] [range(1, 4), range(4, 7), range(7, 10), range(10, 13)] >>> In the same vein a transpose: >>> [list(dd[i::3]) for i in range(3)] [[0, 3, 6, 9], [1, 4, 7, 10], [2, 5, 8, 11]] [Not sure why both are 3; no 4's...] From rustompmody at gmail.com Mon Oct 27 22:37:07 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 27 Oct 2014 19:37:07 -0700 (PDT) Subject: memory, PE files, etc... In-Reply-To: References: <49c92881-e8bf-4e80-9e4d-8b88c0d12133@googlegroups.com> Message-ID: <387322ee-d76f-43dc-9a0b-69067a0d5fbc@googlegroups.com> On Tuesday, October 28, 2014 12:41:40 AM UTC+5:30, kiuh... at yahoo.it wrote: > On Monday, October 27, 2014 6:24:19 PM UTC+1, Tim Golden wrote: > > psutil is definitely your friend: > > > > https://github.com/giampaolo/psutil > > > > Although WMI can be quite handy too, depending on what you're trying to do: > > > > http://timgolden.me.uk/python/wmi/ > > > > TJG > > Thanks for answering. > I don't know if psutil is what I'm looking for. > What I need to do is more related to debugging than to administration. > Let's say I want to search for a sequence of bytes in the .text section of a given module. Can I do that with psutil? https://code.google.com/p/pefile/ ? From nobody at nowhere.invalid Mon Oct 27 23:52:43 2014 From: nobody at nowhere.invalid (Nobody) Date: Tue, 28 Oct 2014 03:52:43 +0000 Subject: Status of side-effecting functions in python References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> <87bnoxv91p.fsf@elektro.pacujo.net> Message-ID: On Mon, 27 Oct 2014 17:14:58 +0200, Marko Rauhamaa wrote: > In POSIX, a write(2) system call on file blocks until all bytes have been > passed on to the file system. The only exception (no pun intended) I know > is the reception of a signal. Writing to a file (or block device) will return a short count in the event that it results in the size of the file exceeding * the space available on the partition, * the user's quota, * the process' file size limit (RLIMIT_FSIZE), or * any implementation limit on the maximum size of a file, and at least one byte can be written. This behaviour is mandated by POSIX. This is different to writing to a socket, pipe or character device, where a short count is considered an entirely normal result, and a subsequent write for the remaining bytes will often succeed. > Even then, I'm not sure Linux file systems ever cut writes short because > of signals. Linux never interrupts I/O on discs or block devices due to signals. These are restarted regardless of whether the signal is set for automatic restarting (SA_RESTART flag). > I think the lack of nonblocking file access in Linux is one of the OS's > main shortcomings. It doesn't really matter. In the absence of an explicit mlock() or mlockall(), the actual code which would be controlling the access is demand-paged from disc, as is the "memory" to/from which the data is transferred (along with the memory which would hold the return code from read() or write(), for that matter). Asynchronous I/O in the sense of select(), poll(), O_NONBLOCK etc is meant for situations where delays could be indefinite, e.g. network connections or terminals. For "short" delays (i.e. disc access), there's not much point having a mechanism so that you can avoid blocking while the data is read from disc just so that you can block while the code in the "else" branch is read from disc. If you want the program to be able to do something else while waiting for I/O, use threads. The introduction of threads made most concurrency- related issues in the POSIX API moot. From tjreedy at udel.edu Tue Oct 28 00:08:27 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 28 Oct 2014 00:08:27 -0400 Subject: Classes and the command line In-Reply-To: References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> <85mw8i1aak.fsf@benfinney.id.au> <0d42e474-a864-4155-b602-e4659899fffd@googlegroups.com> Message-ID: On 10/26/2014 11:24 PM, Chris Angelico wrote: > On Mon, Oct 27, 2014 at 2:18 PM, Rustom Mody wrote: >> On Monday, October 27, 2014 8:40:48 AM UTC+5:30, Chris Angelico wrote: >>> You can get block-by-block history by using Idle. I find that fairly >>> convenient for manipulating class/function definitions. >>> >>> ChrisA >> >> Umm... Nice! >> A bit inconsistent in that the '...' does not appear. >> But thats good; makes copy|cut-pasting from interpreter to file >> a mostly trivial operation. One of the differences between console interpreter and Idle Shell is that the former is line oriented whereas Shell is statement oriented. In the console interpreter, you cannot edit a line after it is entered. In Shell, you can edit any line until you enter an entire statment. Similarly, c. i. history recalls a line at a time. Recalling an multiline statment has to be done a line at a time, in order. Shell history recalls an entire statement, even if multiple lines (this is what Chris means by 'blocks'). Explaining this difference as the reason for no ... is on my todo list. > It's inconsistent only because the default sys.ps2 is those dots, > which aren't necessary in Idle. You could make it consistent by simply > changing sys.ps2. Nope. User code is executed in the user process. Its only effect on the Idle process is to write to stdout or stderr for display. There is tracker issue about letting users change sys.ps1 *in the Idle process*, but it would have to be through the menu or config dialog. -- Terry Jan Reedy From tjreedy at udel.edu Tue Oct 28 00:14:53 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 28 Oct 2014 00:14:53 -0400 Subject: Classes and the command line In-Reply-To: References: Message-ID: On 10/26/2014 11:28 PM, Seymore4Head wrote: > I am going to be flexible on IDLE in the near future, but I wanted to > try it the old fashion way. I already know using IDLE is better, but > I am not sure using IDLE will invoke Python 2 and I am not sure how to > change that at the moment. Currently, Idle executes user code with the same interpreter it is running on. Now that user code is executed in a subprocess, there is the possibility of using a different python in the subprocess. But this is for the future. -- Terry Jan Reedy From tjreedy at udel.edu Tue Oct 28 00:24:01 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 28 Oct 2014 00:24:01 -0400 Subject: Anyone know the solution In-Reply-To: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> Message-ID: On 10/27/2014 11:10 AM, emmanueloje at gmail.com wrote: > THIS IS THE LIST OF BOY NAMES > Jacob > ... Writing hundreds of unnecessary lines at minimum inconsiderate. Please don't do it. -- Terry Jan Reedy From rosuav at gmail.com Tue Oct 28 00:57:10 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 28 Oct 2014 15:57:10 +1100 Subject: Classes and the command line In-Reply-To: References: <8uar4a1pa6d631ktr33h8rau1ilf2rjvi3@4ax.com> <85mw8i1aak.fsf@benfinney.id.au> <0d42e474-a864-4155-b602-e4659899fffd@googlegroups.com> Message-ID: On Tue, Oct 28, 2014 at 3:08 PM, Terry Reedy wrote: >> It's inconsistent only because the default sys.ps2 is those dots, >> which aren't necessary in Idle. You could make it consistent by simply >> changing sys.ps2. > > > Nope. User code is executed in the user process. Its only effect on the > Idle process is to write to stdout or stderr for display. There is tracker > issue about letting users change sys.ps1 *in the Idle process*, but it would > have to be through the menu or config dialog. I knew that, honest I did... umm, let's just pretend I was talking about changing sys.ps2 in the console interpreter. Yeah. Because I totally knew that changing it in Idle wouldn't work. Plus, I tested it before posting, like everyone should. Honest! Changing it in the console interpreter does work, though. Python 3.5.0a0 (default:301b9a58021c, Oct 2 2014, 09:20:24) [GCC 4.7.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.ps2=" " >>> def x(): pass >>> And if you want consistency, that's a good way to get it. ChrisA From ngangsia at gmail.com Tue Oct 28 02:42:37 2014 From: ngangsia at gmail.com (ngangsia akumbo) Date: Mon, 27 Oct 2014 23:42:37 -0700 (PDT) Subject: hotel management system Message-ID: <3f10c652-9d9d-4353-b24f-939d21978998@googlegroups.com> Please can someone look at my code and may be advice and may be help me with some correction. I have been learning python for some time now. This is my first project i wish to write. A hotel management system. http://pastebin.com/LMHmuTiC Thnaks From rosuav at gmail.com Tue Oct 28 03:09:36 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 28 Oct 2014 18:09:36 +1100 Subject: hotel management system In-Reply-To: <3f10c652-9d9d-4353-b24f-939d21978998@googlegroups.com> References: <3f10c652-9d9d-4353-b24f-939d21978998@googlegroups.com> Message-ID: On Tue, Oct 28, 2014 at 5:42 PM, ngangsia akumbo wrote: > Please can someone look at my code and may be advice and may be help me with some correction. I have been learning python for some time now. This is my first project i wish to write. A hotel management system. > > > http://pastebin.com/LMHmuTiC > Sure, we can do code reviews! It's usually helpful to provide your code in-line, though, rather than linking to pastebin. You're using Python 2, as evidenced by the print statements. So don't do this, ever: > def emp_age(): > """displaying employees age""" > > age = input("Enter age: ") The input function is extremely dangerous. Everywhere else, you use raw_input, which is correct. > class Bar: This is an old-style class. It's better to explicitly subclass object: class Bar(object): > class Beer(Bar): Not sure why you're doing this. Firstly, you never use your Beer class... but secondly, your Beer isn't a special type of Bar, it's a quite different thing. When you subclass, it's usually helpful to follow the Liskov Substitution Principle: https://en.wikipedia.org/wiki/Liskov_substitution_principle Think carefully about your class hierarchy, because it defines all sorts of things about your code. Be sure you're happy with it before you code up too much else. ChrisA From nomail at invalid.com Tue Oct 28 03:35:01 2014 From: nomail at invalid.com (ast) Date: Tue, 28 Oct 2014 08:35:01 +0100 Subject: Callback functions arguments In-Reply-To: References: <544dff5d$0$2073$426a74cc@news.free.fr> Message-ID: <544f4729$0$2399$426a74cc@news.free.fr> "Peter Otten" <__peter__ at web.de> a ?crit dans le message de news:mailman.15231.1414399974.18130.python-list at python.org... Tanks for you answer > Python doesn't "know" it has to pass an argument, it just does it. Change > the callback to > > def maj(): > print("no args") > > and you'll get an error. If I were to guess Yes you are right. I got an error: TypeError: maj() takes 0 positional arguments but 1 was given OK, but i still find very strange the choice of Python's designers to make the Scale behaves like that. The position of the scale is in variable Valeur (StringVar()) which cold be read/write from anywhere, so it is not necessary to pass this variable as an argument to the call back function. If you are looking at the SpinBox widget, in example 4 in the same web site: http://fsincere.free.fr/isn/python/cours_python_tkinter.php boite = Spinbox(Mafenetre,from_=0,to=10,increment=0.5, \ textvariable=Valeur,width=5,command=carre) with the callback function "carre" def carre(): """ Calcul du carr? """ Resultat.set("Carr? = "+str(float(Valeur.get())**2)) you can notice that carre function has no arguments. The value in the SpinBox is catched with Valeur variable. So SpinBox and Scale behaves differently. It is strange. > you probably are misled by the 'command=maj' part in the above line. no, I understood this mechanism From rosuav at gmail.com Tue Oct 28 03:51:21 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 28 Oct 2014 18:51:21 +1100 Subject: Callback functions arguments In-Reply-To: <544f4729$0$2399$426a74cc@news.free.fr> References: <544dff5d$0$2073$426a74cc@news.free.fr> <544f4729$0$2399$426a74cc@news.free.fr> Message-ID: On Tue, Oct 28, 2014 at 6:35 PM, ast wrote: > OK, but i still find very strange the choice of Python's designers to > make the Scale behaves like that. That's nothing to do with Python's design. That's all about Tkinter, which presumably is imitating Tk. Python allows the callback function to be called with whatever arguments the caller wishes; you can look at the docs for the different objects to see what args they'll be giving their callbacks. ChrisA From nad at acm.org Tue Oct 28 04:11:50 2014 From: nad at acm.org (Ned Deily) Date: Tue, 28 Oct 2014 01:11:50 -0700 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? References: Message-ID: In article , Cyd Haselton wrote: [...] > I'm building python on an Android device in the KBOX > environment...which simulates a Unix type filesystem. > Python isn't installed; I'm building from sources (2.7.8) with GCC > 4.8.0 and make. > > The problem with the LDFLAGS approach is that some of the libraries > that must be linked (-lc -ldl) do not need the --allow-shlib-undefined > option...it's only the lpython2.7 that does. Any way to do this? Sorry, I have no experience with that environment nor an understanding of why you need to specify --allow-shlib-undefined (it seems to be the default in some versions of ld). You could look at and, if necessary, modify Lib/distutils, the part of the Python standard library that builds extension modules from setup.py. -- Ned Deily, nad at acm.org From eileenjthompson8 at gmail.com Tue Oct 28 04:48:19 2014 From: eileenjthompson8 at gmail.com (Eileen | Cellsix Pty Ltd) Date: Tue, 28 Oct 2014 08:48:19 +0000 Subject: www.python.org Message-ID: <089e013cc44c7e9d8e050677b59c@google.com> Hi, I recently browsed through your business website and wanted to highlight some key points for consideration. I am sure it will complement your-SEO work to help your website attract only quality visitors and make it scale high on the search .engine results page (SERP) gradually. Would you be interested in receiving the details? Best regards, Eileen Online-Strategist CELLsIX MEDIA PTY LTD. Headquarters: Office 7003 X2 Tower, Cluster X, Melbourne Vic. 3000 Australia Other Branches: Sydney | Perth | Brisbane | Adelaide | Hobart Disclaimer: This e-mail is private and confidential. If you are not the intended recipient, please advise us by return e-mail immediately, and delete the e-mail and any attachments without using or disclosing the contents in any way. The views expressed in this e-mail are those of the author, and do not represent those of this company unless this is clearly indicated. You should scan this e-mail and any attachments for viruses. This company accepts no liability for any direct or indirect damage or loss resulting from the use of any attachments to this e-mail. All quotes received from Cellsix Media by email are informal and not binding until a formal quote is agreed upon by both the parties. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marko at pacujo.net Tue Oct 28 05:07:14 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 28 Oct 2014 11:07:14 +0200 Subject: Status of side-effecting functions in python References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> <87bnoxv91p.fsf@elektro.pacujo.net> Message-ID: <87y4s0tvel.fsf@elektro.pacujo.net> Nobody : > Asynchronous I/O in the sense of select(), poll(), O_NONBLOCK etc is > meant for situations where delays could be indefinite, e.g. network > connections or terminals. For "short" delays (i.e. disc access), > there's not much point having a mechanism so that you can avoid > blocking while the data is read from disc just so that you can block > while the code in the "else" branch is read from disc. I disagree with the "shortness" of the delays. > If you want the program to be able to do something else while waiting > for I/O, use threads. The introduction of threads made most > concurrency- related issues in the POSIX API moot. I disagree about that point of view as well. If files played ball with select() et al, the linux world would be a better, more coherent place. For example, looking at Python3's asyncio, I don't want to go out of the asyncio model just because of disk (or DB) access. Marko From marko at pacujo.net Tue Oct 28 05:10:07 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Tue, 28 Oct 2014 11:10:07 +0200 Subject: Status of side-effecting functions in python References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> <87bnoxv91p.fsf@elektro.pacujo.net> Message-ID: <87tx2otv9s.fsf@elektro.pacujo.net> Marko Rauhamaa : > Python's sockets and pipes don't have write methods. Actually, that's mistaken as well. The sys.std* handles and pipes returned by subprocess are accessed using file.write() and thus may return partial writes. That brings up another point: Python3's file.write() returns the number of characters written. What might it return if a partial character should be written? Marko From massi_srb at msn.com Tue Oct 28 07:02:44 2014 From: massi_srb at msn.com (massi_srb at msn.com) Date: Tue, 28 Oct 2014 04:02:44 -0700 (PDT) Subject: Regex substitution trouble Message-ID: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> Hi everyone, I'm not really sure if this is the right place to ask about regular expressions, but since I'm usin python I thought I could give a try :-) Here is the problem, I'm trying to write a regex in order to substitute all the occurences in the form $"somechars" with another string. This is what I wrote: newstring = re.sub(ur"""(?u)(\$\"[\s\w]+\")""", subst, oldstring) This works pretty well, but it has a problem, I would need it also to handle the case in which the internal string contains the double quotes, but only if preceeded by a backslash, that is something like $"somechars_with\\"doublequotes". Can anyone help me to correct it? Thanks in advance! From eugen.wintersberger at desy.de Tue Oct 28 07:09:27 2014 From: eugen.wintersberger at desy.de (Wintersberger, Eugen) Date: Tue, 28 Oct 2014 12:09:27 +0100 Subject: C++ extension and shared library with distutils Message-ID: <35E004AD6290A7438FCA34BBF325F41606996A81@ADXV2.win.desy.de> Hi folks I have a little problem with a Python extension and could not find a good solution in the documentation. So hopefully someone here has a clever idea. Here is the problem: I have two extensions written in C++ (bindings to existing C++ code). Lets call this two extensions C and B which are part of a larger package with parent A. So in the simplest case the installation on Linux would somehow look like this A/ __init__.py B/ __init__.py _b.so C/ __init__.py _c.so The extension C is optional but depends on B. In the code for C I would like to use some utilities developed for B. The idea was to keep this utility functions in a shared library and link B and C against this library. Lets call this library libb_utils.so. The problem here is that the code in libb_utils.so depends on the Python version used to build the extensions so it is not possible to build a Python agnostic version of the library. My idea now was to build extension B and in the same code tree build libb_utils.so. The idea was to install this shared object along with the extension and then link C against it. The new installation would look like this A/ __init__.py B/ __init__.py _b.so libb_utils.so with header files for libb_utils.so in $PREFIX/include/pythonX.Y/A/B/ My hope is that I can do all this with distutils. Building and installing the extension is trivial. But 1.) is there a better way to build a shared library with distutils than using the CCompiler submodule? 2.) is the way I am planning the installation of my code ok or is there a better way (maybe even a kind of standard) to deal with such a situation. best regards and thanks in advance Eugen Wintersberger -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 230 bytes Desc: This is a digitally signed message part URL: From nomail at invalid.com Tue Oct 28 07:14:30 2014 From: nomail at invalid.com (ast) Date: Tue, 28 Oct 2014 12:14:30 +0100 Subject: Callback functions arguments In-Reply-To: References: <544dff5d$0$2073$426a74cc@news.free.fr> <544f4729$0$2399$426a74cc@news.free.fr> Message-ID: <544f7a9a$0$5115$426a74cc@news.free.fr> "Chris Angelico" a ?crit dans le message de news:mailman.15254.1414482690.18130.python-list at python.org... > On Tue, Oct 28, 2014 at 6:35 PM, ast wrote: That's clear to me now. Spinbox and Scale widgets behave differently, that's all. Command on Scale widget: A procedure to be called every time the slider is moved. This procedure will be passed one argument, the new scale value. If the slider is moved rapidly, you may not get a callback for every possible position, but you'll certainly get a callback when it settles Command on Spinbox widget A procedure to be called whenever the scrollbar is moved. No argument is passed. From rosuav at gmail.com Tue Oct 28 07:24:42 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 28 Oct 2014 22:24:42 +1100 Subject: Regex substitution trouble In-Reply-To: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> References: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> Message-ID: On Tue, Oct 28, 2014 at 10:02 PM, wrote: > I'm not really sure if this is the right place to ask about regular expressions, but since I'm usin python I thought I could give a try :-) Yeah, that sort of thing is perfectly welcome here. Same with questions about networking in Python, or file I/O in Python, or anything like that. Not a problem! > Here is the problem, I'm trying to write a regex in order to substitute all the occurences in the form $"somechars" with another string. This is what I wrote: > > newstring = re.sub(ur"""(?u)(\$\"[\s\w]+\")""", subst, oldstring) > > This works pretty well, but it has a problem, I would need it also to handle the case in which the internal string contains the double quotes, but only if preceeded by a backslash, that is something like $"somechars_with\\"doublequotes". > Can anyone help me to correct it? But this is a problem. You can use look-ahead assertions and such to allow the string \" inside your search string, but presumably the backslash ought itself to be escapable, in order to make it possible to have a loose backslash legal at the end of the string. I suggest that, instead of a regex, you look for a different way of parsing. What's the surrounding text like? ChrisA From robin at reportlab.com Tue Oct 28 07:30:37 2014 From: robin at reportlab.com (Robin Becker) Date: Tue, 28 Oct 2014 11:30:37 +0000 Subject: Python Fabric on Windows : In-Reply-To: References: Message-ID: <544F7E5D.8070906@chamonix.reportlab.co.uk> On 27/10/2014 04:49, Ganesh Pal wrote: > Hi Team , > > Iam new to Fabric and Iam using the fab command-line tool to run a set > of task on Linux clients. > > I just started coding and Iam pretty new to fabric, Iam hoping I will be > able to launch my fabric scripts from both Windows and Linux Machine . > I found fabric on windows quite hard, but I have managed to use it. For ssh I think I had to use the putty tools eg plink to do remote work. On the other hand I find plumbum much easier http://tomerfiliba.com/blog/Plumbum/ > Installing Cygwin might help in windows case I guess. please suggest if > you foresee problems using fabric on Windows and also suggest an > alternative to this if available. . > -- Robin Becker From gandalf23 at mail.com Tue Oct 28 08:15:40 2014 From: gandalf23 at mail.com (gandalf23 at mail.com) Date: Tue, 28 Oct 2014 05:15:40 -0700 (PDT) Subject: memory, PE files, etc... In-Reply-To: <387322ee-d76f-43dc-9a0b-69067a0d5fbc@googlegroups.com> References: <49c92881-e8bf-4e80-9e4d-8b88c0d12133@googlegroups.com> <387322ee-d76f-43dc-9a0b-69067a0d5fbc@googlegroups.com> Message-ID: <802a6f09-77dc-4612-8b87-e642c4e22ba8@googlegroups.com> On Tuesday, October 28, 2014 3:37:19 AM UTC+1, Rustom Mody wrote: > On Tuesday, October 28, 2014 12:41:40 AM UTC+5:30, kiuh... at yahoo.it wrote: > > On Monday, October 27, 2014 6:24:19 PM UTC+1, Tim Golden wrote: > > > psutil is definitely your friend: > > > > > > https://github.com/giampaolo/psutil > > > > > > Although WMI can be quite handy too, depending on what you're trying to do: > > > > > > http://timgolden.me.uk/python/wmi/ > > > > > > TJG > > > > Thanks for answering. > > I don't know if psutil is what I'm looking for. > > What I need to do is more related to debugging than to administration. > > Let's say I want to search for a sequence of bytes in the .text section of a given module. Can I do that with psutil? > > https://code.google.com/p/pefile/ > > ? I need to analyze the memory of running processes. The answer is PyDbg or direct access to the API of Windows. From massi_srb at msn.com Tue Oct 28 08:28:13 2014 From: massi_srb at msn.com (massi_srb at msn.com) Date: Tue, 28 Oct 2014 05:28:13 -0700 (PDT) Subject: Regex substitution trouble In-Reply-To: References: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> Message-ID: Hi Chris, thanks for the reply. I tried to use look ahead assertions, in particular I modified the regex this way: newstring = re.sub(ur"""(?u)(\$\"[\s\w(?<=\\)\"]+\")""", subst, oldstring) but it does not work. I'm absolutely not a regex guru so I'm surely missing something. The strings I'm dealing with are similar to formulas, let's say something like: '$["simple_input"]+$["messed_\\"_input"]+10' Thanks for any help! From rosuav at gmail.com Tue Oct 28 08:59:31 2014 From: rosuav at gmail.com (Chris Angelico) Date: Tue, 28 Oct 2014 23:59:31 +1100 Subject: Regex substitution trouble In-Reply-To: References: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> Message-ID: (Please quote enough of the previous text to provide context, and write your replies underneath the quoted text - don't assume that everyone's read the previous posts. Thanks!) On Tue, Oct 28, 2014 at 11:28 PM, wrote: > Hi Chris, thanks for the reply. I tried to use look ahead assertions, in particular I modified the regex this way: > > newstring = re.sub(ur"""(?u)(\$\"[\s\w(?<=\\)\"]+\")""", subst, oldstring) > > but it does not work. I'm absolutely not a regex guru so I'm surely missing something. Yeah, I'm not a high-flying regex programmer either, so I'll leave the specifics for someone else to answer. Tip, though: Print out your regex, to see if it's really what you think it is. When you get backslashes and quotes coming through, sometimes you can get tangled, even in a raw string literal; sometimes, one quick print(some_re) can save hours of hair-pulling. > The strings I'm dealing with are similar to formulas, let's say something like: > > '$["simple_input"]+$["messed_\\"_input"]+10' > > Thanks for any help! Hmm. This looks like a job for ast.literal_eval with an actual dictionary. All you'd have to do is replace every instance of $ with a dict literal; it mightn't be efficient, but it would be safe. Using Python 2.7.8 as you appear to be on 2.x: >>> expr = '$["simple_input"]+$["messed_\\"_input"]+10' >>> values = {"simple_input":123, "messed_\"_input":75} >>> ast.literal_eval(expr.replace("$",repr(values))) Traceback (most recent call last): File "", line 1, in ast.literal_eval(expr.replace("$",repr(values))) File "C:\Python27\lib\ast.py", line 80, in literal_eval return _convert(node_or_string) File "C:\Python27\lib\ast.py", line 79, in _convert raise ValueError('malformed string') ValueError: malformed string Unfortunately, it doesn't appear to work, as evidenced by the above message. It works with the full (and dangerous) eval, though: >>> eval(expr.replace("$",repr(values))) 208 Can someone who better knows ast.literal_eval() explain what's malformed about this? The error message in 3.4 is a little more informative, but not much more helpful: ValueError: malformed node or string: <_ast.BinOp object at 0x0169BAF0> My best theory is that subscripting isn't allowed, though this seems odd. In any case, it ought in theory to be possible to use Python's own operations on this. You might have to do some manipulation, but it'd mean you can leverage a full expression evaluator that already exists. I'd eyeball the source code for ast.literal_eval() and see about making an extended version that allows the operations you want. If you can use something other than a dollar sign - something that's syntactically an identifier - you'll be able to skip the textual replace() operation, which is risky (might change the wrong thing). Do that, and you could have your own little evaluator that uses the ast module for most of its work, and simply runs a little recursive walker that deals with the nodes as it finds them. ChrisA From wingusr at gmail.com Tue Oct 28 09:25:00 2014 From: wingusr at gmail.com (TP) Date: Tue, 28 Oct 2014 06:25:00 -0700 Subject: Regex substitution trouble In-Reply-To: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> References: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> Message-ID: On Tue, Oct 28, 2014 at 4:02 AM, wrote: > Hi everyone, > > I'm not really sure if this is the right place to ask about regular > expressions, but since I'm usin python I thought I could give a try :-) > Here is the problem, I'm trying to write a regex in order to substitute > all the occurences in the form $"somechars" with another string. This is > what I wrote: > > newstring = re.sub(ur"""(?u)(\$\"[\s\w]+\")""", subst, oldstring) > > This works pretty well, but it has a problem, I would need it also to > handle the case in which the internal string contains the double quotes, > but only if preceeded by a backslash, that is something like > $"somechars_with\\"doublequotes". > Can anyone help me to correct it? > > Thanks in advance! > -- > https://mail.python.org/mailman/listinfo/python-list > Carefully reading the Strings section of "Example Regexes to Match Common Programming Language Constructs" [1] should (with a bit of effort), solve your problem I think. Note the use of the negated character class for one thing. [1] http://www.regular-expressions.info/examplesprogrammer.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From ngangsia at gmail.com Tue Oct 28 11:01:11 2014 From: ngangsia at gmail.com (ngangsia akumbo) Date: Tue, 28 Oct 2014 08:01:11 -0700 (PDT) Subject: bulk sms with python Message-ID: I need to build a bulk SMS system for a particular group of users. i WAS THINKING OF USING RAPIDSMS, AND KANNEL. Is there not a way to use just python from scratch to build a bulk sms system or if there are other simpler means please indicate to me. Thanks Ngangsi Richard skyoe: ngangsia.richard From bobjects at gmail.com Tue Oct 28 11:27:09 2014 From: bobjects at gmail.com (Bob Hartwig) Date: Tue, 28 Oct 2014 08:27:09 -0700 Subject: bulk sms with python In-Reply-To: References: Message-ID: Sounds like you want to use Twisted or something to implement the SMPP protocol. That's not trivial, but probably not too difficult; if you don't need message delivery confirmation, it should be stateless. Bob On Tue, Oct 28, 2014 at 8:01 AM, ngangsia akumbo wrote: > I need to build a bulk SMS system for a particular group of users. > > i WAS THINKING OF USING RAPIDSMS, AND KANNEL. > > Is there not a way to use just python from scratch to build a bulk sms > system > > or if there are other simpler means please indicate to me. > > > Thanks > > Ngangsi Richard > > skyoe: ngangsia.richard > > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nimbiotics at gmail.com Tue Oct 28 11:38:33 2014 From: nimbiotics at gmail.com (Mario R. Osorio) Date: Tue, 28 Oct 2014 08:38:33 -0700 (PDT) Subject: Anyone know the solution In-Reply-To: References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> Message-ID: On Tuesday, October 28, 2014 12:25:13 AM UTC-4, Terry Reedy wrote: > On 10/27/2014 11:10 AM, emmanueloje at gmail.com wrote: > > > THIS IS THE LIST OF BOY NAMES > > Jacob > > ... > > Writing hundreds of unnecessary lines at minimum inconsiderate. Please > don't do it. > > -- > Terry Jan Reedy The python programming community is BY FAR the best I've been in touch with. Asking for help with some code that is not working is OK here, but asking to have the homework done is disgusting. Just try mentioning the word homework on c++ or javascrip groups: They'll bully you to death! From sffjunkie at gmail.com Tue Oct 28 11:47:43 2014 From: sffjunkie at gmail.com (Simon Kennedy) Date: Tue, 28 Oct 2014 08:47:43 -0700 (PDT) Subject: OS X Menubar in Tkinter In-Reply-To: References: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> Message-ID: <70233fcf-d51d-4dab-bff4-6f9911d319bf@googlegroups.com> On Thursday, 23 October 2014 20:02:43 UTC+1, Chris Angelico wrote: > I don't think it's possible to auto-solve the Google Groups formatting > issues at the mailing list level, as the fundamental problem is that > information isn't being transmitted. (Forcing everything to be wrapped > and forcing blank line removal risks breaking other formatting.) The > last time I had a job interview with Google, I said that I wanted to > spend my 20% time fixing Google Groups' paragraph handling... and then > they didn't hire me. Not sure if this is coincidental or not. :) > > ChrisA Hopefully something may be happening... https://productforums.google.com/d/msg/apps/4WQcWWajjvU/0NF7JgezGS0J From rustompmody at gmail.com Tue Oct 28 11:59:25 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 28 Oct 2014 08:59:25 -0700 (PDT) Subject: OS X Menubar in Tkinter In-Reply-To: <70233fcf-d51d-4dab-bff4-6f9911d319bf@googlegroups.com> References: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> <70233fcf-d51d-4dab-bff4-6f9911d319bf@googlegroups.com> Message-ID: On Tuesday, October 28, 2014 9:18:09 PM UTC+5:30, Simon Kennedy wrote: > On Thursday, 23 October 2014 20:02:43 UTC+1, Chris Angelico wrote: > > I don't think it's possible to auto-solve the Google Groups formatting > > issues at the mailing list level, as the fundamental problem is that > > information isn't being transmitted. (Forcing everything to be wrapped > > and forcing blank line removal risks breaking other formatting.) The > > last time I had a job interview with Google, I said that I wanted to > > spend my 20% time fixing Google Groups' paragraph handling... and then > > they didn't hire me. Not sure if this is coincidental or not. :) > > > > ChrisA > > Hopefully something may be happening... > > https://productforums.google.com/d/msg/apps/4WQcWWajjvU/0NF7JgezGS0J Yay! Seems to be fixed! [Posted from GG without my usual post-processing filter. Ok??] From rosuav at gmail.com Tue Oct 28 12:06:47 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 29 Oct 2014 03:06:47 +1100 Subject: OS X Menubar in Tkinter In-Reply-To: <70233fcf-d51d-4dab-bff4-6f9911d319bf@googlegroups.com> References: <45ced550-3ff2-4cc1-8592-6d1ca01caa8a@googlegroups.com> <70233fcf-d51d-4dab-bff4-6f9911d319bf@googlegroups.com> Message-ID: On Wed, Oct 29, 2014 at 2:47 AM, Simon Kennedy wrote: > On Thursday, 23 October 2014 20:02:43 UTC+1, Chris Angelico wrote: >> I don't think it's possible to auto-solve the Google Groups formatting >> issues at the mailing list level, as the fundamental problem is that >> information isn't being transmitted. (Forcing everything to be wrapped >> and forcing blank line removal risks breaking other formatting.) The >> last time I had a job interview with Google, I said that I wanted to >> spend my 20% time fixing Google Groups' paragraph handling... and then >> they didn't hire me. Not sure if this is coincidental or not. :) >> >> ChrisA > > Hopefully something may be happening... > > https://productforums.google.com/d/msg/apps/4WQcWWajjvU/0NF7JgezGS0J Wow! That'd be awesome. If they can properly wrap text and not double-space, most of the GG issues would vanish. ChrisA From ngangsia at gmail.com Tue Oct 28 12:07:17 2014 From: ngangsia at gmail.com (ngangsia akumbo) Date: Tue, 28 Oct 2014 09:07:17 -0700 (PDT) Subject: Anyone know the solution In-Reply-To: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> Message-ID: This is a sample code on how to read data from a file files1 {} result = open("file1.txt") for line in result: file1 = line>split() files1.append(file1) result.close() file1.sort() file1.reverse() print('THE FILE INFO') print(file1(0) print(file1(1) From jtim.arnold at gmail.com Tue Oct 28 12:38:00 2014 From: jtim.arnold at gmail.com (Tim) Date: Tue, 28 Oct 2014 09:38:00 -0700 (PDT) Subject: Regex substitution trouble In-Reply-To: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> References: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> Message-ID: <87db4b2a-9982-4cd5-9148-12aacb20bcc1@googlegroups.com> On Tuesday, October 28, 2014 7:03:00 AM UTC-4, mass... at msn.com wrote: > Hi everyone, > I'm not really sure if this is the right place to ask about regular expressions, but since I'm usin python I thought I could give a try :-) > Here is the problem, I'm trying to write a regex in order to substitute all the occurences in the form $"somechars" with another string. This is what I wrote: > newstring = re.sub(ur"""(?u)(\$\"[\s\w]+\")""", subst, oldstring) > > This works pretty well, but it has a problem, I would need it also to handle the case in which the internal string contains the double quotes, but only if preceeded by a backslash, that is something like $"somechars_with\\"doublequotes". > Can anyone help me to correct it? > Thanks in advance! You have some good answers already, but I wanted to let you know about a tool you may already have which is useful for experimenting with regexps. On windows, the file `redemo.py` is in the Tools/Scripts folder. If you're on a Mac, see http://stackoverflow.com/questions/1811236/how-can-i-run-redemo-py-or-equivalent-on-a-mac It has really helped me work on some tough regexps. good luck, --Tim From python at mrabarnett.plus.com Tue Oct 28 13:52:32 2014 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 28 Oct 2014 17:52:32 +0000 Subject: Regex substitution trouble In-Reply-To: References: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> Message-ID: <544FD7E0.8000205@mrabarnett.plus.com> On 2014-10-28 12:28, massi_srb at msn.com wrote: > Hi Chris, thanks for the reply. I tried to use look ahead assertions, in particular I modified the regex this way: > > newstring = re.sub(ur"""(?u)(\$\"[\s\w(?<=\\)\"]+\")""", subst, oldstring) > > but it does not work. I'm absolutely not a regex guru so I'm surely missing something. The strings I'm dealing with are similar to formulas, let's say something like: > > '$["simple_input"]+$["messed_\\"_input"]+10' > > Thanks for any help! > Your original post said you wanted to match strings like: $"somechars_with\\"doublequotes". This regex will do that: ur'\$"[^"\\]*(?:\\.[^"\\]*)*"' However, now you say you want to match: '$["simple_input"]' This is different; it has '[' immediately after the '$' instead of '"'. From ethan at stoneleaf.us Tue Oct 28 15:53:52 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 28 Oct 2014 12:53:52 -0700 Subject: [ANN] dbf v0.96 is released Message-ID: <544FF450.5020807@stoneleaf.us> and finally supports Python 3! :) Versions supported are 2.5 - 2.7, and 3.2+ ========================================= dbf === dbf (also known as python dbase) is a module for reading/writing dBase III, FP, VFP, and Clipper .dbf database files. It's an ancient format that still finds lots of use (the most common I'm aware of is retrieving legacy data so it can be stored in a newer database system; other uses include GIS, stand-alone programs such as Family History, Personal Finance, etc.). Highlights ---------- Table -- represents a single .dbf/.dbt (or .fpt) file combination and provides access to records; suports the sequence access and 'with' protocols. Temporary tables can also live entirely in memory. Record -- repesents a single record/row in the table, with field access returning native or custom data types; supports the sequence, mapping, attribute access (with the field names as the attributes), and 'with' protocols. Updates to a record object are reflected on disk either immediately (using gather() or write()), or at the end of a 'with' statement. Index -- nonpersistent index for a table. Fields:: dBase III (Null not supported) Character --> unicode Date --> datetime.date or None Logical --> bool or None Memo --> unicode or None Numeric --> int/float depending on field definition or None Float --> same as numeric Clipper (Null not supported) Character --> unicode (character fields can be up to 65,519) Foxpro (Null supported) General --> str/bytes (treated as binary) Picture --> str/bytes (treated as binary) Visual Foxpro (Null supported) Currency --> decimal.Decimal douBle --> float Integer --> int dateTime --> datetime.datetime If a field is uninitialized (Date, Logical, Numeric, Memo, General, Picture) then None is returned for the value. Custom data types:: Null --> used to support Null values Char --> unicode type that auto-trims trailing whitespace, and ignores trailing whitespace for comparisons Date --> date object that allows for no date DateTime --> datetime object that allows for no datetime Time --> time object that allows for no time Logical --> adds Unknown state to bool's: instead of True/False/None, values are Truth, Falsth, and Unknown, with appropriate tri-state logic; just as bool(None) is False, bool(Unknown) is also False; the numerical values of Falsth, Truth, and Unknown is 0, 1, 2 Quantum --> similar to Logical, but implements boolean algebra (I think). Has states of Off, On, and Other. Other has no boolean nor numerical value, and attempts to use it as such will raise an exception Whirlwind Tour -------------- import datetime import dbf table = dbf.Table( filename='test', field_specs='name C(25); age N(3,0); birth D; qualified L', on_disk=False, ) table.open() for datum in ( ('Spanky', 7, dbf.Date.fromymd('20010315'), False), ('Spunky', 23, dbf.Date(1989, 07, 23), True), ('Sparky', 99, dbf.Date(), dbf.Unknown), ): table.append(datum) for record in table: print record print '--------' print record[0:3] print record['name':'qualified'] print [record.name, record.age, record.birth] print '--------' custom = table.new( filename='test_on_disk', default_data_types=dict(C=dbf.Char, D=dbf.Date, L=dbf.Logical), ) with custom: # automatically opened and closed for record in table: custom.append(record) for record in custom: dbf.write(record, name=record.name.upper()) print record print '--------' print record[0:3] print record['name':'qualified'] print [record.name, record.age, record.birth] print '--------' table.close() From python.list at tim.thechases.com Tue Oct 28 16:08:56 2014 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 28 Oct 2014 15:08:56 -0500 Subject: [ANN] dbf v0.96 is released In-Reply-To: <544FF450.5020807@stoneleaf.us> References: <544FF450.5020807@stoneleaf.us> Message-ID: <20141028150856.1f070f88@bigbox.christie.dr> On 2014-10-28 12:53, Ethan Furman wrote: > dbf (also known as python dbase) is a module for reading/writing > dBase III, FP, VFP, and Clipper .dbf database files. It's > an ancient format that still finds lots of use Just a little note to give thanks for all the work you put into such an unglamorous-yet-backside-saving project. It *is* appreciated by those of us who have had to disinter data from old client .dbf files. -tkc From ethan at stoneleaf.us Tue Oct 28 16:28:58 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 28 Oct 2014 13:28:58 -0700 Subject: [ANN] dbf v0.96 is released In-Reply-To: <20141028150856.1f070f88@bigbox.christie.dr> References: <544FF450.5020807@stoneleaf.us> <20141028150856.1f070f88@bigbox.christie.dr> Message-ID: <544FFC8A.2080007@stoneleaf.us> On 10/28/2014 01:08 PM, Tim Chase wrote: > > Just a little note to give thanks for all the work you put into such > an unglamorous-yet-backside-saving project. It *is* appreciated by > those of us who have had to disinter data from old client .dbf files. Thank you! :) -- ~Ethan~ From cousinstanley at gmail.com Tue Oct 28 16:34:11 2014 From: cousinstanley at gmail.com (Cousin Stanley) Date: Tue, 28 Oct 2014 13:34:11 -0700 Subject: [ANN] dbf v0.96 is released References: Message-ID: > .... > dbf > === > > dbf (also known as python dbase) is a module > for reading/writing dBase III, FP, VFP, > and Clipper .dbf database files. > .... Available via PyPI at ? https://pypi.python.org/pypi/dbf/0.96.001 -- Stanley C. Kitching Human Being Phoenix, Arizona From chaselton at gmail.com Tue Oct 28 16:40:49 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Tue, 28 Oct 2014 15:40:49 -0500 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? In-Reply-To: References: Message-ID: On Tue, Oct 28, 2014 at 3:11 AM, Ned Deily wrote: > In article > , > Cyd Haselton wrote: > [...] >> I'm building python on an Android device in the KBOX >> environment...which simulates a Unix type filesystem. >> Python isn't installed; I'm building from sources (2.7.8) with GCC >> 4.8.0 and make. >> >> The problem with the LDFLAGS approach is that some of the libraries >> that must be linked (-lc -ldl) do not need the --allow-shlib-undefined >> option...it's only the lpython2.7 that does. Any way to do this? > > Sorry, I have no experience with that environment nor an understanding > of why you need to specify --allow-shlib-undefined (it seems to be the > default in some versions of ld). You could look at and, if necessary, > modify Lib/distutils, the part of the Python standard library that > builds extension modules from setup.py. > > -- > Ned Deily, > nad at acm.org > > -- > https://mail.python.org/mailman/listinfo/python-list No need to apologize. Also no need to have an understanding of the environment; with a few rare exceptions it behaves just like a Unix/Linux one. The reason why I need to specify --allow-shlib-undefined is for the python library; it's throwing undefined references to sincos even though the symbol is there. Specifying that option is the only fix I've found. As mentioned earlier, i'm not familiar with python or its build system; which file in the distutils dir do I need to modify? From ethan at stoneleaf.us Tue Oct 28 16:51:03 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 28 Oct 2014 13:51:03 -0700 Subject: [ANN] dbf v0.96 is released In-Reply-To: References: Message-ID: <545001B7.4070100@stoneleaf.us> On 10/28/2014 01:34 PM, Cousin Stanley wrote: >> .... >> dbf >> === >> >> dbf (also known as python dbase) is a module >> for reading/writing dBase III, FP, VFP, >> and Clipper .dbf database files. >> .... > > Available via PyPI at ? > > https://pypi.python.org/pypi/dbf/0.96.001 Ah, yes, that's the place! Although I usually leave off the version so the link is always to the most recent: https://pypi.python.org/pypi/dbf -- ~Ethan~ From nad at acm.org Tue Oct 28 17:01:34 2014 From: nad at acm.org (Ned Deily) Date: Tue, 28 Oct 2014 14:01:34 -0700 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? References: Message-ID: In article , Cyd Haselton wrote: > On Tue, Oct 28, 2014 at 3:11 AM, Ned Deily wrote: > > In article > > , > > Cyd Haselton wrote: > > [...] > >> I'm building python on an Android device in the KBOX > >> environment...which simulates a Unix type filesystem. > >> Python isn't installed; I'm building from sources (2.7.8) with GCC > >> 4.8.0 and make. > >> > >> The problem with the LDFLAGS approach is that some of the libraries > >> that must be linked (-lc -ldl) do not need the --allow-shlib-undefined > >> option...it's only the lpython2.7 that does. Any way to do this? > > > > Sorry, I have no experience with that environment nor an understanding > > of why you need to specify --allow-shlib-undefined (it seems to be the > > default in some versions of ld). You could look at and, if necessary, > > modify Lib/distutils, the part of the Python standard library that > > builds extension modules from setup.py. > No need to apologize. Also no need to have an understanding of the > environment; with a few rare exceptions it behaves just like a > Unix/Linux one. > > The reason why I need to specify --allow-shlib-undefined is for the > python library; it's throwing undefined references to sincos even > though the symbol is there. Specifying that option is the only fix > I've found. > > As mentioned earlier, i'm not familiar with python or its build > system; which file in the distutils dir do I need to modify? Perhaps I should apologize for not asking earlier what you are really trying to do before suggesting heading down the path of modifying Distutils :) So the issue is with an undefined reference to sincos? It appears that that routine is often supplied in libm. Is that the case on your platform? And, if so, the right fix might be to supply it manually or, better, ensure that Python supplies it as a result of running ./configure. Also, what version of Python are you building? -- Ned Deily, nad at acm.org From juan0christian at gmail.com Tue Oct 28 17:45:13 2014 From: juan0christian at gmail.com (Juan Christian) Date: Tue, 28 Oct 2014 19:45:13 -0200 Subject: Python 3.4.2 + PyQt4 + PyCharm 3.4.1 Message-ID: Python 3.4.2 Windows x64 PyQt4 4.11.2 Py3.4 Qt4.8.6 (x64) PyCharm 3.4.1 Pro Edition So, PyCharm works 100% with everything here but PyQt. I have this folder structure: Disk C: > PyQt4 >> Lib/site-packages/PyQt4/(tons of files here) > Python34 (normal/default installation) --- I tried copying the 'PyQt4' folder to my 'Python34/Lib/site-packages' folder but when I try to code something Qt related on PyCharm I get this issue: Some skeletons failed to generate: 19 modules failed in 1 interpreter. Details... Failed modules Python 3.4.2 PyQt4.QAxContainer PyQt4.Qsci PyQt4.QtCore PyQt4.QtDeclarative PyQt4.QtDesigner PyQt4.QtGui PyQt4.QtHelp PyQt4.QtMultimedia PyQt4.QtNetwork PyQt4.QtOpenGL PyQt4.QtScript PyQt4.QtScriptTools PyQt4.QtSql PyQt4.QtSvg PyQt4.QtTest PyQt4.QtWebKit PyQt4.QtXml PyQt4.QtXmlPatterns PyQt4.phonon Generation of skeletons for the modules above will be tried again when the modules are updated or a new version of generator is available. And PyCharm tells me that my 'import PyQt4.ANYTHING_HERE import *' has 'Unresolved references'. --- When I try to install the PyQt4 via the installer, in the default location (C:/Python34) I get an even 'worse' error, whenever PyCharm try to update the skeletons or something like that (that is, whenever I open a file there...), I get tons and tons of the same error, 'Error while accessing memory at address XXXX', and 'python.exe' stops working. -------------- next part -------------- An HTML attachment was scrubbed... URL: From satishmlmlml at gmail.com Tue Oct 28 17:41:42 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Tue, 28 Oct 2014 14:41:42 -0700 (PDT) Subject: % symbol in python Message-ID:
key rowhtml = '
%s\n" what does % mean in first line of code and what does %%(%s)s mean in second line of code kindly explain From breamoreboy at yahoo.co.uk Tue Oct 28 18:17:11 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 28 Oct 2014 22:17:11 +0000 Subject: % symbol in python In-Reply-To: References: Message-ID: On 28/10/2014 21:41, satishmlmlml at gmail.com wrote: >
key > rowhtml = '
%s\n" > > what does % mean in first line of code and > what does %%(%s)s mean in second line of code > > kindly explain > Please refer to https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rpdooling at gmail.com Tue Oct 28 18:21:30 2014 From: rpdooling at gmail.com (Rick Dooling) Date: Tue, 28 Oct 2014 15:21:30 -0700 (PDT) Subject: checking whether a string is text or binary Message-ID: I'm an English major who hacks scripts together to do things as needed. I used this code from the Python Cookbook for years. https://www.safaribooksonline.com/library/view/python-cookbook-2nd/0596007973/ch01s12.html Especially when I need to convert old WPD files to markdown, some of which don't even have file extensions, so the code helps determine what kind of file it is I am reading in conversion scripts. I tried to convert the code using 2to3 and it broke. The error I get when using Python 3 is on this line: _null_trans = string.maketrans("", "") and the error reads AttributeError: 'module' object has no attribute 'maketrans' Any help? I barely understand the whole unicode business, but any guidance in updating the code would be much appreciated. THANKS Rick From drsalists at gmail.com Tue Oct 28 18:30:15 2014 From: drsalists at gmail.com (Dan Stromberg) Date: Tue, 28 Oct 2014 15:30:15 -0700 Subject: checking whether a string is text or binary In-Reply-To: References: Message-ID: On Tue, Oct 28, 2014 at 3:21 PM, Rick Dooling wrote: > I tried to convert the code using 2to3 and it broke. > > The error I get when using Python 3 is on this line: > > _null_trans = string.maketrans("", "") > > and the error reads > > AttributeError: 'module' object has no attribute 'maketrans' > > Any help? I barely understand the whole unicode business, but any guidance in updating the code would be much appreciated. Top hit on "python3 maketrans" in Google: http://stackoverflow.com/questions/3031045/how-come-string-maketrans-does-not-work-in-python-3-1 From richarddooling at gmail.com Tue Oct 28 19:03:54 2014 From: richarddooling at gmail.com (richarddooling at gmail.com) Date: Tue, 28 Oct 2014 16:03:54 -0700 (PDT) Subject: checking whether a string is text or binary In-Reply-To: References: Message-ID: <3e6d0ee5-057b-47a7-ad4e-c97b39f10d17@googlegroups.com> On Tuesday, October 28, 2014 5:30:31 PM UTC-5, Dan Stromberg wrote: > On Tue, Oct 28, 2014 at 3:21 PM, Rick Dooling wrote: > > I tried to convert the code using 2to3 and it broke. > > > > The error I get when using Python 3 is on this line: > > > > _null_trans = string.maketrans("", "") > > > > and the error reads > > > > AttributeError: 'module' object has no attribute 'maketrans' > > > > Any help? I barely understand the whole unicode business, but any guidance in updating the code would be much appreciated. > > Top hit on "python3 maketrans" in Google: > > http://stackoverflow.com/questions/3031045/how-come-string-maketrans-does-not-work-in-python-3-1 THANK YOU I read that twice before without being able to figure what I needed to change, but third time is a charm. Rick From cs at zip.com.au Tue Oct 28 20:53:46 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 29 Oct 2014 11:53:46 +1100 Subject: Anyone know the solution In-Reply-To: References: Message-ID: <20141029005346.GA48374@cskk.homeip.net> On 28Oct2014 09:07, ngangsia akumbo wrote: >This is a sample code on how to read data from a file > >files1 {} > >result = open("file1.txt") >for line in result: > file1 = line>split() >files1.append(file1) >result.close() >file1.sort() >file1.reverse() > >print('THE FILE INFO') > >print(file1(0) >print(file1(1) Do you have a specific question to accompany this? The code above is syntactly invalid, so it will not run. The line: files1 {} is invalid, but looks like it is intended to initialise files1 as a dictionary. However, the rest of the program seems to use it as though it were a list. The line: file1 = line>split() should probably be written: file1 = line.split() With ">" it is legal (as it performs a comparison) but will fail because there's no bare "split()" function, and anyway is probably not as intended. Your final print statements need an extra closing parenthesis each. Cheers, Cameron Simpson I fit in my suit, my suit fits in my suitcase, hence i fit in my suitcase. - Cees Keyer From anton.schattenfeld at gmail.com Tue Oct 28 21:28:44 2014 From: anton.schattenfeld at gmail.com (Anton) Date: Tue, 28 Oct 2014 18:28:44 -0700 (PDT) Subject: Anyone know the solution In-Reply-To: References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> Message-ID: <9b5151e5-9a8c-449c-9164-98bc908b887d@googlegroups.com> On Monday, October 27, 2014 5:33:17 PM UTC-7, alex23 wrote: > On 28/10/2014 1:10 AM, em.. at gmail.com wrote: > > Write a program that reads the contents of the two files into two separate lists. The user should be able to enter a boy's name, a girl's name or both, and the application will display messages indicating whether the names were among the most popular. > > This is actually a trick question. This is a classic unsolvable problem > in computer science, known as the Dual Baskets problem. It is > NP-complete, meaning that there is no easy solution. It requires > brute-forcing and can take an indefinite period of time to complete, if > at all. > > The correct answer is "Not possible". Can you elaborate why it is an NP-complete problem or maybe a link to description of problem you are referring to? Thanks. From cs at zip.com.au Tue Oct 28 21:22:54 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 29 Oct 2014 12:22:54 +1100 Subject: www.python.org In-Reply-To: <089e013cc44c7e9d8e050677b59c@google.com> References: <089e013cc44c7e9d8e050677b59c@google.com> Message-ID: <20141029012254.GA88666@cskk.homeip.net> Hi Pythonistas, On behalf of all Australians, I would like to apologise for this ill advised SEO spam. Embarrassed, Cameron Simpson On 28Oct2014 08:48, Eileen | Cellsix Pty Ltd wrote: >Hi, > >I recently browsed through your business website and wanted to highlight some >key points for consideration. > >I am sure it will complement your-S.E.O. work to help your website attract >only quality visitors and make it scale high on the search .engine results >page (SERP) gradually. > >Would you be interested in receiving the details? > >Best regards, >Eileen >Online-Strategist > >CELLsIX >MEDIA PTY LTD. > > > >Headquarters: Office 7003 X2 Tower, Cluster X, Melbourne Vic. 3000 Australia >Other Branches: Sydney | Perth | Brisbane | Adelaide | Hobart > >Disclaimer: This e-mail is private and confidential. If you are not the >intended recipient, please advise us by return e-mail immediately, and delete >the e-mail and any attachments without using or disclosing the contents in >any way. The views expressed in this e-mail are those of the author, and do >not represent those of this company unless this is clearly indicated. You >should scan this e-mail and any attachments for viruses. This company accepts >no liability for any direct or indirect damage or loss resulting from the use >of any attachments to this e-mail. All quotes received from Cellsix Media by >email are informal and not binding until a formal quote is agreed upon by >both the parties. > > >-- >https://mail.python.org/mailman/listinfo/python-list From davea at davea.name Tue Oct 28 21:57:23 2014 From: davea at davea.name (Dave Angel) Date: Tue, 28 Oct 2014 21:57:23 -0400 (EDT) Subject: % symbol in python References: Message-ID: satishmlmlml at gmail.com Wrote in message: >
key > rowhtml = '
%s\n" > > what does % mean in first line of code and > what does %%(%s)s mean in second line of code > > kindly explain > Please post Python code, and we can try to comment on it. Those extra
thingies are really killing my mental syntax checker. Also, always specify the python version. -- DaveA From wuwei23 at gmail.com Tue Oct 28 22:03:21 2014 From: wuwei23 at gmail.com (alex23) Date: Wed, 29 Oct 2014 12:03:21 +1000 Subject: Anyone know the solution In-Reply-To: <9b5151e5-9a8c-449c-9164-98bc908b887d@googlegroups.com> References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> <9b5151e5-9a8c-449c-9164-98bc908b887d@googlegroups.com> Message-ID: On 29/10/2014 11:28 AM, Anton wrote: > Can you elaborate why it is an NP-complete problem or maybe a link to description of problem you are referring to? While not the exact problem, it's tangentially related to: http://kenlevine.blogspot.com.au/2011/03/reducing-humor-to-equation.html From davea at davea.name Tue Oct 28 22:11:26 2014 From: davea at davea.name (Dave Angel) Date: Tue, 28 Oct 2014 22:11:26 -0400 (EDT) Subject: Anyone know the solution References: <20141029005346.GA48374@cskk.homeip.net> Message-ID: Cameron Simpson Wrote in message: > On 28Oct2014 09:07, ngangsia akumbo wrote: >>This is a sample code on how to read data from a file >> >>files1 {} >> >>result = open("file1.txt") >>for line in result: >> file1 = line>split() >>files1.append(file1) >>result.close() >>file1.sort() >>file1.reverse() >> >>print('THE FILE INFO') >> >>print(file1(0) >>print(file1(1) > > Do you have a specific question to accompany this? > > The code above is syntactly invalid, so it will not run. > > .... > > Your final print statements need an extra closing parenthesis each. > > Other comments - The line that appends probably wants to be in the loop, and is not. Is there a reason you're subsequently processing only the last line? -- DaveA From cs at zip.com.au Tue Oct 28 22:14:54 2014 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 29 Oct 2014 13:14:54 +1100 Subject: Regex substitution trouble In-Reply-To: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> References: <8c1c1b7f-d121-4f3d-adf9-8262ddd8f102@googlegroups.com> Message-ID: <20141029021454.GA80296@cskk.homeip.net> On 28Oct2014 04:02, massi_srb at msn.com wrote: >I'm not really sure if this is the right place to ask about regular >expressions, but since I'm usin python I thought I could give a try :-) >Here is the problem, I'm trying to write a regex in order to substitute all the occurences in the form $"somechars" with another string. This is what I wrote: > >newstring = re.sub(ur"""(?u)(\$\"[\s\w]+\")""", subst, oldstring) > >This works pretty well, but it has a problem, I would need it also to handle the case in which the internal string contains the double quotes, but only if preceeded by a backslash, that is something like $"somechars_with\\"doublequotes". >Can anyone help me to correct it? People seem to be making this harder than it should be. I'd just be fixing up your definition of what's inside the quotes. There seem to be 3 kinds of things: - not a double quote or backslash - a backslash followed by a double quote - a backslash followed by not a double quote Kind 3 is a policy call - take the following character or not? I would go with treating it like kind 2 myself. So you have: 1 [^\\"] 2 \\" 3 \\[^"] and fold 2 and 3 into: 2+3 \\. So your regexp inner becomes: ([^\\"]|\\.)* and the whole thing becomes: \$"(([^\\"]|\\.)*)" and as a raw string: ur'\$"(([^\\"]|\\.)*)"' choosing single quotes to be more readable given the double quotes in the regexp. Cheers, Cameron Simpson -- cat: /Users/cameron/rc/mail/signature.: No such file or directory Language... has created the word "loneliness" to express the pain of being alone. And it has created the word "solitude" to express the glory of being alone. - Paul Johannes Tillich From denismfmcmahon at gmail.com Tue Oct 28 22:17:27 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Wed, 29 Oct 2014 02:17:27 +0000 (UTC) Subject: A bug? References: Message-ID: On Tue, 28 Oct 2014 01:29:28 +0000, Joshua Landau wrote: > On 28 October 2014 00:36, Denis McMahon > wrote: >> >> d = [[list(range(1,13))[i*3+j] for j in range(3)] for i in range(4)] > > A quick note. Ranges (even 2.7's xrange) are all indexable. The cast to > a list isn't needed. Until you apply Chris' slicing trick, and then: >>> [list(range(1,13))[i*3:i*3+3] for i in range(4)] [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] >>> [range(1,13)[i*3:i*3+3] for i in range(4)] [range(1, 4), range(4, 7), range(7, 10), range(10, 13)] >>> Depends how important it is that you get a list and not a range object ;) (Thinking back to a recent discussion where someone was taking str(range (x)) and not getting the expected results) -- Denis McMahon, denismfmcmahon at gmail.com From denismfmcmahon at gmail.com Tue Oct 28 22:18:19 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Wed, 29 Oct 2014 02:18:19 +0000 (UTC) Subject: memory, PE files, etc... References: <49c92881-e8bf-4e80-9e4d-8b88c0d12133@googlegroups.com> Message-ID: On Mon, 27 Oct 2014 10:16:43 -0700, kiuhnm03 wrote: > I'd like to write one or more scripts that analyze processes in memory > on Windows 7. I used to do these things in C++ by using native Win32 API > calls. > How should I proceed in python? Any pointers? This seems to be a very common request. Does anyone know why? -- Denis McMahon, denismfmcmahon at gmail.com From rosuav at gmail.com Tue Oct 28 22:25:41 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 29 Oct 2014 13:25:41 +1100 Subject: memory, PE files, etc... In-Reply-To: References: <49c92881-e8bf-4e80-9e4d-8b88c0d12133@googlegroups.com> Message-ID: On Wed, Oct 29, 2014 at 1:18 PM, Denis McMahon wrote: > On Mon, 27 Oct 2014 10:16:43 -0700, kiuhnm03 wrote: > >> I'd like to write one or more scripts that analyze processes in memory >> on Windows 7. I used to do these things in C++ by using native Win32 API >> calls. >> How should I proceed in python? Any pointers? > > This seems to be a very common request. Does anyone know why? I hadn't noticed it as hugely common, but in any case... I'd say it's because ctypes and pywin32 are (rightly) obscure, so people don't know they can basically do the same thing in Python as in C++. That's what python-list is for, I think. ChrisA From rustompmody at gmail.com Tue Oct 28 23:22:13 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 28 Oct 2014 20:22:13 -0700 (PDT) Subject: What for -- for? (was A bug?) In-Reply-To: References: Message-ID: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> On Wednesday, October 29, 2014 7:47:47 AM UTC+5:30, Denis McMahon wrote: > On Tue, 28 Oct 2014 01:29:28 +0000, Joshua Landau wrote: > > > On 28 October 2014 00:36, Denis McMahon wrote: > >> > >> d = [[list(range(1,13))[i*3+j] for j in range(3)] for i in range(4)] > > > > A quick note. Ranges (even 2.7's xrange) are all indexable. The cast to > > a list isn't needed. > > Until you apply Chris' slicing trick, and then: > > >>> [list(range(1,13))[i*3:i*3+3] for i in range(4)] > [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]] > >>> [range(1,13)[i*3:i*3+3] for i in range(4)] > [range(1, 4), range(4, 7), range(7, 10), range(10, 13)] > >>> > > Depends how important it is that you get a list and not a range object ;) Heh! Strange that you say this in this context! Yesterday I was trying to introduce python to some senior computer scientists. Tried showing a comprehension-based dir-walker vs a for-loop based one: def dw(p): if isfile(p): return [p] else: return [p] + [c for f in listdir(p) for c in dw(p+'/'+f)] def dw(p): if isfile(p): return [p] else: ls = [p] for f in listdir(p): ls = ls+[f] for c in dw(p+'/'+f): ls = ls+[c] return ls Comment to me : "Well this is neat and compact, but it does not add anything fundamental (over usual index based for-loops)" I tried to say that 'for' over general sequences is quite different and significantly more powerful than C/Pascal for over indexes + explicit indexing. In particular the fact that in python-3: >>> range(1,10) range(1, 10) and not like python2's >>> range(1,10) [1, 2, 3, 4, 5, 6, 7, 8, 9] seemed to convincingly show that python's range is just 'notional' like Pascal's subrange types and not an actual sequence. That >>> range(10)+range(10) works in python 2 but not 3 does not help my case at all! I'd be interested in thoughts on this -- is a range a 'real' or a 'notional' sequence? Related point: "A range is a sequence" How to prove this introspectively? ie if I do: >>> type([]).__mro__ (, ) >>> type(range(10)).__mro__ (, ) >>> How to see that list and range are both sequences? Or more generally how to to introspectively discover (ie not by reading docs!!) the abstract base classes -- eg sequence, iterable etc -- for an arbitrary object? From satishmlmlml at gmail.com Tue Oct 28 23:51:12 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Tue, 28 Oct 2014 20:51:12 -0700 (PDT) Subject: % symbol in python In-Reply-To: References: Message-ID: <9a7bada3-6a2c-49c1-9806-cbf690a350b8@googlegroups.com> import cgi, shelve, sys, os shelvename = 'class-shelve' fieldnames = ('name', 'age', 'job', 'pay') form = cgi.FieldStorage() print('Content-type: text/html') sys.path.insert(0, os.getcwd()) replyhtml = """ People Input Form
key $ROWS$

""" rowhtml = '
%s\n' rowshtml = '' for fieldname in fieldnames: rowshtml += (rowhtml % ((fieldname, ) * 3)) replyhtml = replyhtml.replace('$ROWS$', rowshtml) def htmlize(adict): new = adict.copy() for field in fieldnames: value = new[field] new[field] = cgi.escape(repr(value)) return new def fetchRecord(db, form): try: key = form['key'].value record = db[key] fields = record.__dict__ fields['key'] = key except: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing or invalid key!' return fields def updateRecord(db, form): if not 'key' in form: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing key input!' else: key = form['key'].value if key in db: record = db[key] else: from person import Person record = Person(name='?', age='?') for field in fieldnames: setattr(record, field, eval(form[field].value)) db[key] = record fields = record.__dict__ fields['key'] = key return fields db = shelve.open(shelvename) action = form['action'].value if 'action' in form else None if action == 'Fetch': fields = fetchRecord(db, form) elif action == 'Update': fields = updateRecord(db, form) else: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing or invalid action!' db.close() print(replyhtml % htmlize(fields)) From rosuav at gmail.com Wed Oct 29 00:02:07 2014 From: rosuav at gmail.com (Chris Angelico) Date: Wed, 29 Oct 2014 15:02:07 +1100 Subject: % symbol in python In-Reply-To: <9a7bada3-6a2c-49c1-9806-cbf690a350b8@googlegroups.com> References: <9a7bada3-6a2c-49c1-9806-cbf690a350b8@googlegroups.com> Message-ID: On Wed, Oct 29, 2014 at 2:51 PM, wrote: > def fetchRecord(db, form): > try: > key = form['key'].value When you paste Python code into an email, it's absolutely crucial that you maintain formatting. The indentation is significant. Can you paste it again, please? ChrisA From zachary.ware+pylist at gmail.com Wed Oct 29 00:16:32 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Tue, 28 Oct 2014 23:16:32 -0500 Subject: What for -- for? (was A bug?) In-Reply-To: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> Message-ID: On Tue, Oct 28, 2014 at 10:22 PM, Rustom Mody wrote: > How to see that list and range are both sequences? > Or more generally how to to introspectively discover (ie not by reading docs!!) > the abstract base classes -- eg sequence, iterable etc -- for an arbitrary > object? # Python 2/3 compatible. Combine with pprint for nice interactive output try: from collections import abc except ImportError: import collections as abc def get_abc_map(cls): return {n: issubclass(cls, getattr(abc, n)) for n in dir(abc) if n[0].isupper()} -- Zach From zachary.ware+pylist at gmail.com Wed Oct 29 00:23:06 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Tue, 28 Oct 2014 23:23:06 -0500 Subject: What for -- for? (was A bug?) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> Message-ID: On Tue, Oct 28, 2014 at 11:16 PM, Zachary Ware wrote: > def get_abc_map(cls): > return {n: issubclass(cls, getattr(abc, n)) for n in dir(abc) if > n[0].isupper()} Of course, Gmail decided to wrap my long line for me. In case it's not obvious, that should be a single line. -- Zach From rustompmody at gmail.com Wed Oct 29 00:40:16 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 28 Oct 2014 21:40:16 -0700 (PDT) Subject: What for -- for? (was A bug?) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> Message-ID: <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> On Wednesday, October 29, 2014 9:53:46 AM UTC+5:30, Zachary Ware wrote: > On Tue, Oct 28, 2014 at 11:16 PM, Zachary Ware wrote: > > def get_abc_map(cls): > > return {n: issubclass(cls, getattr(abc, n)) for n in dir(abc) if > > n[0].isupper()} > > Of course, Gmail decided to wrap my long line for me. In case it's > not obvious, that should be a single line. Thanks Wrapping -- no problem. But the isupper looks like black-magic :-) And removing the ' ... if n[0].isupper()' breaks the code From satishmlmlml at gmail.com Wed Oct 29 00:41:29 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Tue, 28 Oct 2014 21:41:29 -0700 (PDT) Subject: % symbol in python In-Reply-To: References: <9a7bada3-6a2c-49c1-9806-cbf690a350b8@googlegroups.com> Message-ID: <77e77ae3-315e-4c3e-aedf-f501c8a217a7@googlegroups.com> import cgi, shelve, sys, os shelvename = 'class-shelve' fieldnames = ('name', 'age', 'job', 'pay') form = cgi.FieldStorage() print('Content-type: text/html') sys.path.insert(0, os.getcwd()) replyhtml = """ People Input Form
key $ROWS$

""" rowhtml = '
%s\n' rowshtml = '' for fieldname in fieldnames: rowshtml += (rowhtml % ((fieldname, ) * 3)) replyhtml = replyhtml.replace('$ROWS$', rowshtml) def htmlize(adict): new = adict.copy() for field in fieldnames: value = new[field] new[field] = cgi.escape(repr(value)) return new def fetchRecord(db, form): try: key = form['key'].value record = db[key] fields = record.__dict__ fields['key'] = key except: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing or invalid key!' return fields def updateRecord(db, form): if not 'key' in form: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing key input!' else: key = form['key'].value if key in db: record = db[key] else: from person import Person record = Person(name='?', age='?') for field in fieldnames: setattr(record, field, eval(form[field].value)) db[key] = record fields = record.__dict__ fields['key'] = key return fields db = shelve.open(shelvename) action = form['action'].value if 'action' in form else None if action == 'Fetch': fields = fetchRecord(db, form) elif action == 'Update': fields = updateRecord(db, form) else: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing or invalid action!' db.close() print(replyhtml % htmlize(fields)) kindly let me know what is $ROWS$ along with % symbol's meaning From zachary.ware+pylist at gmail.com Wed Oct 29 00:59:13 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Tue, 28 Oct 2014 23:59:13 -0500 Subject: What for -- for? (was A bug?) In-Reply-To: <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> Message-ID: On Tue, Oct 28, 2014 at 11:40 PM, Rustom Mody wrote: > On Wednesday, October 29, 2014 9:53:46 AM UTC+5:30, Zachary Ware wrote: >> On Tue, Oct 28, 2014 at 11:16 PM, Zachary Ware wrote: >> > def get_abc_map(cls): >> > return {n: issubclass(cls, getattr(abc, n)) for n in dir(abc) if >> > n[0].isupper()} >> >> Of course, Gmail decided to wrap my long line for me. In case it's >> not obvious, that should be a single line. > > Thanks > > Wrapping -- no problem. > But the isupper looks like black-magic :-) > > And removing the ' ... if n[0].isupper()' > breaks the code It's a terrible hack for 2/3 compatibility; in 3 I'd do "if not n.startswith('__')" since the Python 3 collections.abc module only contains ABCs (and the standard dunder names). Python 2 has all the ABCs mixed into the toplevel collections namespace with some other non-ABCs, but it happens that all the ABCs are capitalized, while the non-ABCs are not. The ABCs are imported into collections from _abcoll, but _abcoll also some uncapitalized non-ABCs as well. For somewhat greyer magic, do 'from abc import ABCMeta' and filter the collections<.abc> namespace with isinstance(obj, ABCMeta). I just used the above because it's short and sweet and keeps the name handy :) -- Zach From alan at scooby-doo.csail.mit.edu Wed Oct 29 01:06:50 2014 From: alan at scooby-doo.csail.mit.edu (Alan Bawden) Date: Wed, 29 Oct 2014 01:06:50 -0400 Subject: .write() behavior References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> <87bnoxv91p.fsf@elektro.pacujo.net> <87tx2otv9s.fsf@elektro.pacujo.net> Message-ID: Marko Rauhamaa writes: > Marko Rauhamaa : > Actually, that's mistaken as well. The sys.std* handles and pipes > returned by subprocess are accessed using file.write() and thus may > return partial writes. I find this very surprising. In Python 2, where file.write() seems to always return None, are you telling me that a call to file.write() might silently return after only writing _some_ of my output? Without raising an exception or returning any other indication of failure? How am I supposed to defend myself against that? You might be right, because nothing in the Python 2 documentation I can find _explicitly_ says that file.write() is guaranteed to write everything I told it to, but that seems like a sufficiently surprising fact that I would expect the documentation to emphasize the danger. In Python 3 the situation is more puzzling: The documentation for open() explains that the type of object returned depends on the mode argument, and several possible candidates for the class of the file object returned are mentioned. Some of those classes document a .write() method that may indeed perform a partial write and return a count of how far it got. Other classes don't say that they might do partial writes, but neither do they say that they don't do partial writes. It seems possible that the _intent_ is that text mode opens return a file object that guarantees to always do a full write. But maybe not. OK, so maybe the situation is that in Python 2 file.write() is guaranteed to never do a partial write and that in Python 3 there are no such guarantees. That seems like a big change to watch out for when migrating my code from 2 to 3. But I can't seem to find any warnings about that in the Python 3 documentation. Just to be clear here, are you saying that in Python 3, I have to start using a utility like: def guaranteed_write(file, data): while data: n = file.write(data) if n < len(data): data = data[n:] else: return for any file object returned by open()? Or maybe just for file objects opened in "binary mode"? Am I missing something? There seem to be some primitive IO facilities in Python 3 that make a distinction between blocking and non-blocking mode, but that distinction doesn't seem to be available when I just call open(). Maybe there is some design document for Python 3 IO that I should read that would explain the rationale for all this? -- Alan Bawden From greg.ewing at canterbury.ac.nz Wed Oct 29 01:13:00 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Wed, 29 Oct 2014 18:13:00 +1300 Subject: Anyone know the solution In-Reply-To: <9b5151e5-9a8c-449c-9164-98bc908b887d@googlegroups.com> References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> <9b5151e5-9a8c-449c-9164-98bc908b887d@googlegroups.com> Message-ID: > On Monday, October 27, 2014 5:33:17 PM UTC-7, alex23 wrote: > >>It is NP-complete, meaning that there is no easy solution. >> >>The correct answer is "Not possible". No, that's not the correct answer. Being NP-complete doesn't mean something is impossible, or even hard to do. All it means is that nobody knows of a cleverer solution than just trying all possibilities. That's only a difficulty if the problem is large enough; often it won't be. -- Greg From rustompmody at gmail.com Wed Oct 29 01:15:13 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 28 Oct 2014 22:15:13 -0700 (PDT) Subject: What for -- for? (was A bug?) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> Message-ID: On Wednesday, October 29, 2014 10:29:48 AM UTC+5:30, Zachary Ware wrote: > On Tue, Oct 28, 2014 at 11:40 PM, Rustom Mody wrote: > > On Wednesday, October 29, 2014 9:53:46 AM UTC+5:30, Zachary Ware wrote: > >> On Tue, Oct 28, 2014 at 11:16 PM, Zachary Ware wrote: > >> > def get_abc_map(cls): > >> > return {n: issubclass(cls, getattr(abc, n)) for n in dir(abc) if > >> > n[0].isupper()} > >> > >> Of course, Gmail decided to wrap my long line for me. In case it's > >> not obvious, that should be a single line. > > > > Thanks > > > > Wrapping -- no problem. > > But the isupper looks like black-magic :-) > > > > And removing the ' ... if n[0].isupper()' > > breaks the code > > It's a terrible hack for 2/3 compatibility; in 3 I'd do "if not > n.startswith('__')" since the Python 3 collections.abc module only > contains ABCs (and the standard dunder names). Python 2 has all the > ABCs mixed into the toplevel collections namespace with some other > non-ABCs, but it happens that all the ABCs are capitalized, while the > non-ABCs are not. The ABCs are imported into collections from > _abcoll, but _abcoll also some uncapitalized non-ABCs as well. > > For somewhat greyer magic, do 'from abc import ABCMeta' and filter the > collections<.abc> namespace with isinstance(obj, ABCMeta). I just > used the above because it's short and sweet and keeps the name handy > :) Ha! Thanks Maybe nicer to filter out the false's with a filter-false thus?? def ff(d): return [n for n in d if d[n]] From ben+python at benfinney.id.au Wed Oct 29 01:27:28 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 29 Oct 2014 16:27:28 +1100 Subject: What for -- for? (was A bug?) References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> Message-ID: <85a94f1m4f.fsf@benfinney.id.au> Zachary Ware writes: > Of course, Gmail decided to wrap my long line for me. In case it's not > obvious, that should be a single line. Right, GMail is a poor choice for composing messages. You might get better results installing a proper mail client, and communicating via IMAP. -- \ ?Pinky, are you pondering what I'm pondering?? ?Wuh, I think | `\ so, Brain, but how will we get three pink flamingos into one | _o__) pair of Capri pants?? ?_Pinky and The Brain_ | Ben Finney From wuwei23 at gmail.com Wed Oct 29 01:25:45 2014 From: wuwei23 at gmail.com (alex23) Date: Wed, 29 Oct 2014 15:25:45 +1000 Subject: % symbol in python In-Reply-To: <77e77ae3-315e-4c3e-aedf-f501c8a217a7@googlegroups.com> References: <9a7bada3-6a2c-49c1-9806-cbf690a350b8@googlegroups.com> <77e77ae3-315e-4c3e-aedf-f501c8a217a7@googlegroups.com> Message-ID: On 29/10/2014 2:41 PM, satishmlmlml at gmail.com wrote: > kindly let me know what is $ROWS$ along with % symbol's meaning It's a token, a static value added to the template to indicate where additional data will be added. So $ROW$ in this section: > >
key > $ROWS$ >
Will be replaced by whatever rowshtml contains at this point: > replyhtml = replyhtml.replace('$ROWS$', rowshtml) Of note: the template section above has opening tags for
and but no closing ones. It's not valid html. Also I don't think this is doing what you think it is: > rowhtml = '
%s\n' > rowshtml = '' > for fieldname in fieldnames: > rowshtml += (rowhtml % ((fieldname, ) * 3)) > replyhtml = replyhtml.replace('$ROWS$', rowshtml) After the first fieldname ('name' in this case), the token $ROWS$ will be replaced by the string : '
name\n'. On the second iteration of the loop, when fieldname is 'age', rowshtml will equal: '
name\n
age\n' ...but nothing will happen with it as $ROWS$ has already been replaced during the first time through the loop. Either the `replyhtml = ...` line is mis-indented or the code is terribly broken. Unless this is for homework, I highly recommend just using one of the many templating libraries that exist for Python, such as Jinja2. From zachary.ware+pylist at gmail.com Wed Oct 29 01:39:31 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Wed, 29 Oct 2014 00:39:31 -0500 Subject: What for -- for? (was A bug?) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> Message-ID: On Wed, Oct 29, 2014 at 12:15 AM, Rustom Mody wrote: > Maybe nicer to filter out the false's with a filter-false thus?? > > def ff(d): return [n for n in d if d[n]] Sure. Or, combining things: try: from collections import abc except ImportError: import collections as abc from abc import ABCMeta abcs = [o for o in vars(abc).values() if isinstance(o, ABCMeta)] def get_abcs(cls): return [abc for abc in abcs if issubclass(cls, abc)] def get_abc_names(cls): return [abc.__name__ for abc in get_abcs(cls)] Of course, that's 3 (progressively shorter) loops to get the names of the ABCs of a class compared to 1 (fairly short in the first place) loop for a map of relationships to all available ABCs, but optimizing such a toy as this would just be an exercise in futility :) -- Zach From zachary.ware+pylist at gmail.com Wed Oct 29 01:42:54 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Wed, 29 Oct 2014 00:42:54 -0500 Subject: What for -- for? (was A bug?) In-Reply-To: <85a94f1m4f.fsf@benfinney.id.au> References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <85a94f1m4f.fsf@benfinney.id.au> Message-ID: On Wed, Oct 29, 2014 at 12:27 AM, Ben Finney wrote: > Zachary Ware writes: > >> Of course, Gmail decided to wrap my long line for me. In case it's not >> obvious, that should be a single line. > > Right, GMail is a poor choice for composing messages. You might get > better results installing a proper mail client, and communicating via > IMAP. Noted, but it works fine 99% of the time for me. I'm not really interested in trying to get a proper mail client set up on 5 different devices and 4 different platforms with settings shared between all just to avoid inconvenient line-wrapping (that I can avoid just by sticking to 80 column lines in the first place :). Although if you have a suggestion for that kind of setup, I'm all ears. -- Zach From satishmlmlml at gmail.com Wed Oct 29 01:48:27 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Tue, 28 Oct 2014 22:48:27 -0700 (PDT) Subject: % symbol in python In-Reply-To: References: <9a7bada3-6a2c-49c1-9806-cbf690a350b8@googlegroups.com> <77e77ae3-315e-4c3e-aedf-f501c8a217a7@googlegroups.com> Message-ID: kindly let me know what does %%(%s)% mean From rustompmody at gmail.com Wed Oct 29 01:57:09 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 28 Oct 2014 22:57:09 -0700 (PDT) Subject: What for -- for? (was A bug?) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <85a94f1m4f.fsf@benfinney.id.au> Message-ID: <0397247b-2581-4732-b0a7-9a49ee8f99ed@googlegroups.com> On Wednesday, October 29, 2014 11:14:14 AM UTC+5:30, Zachary Ware wrote: > On Wed, Oct 29, 2014 at 12:27 AM, Ben Finney wrote: > > Zachary Ware writes: > > > >> Of course, Gmail decided to wrap my long line for me. In case it's not > >> obvious, that should be a single line. > > > > Right, GMail is a poor choice for composing messages. You might get > > better results installing a proper mail client, and communicating via > > IMAP. > > Noted, but it works fine 99% of the time for me. I'm not really > interested in trying to get a proper mail client set up on 5 different > devices and 4 different platforms with settings shared between all > just to avoid inconvenient line-wrapping (that I can avoid just by > sticking to 80 column lines in the first place :). I was going to say the same: gmail is fine if you remember to press RET From ben+python at benfinney.id.au Wed Oct 29 02:02:38 2014 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 29 Oct 2014 17:02:38 +1100 Subject: What for -- for? (was A bug?) References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <85a94f1m4f.fsf@benfinney.id.au> Message-ID: <8561f31kht.fsf@benfinney.id.au> Zachary Ware writes: > [?] just to avoid inconvenient line-wrapping (that I can avoid just by > sticking to 80 column lines in the first place :). That is a valid solution. If you have the discipline to stick to it, congratulations :-) -- \ ?If you ever drop your keys into a river of molten lava, let | `\ 'em go, because, man, they're gone.? ?Jack Handey | _o__) | Ben Finney From marko at pacujo.net Wed Oct 29 02:00:06 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 29 Oct 2014 08:00:06 +0200 Subject: .write() behavior References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> <87bnoxv91p.fsf@elektro.pacujo.net> <87tx2otv9s.fsf@elektro.pacujo.net> Message-ID: <8761f376vt.fsf@elektro.pacujo.net> Alan Bawden : > You might be right, because nothing in the Python 2 documentation I > can find _explicitly_ says that file.write() is guaranteed to write > everything I told it to, but that seems like a sufficiently surprising > fact that I would expect the documentation to emphasize the danger. One can guess that Python2's write tries to push everything into file in a loop. > In Python 3 the situation is more puzzling: The documentation for > open() explains that the type of object returned depends on the mode > argument, and several possible candidates for the class of the file > object returned are mentioned. Some of those classes document a > .write() method that may indeed perform a partial write and return a > count of how far it got. Other classes don't say that they might do > partial writes, but neither do they say that they don't do partial > writes. It seems possible that the _intent_ is that text mode opens > return a file object that guarantees to always do a full write. But > maybe not. Hard to know based on the documentation alone. Let me mention a related problem I ran into a couple of weeks ago. Linux's standard C library (glibc) implements fread(3) differently in RHEL 5 and RHEL 6/7. In RHEL 5, it blocks in a loop until it has read in the desired number of records. In RHEL 6 and 7, it appears to block until it can return at least one whole record. > Am I missing something? There seem to be some primitive IO facilities > in Python 3 that make a distinction between blocking and non-blocking > mode, but that distinction doesn't seem to be available when I just > call open(). I don't think you can do nonblocking I/O with the file.* methods. At least you shouldn't try. The solution is to use os.read(), os.write(), os.pipe(), os.fork() et al. Their semantics is crystal clear. The same dichotomy is there in C. Do you use stdio facilities or system calls? Depends on the type of application you are writing. Marko From satishmlmlml at gmail.com Wed Oct 29 02:02:14 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Tue, 28 Oct 2014 23:02:14 -0700 (PDT) Subject: %%(%s)s mean in python Message-ID: <76c6409c-5289-4cf2-b80a-6349325356c6@googlegroups.com> def fetchRecord(db, form): try: key = form['key'].value record = db[key] fields = record.__dict__ fields['key'] = key except: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing or invalid key!' return fields def updateRecord(db, form): if not 'key' in form: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing key input!' else: key = form['key'].value if key in db: record = db[key] else: from person import Person record = Person(name='?', age='?') for field in fieldnames: setattr(record, field, eval(form[field].value)) db[key] = record fields = record.__dict__ fields['key'] = key return fields db = shelve.open(shelvename) action = form['action'].value if 'action' in form else None if action == 'Fetch': fields = fetchRecord(db, form) elif action == 'Update': fields = updateRecord(db, form) else: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing or invalid action!' db.close() print(replyhtml % htmlize(fields)) What does %%(%s)s mean in Python? From rustompmody at gmail.com Wed Oct 29 02:11:36 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 28 Oct 2014 23:11:36 -0700 (PDT) Subject: What for -- for? (was A bug?) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> Message-ID: <525eb5e7-c221-4336-8c9a-aafb4c545f51@googlegroups.com> On Wednesday, October 29, 2014 11:10:06 AM UTC+5:30, Zachary Ware wrote: > On Wed, Oct 29, 2014 at 12:15 AM, Rustom Mody wrote: > > Maybe nicer to filter out the false's with a filter-false thus?? > > > > def ff(d): return [n for n in d if d[n]] > > Sure. Or, combining things: > > try: > from collections import abc > except ImportError: > import collections as abc > from abc import ABCMeta > > abcs = [o for o in vars(abc).values() if isinstance(o, ABCMeta)] > > def get_abcs(cls): > return [abc for abc in abcs if issubclass(cls, abc)] > > def get_abc_names(cls): > return [abc.__name__ for abc in get_abcs(cls)] > > > > Of course, that's 3 (progressively shorter) loops to get the names of > the ABCs of a class compared to 1 (fairly short in the first place) > loop for a map of relationships to all available ABCs, but optimizing > such a toy as this would just be an exercise in futility :) Not so. The charm of introspection is that the introspection itself can be introspected. For that to be convincing there needs to be a good combo of clarity and succinctness. In particular why not reduce the two functions to one? def get_abc_names(cls): return [abc.__name__ for abc in abcs if issubclass(cls,abc)] From satishmlmlml at gmail.com Wed Oct 29 02:12:36 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Tue, 28 Oct 2014 23:12:36 -0700 (PDT) Subject: %%(%s)s mean in python In-Reply-To: <76c6409c-5289-4cf2-b80a-6349325356c6@googlegroups.com> References: <76c6409c-5289-4cf2-b80a-6349325356c6@googlegroups.com> Message-ID: <362b93be-cb5e-4874-98f8-c27927e66166@googlegroups.com> also what does rowshtml += (rowhtml % ((fieldname,) * 3)) expand to? From zachary.ware+pylist at gmail.com Wed Oct 29 02:18:52 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Wed, 29 Oct 2014 01:18:52 -0500 Subject: What for -- for? (was A bug?) In-Reply-To: <525eb5e7-c221-4336-8c9a-aafb4c545f51@googlegroups.com> References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> <525eb5e7-c221-4336-8c9a-aafb4c545f51@googlegroups.com> Message-ID: On Wed, Oct 29, 2014 at 1:11 AM, Rustom Mody wrote: > On Wednesday, October 29, 2014 11:10:06 AM UTC+5:30, Zachary Ware wrote: >> Of course, that's 3 (progressively shorter) loops to get the names of >> the ABCs of a class compared to 1 (fairly short in the first place) >> loop for a map of relationships to all available ABCs, but optimizing >> such a toy as this would just be an exercise in futility :) > > Not so. > > The charm of introspection is that the introspection > itself can be introspected. > For that to be convincing there needs to be a good combo > of clarity and succinctness. In particular why not reduce > the two functions to one? > > def get_abc_names(cls): > return [abc.__name__ for abc in abcs if issubclass(cls,abc)] Well, it depends on what you actually want, the spec has been a bit fuzzy ;) -- Zach From satishmlmlml at gmail.com Wed Oct 29 02:15:41 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Tue, 28 Oct 2014 23:15:41 -0700 (PDT) Subject: What does %%(%s)s mean/expand to in Python? What does rowshtml += (rowhtml % ((fieldname, ) * 3)) expand to? Kindly explain. Message-ID: def fetchRecord(db, form): try: key = form['key'].value record = db[key] fields = record.__dict__ fields['key'] = key except: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing or invalid key!' return fields def updateRecord(db, form): if not 'key' in form: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing key input!' else: key = form['key'].value if key in db: record = db[key] else: from person import Person record = Person(name='?', age='?') for field in fieldnames: setattr(record, field, eval(form[field].value)) db[key] = record fields = record.__dict__ fields['key'] = key return fields db = shelve.open(shelvename) action = form['action'].value if 'action' in form else None if action == 'Fetch': fields = fetchRecord(db, form) elif action == 'Update': fields = updateRecord(db, form) else: fields = dict.fromkeys(fieldnames, '?') fields['key'] = 'Missing or invalid action!' db.close() print(replyhtml % htmlize(fields)) What does %%(%s)s mean in Python? also what does rowshtml += (rowhtml % ((fieldname,) * 3)) expand to? From __peter__ at web.de Wed Oct 29 03:42:12 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 29 Oct 2014 08:42:12 +0100 Subject: What does %%(%s)s mean/expand to in Python? What does rowshtml += (rowhtml % ((fieldname, ) * 3)) expand to? Kindly explain. References: Message-ID: satishmlmlml at gmail.com wrote: > What does %%(%s)s mean in Python? According to https://docs.python.org/2/library/stdtypes.html#string-formatting in an expression like "%%(%s)s" % ("foo",) '%%' expands to '%' and '%s' expands to 'foo' so the whole thing gives >>> "%%(%s)s" % ("foo",) '%(foo)s' To this you can then apply another formatting operation that takes a dict as its right operand to look up 'foo': >>> "%(foo)s" % {"foo": "bar"} 'bar' What you have with "%%(%s)s" is then a template for a template. > also > what does > rowshtml += (rowhtml % ((fieldname,) * 3)) expand to? (fieldname,) is a 1-tuple, so (fieldname,) *3 gives a 3-tuple (fieldname, fieldname, fieldname): >>> fieldname = "foo" >>> (fieldname,) * 3 ('foo', 'foo', 'foo') rowhhtml % (fieldname, fieldname, fieldname) is again string interpolation. Assuming rowhtml contains "<%s>%s<%s>" may you get >>> fieldname = "foo" >>> rowhtml = "<%s>%s" >>> rowhtml % ((fieldname,)*3) 'foo' From auriocus at gmx.de Wed Oct 29 04:13:29 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Wed, 29 Oct 2014 09:13:29 +0100 Subject: What does %%(%s)s mean/expand to in Python? What does rowshtml += (rowhtml % ((fieldname, ) * 3)) expand to? Kindly explain. In-Reply-To: References: Message-ID: Am 29.10.14 07:15, schrieb satishmlmlml at gmail.com: > What does %%(%s)s mean in Python? Instead of posting all those questions here, you can simply try it in an interactive python interpreter: Apfelkiste:VecTcl chris$ python Python 2.7.2 (default, Oct 11 2012, 20:14:37) [GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> test='%%(%s)s' >>> test % 'foo' '%(foo)s' >>> > also > what does > rowshtml += (rowhtml % ((fieldname,) * 3)) expand to? > >>> fieldname='foo' >>> (fieldname,)*3 ('foo', 'foo', 'foo') >>> test='first %s second %s third %s' >>> test % ((fieldname,)*3) 'first foo second foo third foo' >>> Christian From breamoreboy at yahoo.co.uk Wed Oct 29 04:40:44 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 29 Oct 2014 08:40:44 +0000 Subject: % symbol in python In-Reply-To: References: <9a7bada3-6a2c-49c1-9806-cbf690a350b8@googlegroups.com> <77e77ae3-315e-4c3e-aedf-f501c8a217a7@googlegroups.com> Message-ID: On 29/10/2014 05:48, satishmlmlml at gmail.com wrote: > kindly let me know > what does > %%(%s)% mean > What did you not understand from the link I posted ten hours ago? -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From nomail at invalid.com Wed Oct 29 04:56:47 2014 From: nomail at invalid.com (ast) Date: Wed, 29 Oct 2014 09:56:47 +0100 Subject: Meaning of * in the function arguments list Message-ID: <5450ac05$0$21640$426a74cc@news.free.fr> Hi Consider the following to_bytes method from integer class: int.to_bytes(length, byteorder, *, signed=False) What doest the '*' in the arguments list means ? From __peter__ at web.de Wed Oct 29 05:13:12 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 29 Oct 2014 10:13:12 +0100 Subject: Meaning of * in the function arguments list References: <5450ac05$0$21640$426a74cc@news.free.fr> Message-ID: ast wrote: > Consider the following to_bytes method from integer class: > > int.to_bytes(length, byteorder, *, signed=False) > > What doest the '*' in the arguments list means ? A bare * indicates that the arguments that follow it are keyword-only: >>> def f(a, b=2, *, c=3): ... print("a = {}, b = {}, c = {}".format(a, b, c)) ... >>> f(10) a = 10, b = 2, c = 3 >>> f(10, 20) a = 10, b = 20, c = 3 >>> f(10, 20, 30) Traceback (most recent call last): File "", line 1, in TypeError: f() takes from 1 to 2 positional arguments but 3 were given >>> f(10, 20, c=30) a = 10, b = 20, c = 30 From mail at timgolden.me.uk Wed Oct 29 05:29:39 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 29 Oct 2014 09:29:39 +0000 Subject: memory, PE files, etc... In-Reply-To: References: <49c92881-e8bf-4e80-9e4d-8b88c0d12133@googlegroups.com> Message-ID: <5450B383.8010003@timgolden.me.uk> On 29/10/2014 02:18, Denis McMahon wrote: > On Mon, 27 Oct 2014 10:16:43 -0700, kiuhnm03 wrote: > >> I'd like to write one or more scripts that analyze processes in memory >> on Windows 7. I used to do these things in C++ by using native Win32 API >> calls. >> How should I proceed in python? Any pointers? > > This seems to be a very common request. Does anyone know why? > I certainly wouldn't have called it common, assuming you're referring to the specific request of analyzing processes in memory. I admit we do see on and off the more general request of "How do I do in Python on Windows this thing I can do in C/C++?". TJG From nomail at invalid.com Wed Oct 29 05:37:51 2014 From: nomail at invalid.com (ast) Date: Wed, 29 Oct 2014 10:37:51 +0100 Subject: Meaning of * in the function arguments list In-Reply-To: References: <5450ac05$0$21640$426a74cc@news.free.fr> Message-ID: <5450b574$0$2908$426a74cc@news.free.fr> "Peter Otten" <__peter__ at web.de> a ?crit dans le message de news:mailman.15291.1414574006.18130.python-list at python.org... > > A bare * indicates that the arguments that follow it are keyword-only: > ok, thx From dieffedue at gmx.com Wed Oct 29 06:17:06 2014 From: dieffedue at gmx.com (Dieffe Due) Date: Wed, 29 Oct 2014 03:17:06 -0700 (PDT) Subject: BASTARD STINKY CRIMINALS: DANIEL HEGGLIN EX MORGAN STANLEY + ARRESTED 3 TIMES PAOLO BARRAI (BLOG "MERDATO" LIBERO)! MKG LOTS OF NAZI INSIDER TRADING, DEALING, MARKETS ABUSES! THIEVES, RACIST, BRIBED, WASHING MAFIA'S & PEDOPHILE SILVIO BERLUSCONI'S EURO! Message-ID: BASTARD STINKY CRIMINALS: DANIEL HEGGLIN EX MORGAN STANLEY + ARRESTED 3 TIMES PAOLO BARRAI (BLOG "MERDATO" LIBERO)! MKG LOTS OF NAZI INSIDER TRADING, DEALING, MARKETS ABUSES! THIEVES, RACIST, BRIBED, WASHING MAFIA'S & PEDOPHILE SILVIO BERLUSCONI'S EURO! 1 I READ THIS FOLLOWING TEXT TELLING ABSOLUTE TRUTHS!!! HI, I'M ALFREDO PIACENTINI EX BANQUE SYZ GENEVE AND I CERTAINLY KNOW EVERYTHING BOUT ... "THE EXTREMELY DIRTY PART OF THE WORLD OF FINANCE AND BANKING".. SO... I NOW FEEL A DEEP DEEP, DEEP PASSION TO LET THE WHOLE WORLD KNOW BOUT ALL THIS! BASTARD DREADFUL CRIMINAL DANIEL HEGGLIN EX MORGAN STANLEY SHOULD NOT TERRORIZE GOOGLE AS DEPRAVED SEX MANIAC MAX MOSLEY WANTS TO DO TOO! HE'S REALLY A PAEDERAST, A NAZIMAFIOSO TERRORIST, A PRINCIPAL OF MURDERS, A BRIBED WORM, A STINKY MARKET ABUSER! THIS TEXT THAT HERE WILL FOLLOWS IS FANTASTIC AND TELLS US "UNTOUCHABLES" TRUTHFULNESSES ( "UNTOUCHABLES" FOR NAZIMAFIOSI PIG AND PIIG LIKE DANIEL HEGGLIN EX MORGAN STANLEY, NOT FOR TRULY DEMOCRATIC AND HONEST VALUES, SINCE ALWAYS, MINE))!!! SO I'LL PASS THE MEDIATIC LINE ( AND NOT COCAINE LINE, THAT BASTARD BRUTAL CRIMINAL DANIEL HEGGLIN EX MORGAN STANLEY KNOWS REAL WELL), NOW, TO MASSIMO, WHO IN THIS SCRIPT COMING, IS REALLY THE MAXIMUM OF HONESTY AND SUPER EXTRA DUE!!! Hello. I'm an ex colleague of the extremely stinky criminal Daniel "Danny" Hegglin ex Morgan Stanley and today i really would like "to empty the bag". My name is Massimo, i'm not english native, so, i'm not mother language as you will well see. But i'll write in my best possible english ( in more or less just an hour i have at disposal, to do it). I worked for many years in London, with the killing Hooligans of worldwide stock exchanges: Morgan Stanley (http://www.goodreads.com/book/show/122335.Fiasco). Elbow to elbow with this absolute Jack the Ripper of international finance who is this really stinky shameless criminal bastard Daniel "Danny" Hegglin, now working by an immense Mafia Money Launderer Box called 4th dimension in Hong Kong http://hk.linkedin.com/pub/danny-hegglin/61/277/93 ( this very lousy crook of Daniel "Danny" Hegglin changes his name on the net from Dan to Danny to Daniel, continuously: typical of those who have lot of stinky things to hide, typical move of delinquent, typical move of "dark gray"collars, i wd say, more than white ones)! I saw with my eyes, i repeat, i saw with my eyes, this bastard mega corrupted, better to say, corru-p-ig and also corru-piig, Daniel Hegglin ex Morgan Stanley, getting 100.000, 200.000, 300.000 pounds, cash, put in handbgas. Inside various pubs close to his ex offices in Canary Wharf. " Nazifascist and pro Mafia Morgan Stanley & Co 25 Cabot Square, Canary Wharf London" Cause of immense insider dealings and sometimes even insider tradings he passed to colossal Cosa Nostra's money launderers like Ennio Doris and Massimo Doris from Banca 'Mafiolanum, Camorranum, Ndrangolanum, Nazistanum, Mediolanum' ( not for nothing, bank, "in fact", totally owned by disgusting pedophile and nazimalavitoso dictator Silvio Berlusconi.. and so... bank controlled by Cosa Nostra; choleraic rats Silvio Berlusconi, Marina Berlusconi, Ennio Doris, Massimo Doris and Mafia are same assassin shit since the 60's; since much more than half century; since verminous criminal Berlusconi's father, Luigi Berlusconi, used to wash oceans of killing Cosa Nostra's money in Banca Rasini; 'coincidentally' closed down by American Dea, cause was the bank of the most murderous gangs of half world, and not just sicilian world http://it.wikipedia.org/wiki/Banca_Rasini). 2 Same cash and for same reasons, he used to get from another bastard super delinquent, close to lot of Mafia and NaziRacist international organizations: Paolo Barrai. Having an extremely fascist, mafia money laundering ( via Finter Bank Lugano, via Panama, via Dubai, via Marbella, via bitcoins) and inciting murdering violence blog called Mercato 'Merdato' Libero (bastard criminal excrement Paolo Barrai having already been condemned to big fines or jail, many times; by Consob; by Court in Milan; it looks like, also by Court in Biella; and incredibly by Court in Porto Seguro, Brazil; where they want him now for many years in prison.. for this reason, Hitlerian "jailbird" Paolo Barrai sometimes write of Brazil.. but never put a feet in Brazil anymore). Again and again and again: Same cash and for same reasons, he used to get from another well known corruptor, stinking Al Capone of Italian Bourse: Attilio Ventura, not for nothing, now in 'Mafiaset Hitlerset Mediaset' board http://www.mediaset.it/investor/governance/organi/scheda_9_it.shtml. And used to get other very criminal money from corruptor Francesco Perilli now heading Equita Sim Milan. And from 100s and 100s of other brokers all over Europe. Basically, if "Mussolinian Hooligans" from Morgan Stanley (like another bastard criminal: Michael Chinnick, now laundering lot of mafia assassin cash by Mandarin Capital Hong Kong: https://www.mdncapital.com/about-us) had to buy, for example, lot of Fiat, in Milan, "Jack the Ripper", loathsome worm Daniel Hegglin ex Morgan Stanley used to call "with his private mobile phone another private mobile phone" ( to circumvent the recording of calls, obviously). Belonging to one of noisome maggots above mentioned. And used to say 'Ehy you my big Mafia Banker Ennio Doris.... you know, when you come next week to London.. can you take me that Armani's tie i love so much with code n3124'? Obviously, the translation of this sort of "full of swastika" secret language given in the pub was 'n' = buy, '3124' = Fiat ( "Jack the ripper', extremely rotten felon Daniel Hegglin 4th Dimension Hong Kong used to give to all his corrupting larvas s a list with all the european stocks, with close to any of them, a number: 3124, obviously was for Fiat). Cholaeric escrement Ennio Doris used to answer on the phone "yes Danny, certainly, thank you, actually, thank you". Then started to buy 1.000.000 Fiat for himself ( from his swiss bank account, in very criminal Arner Bank Lugano: pls google "vado riciclo e torno" that means "i go, i wash lot of killing mafia cash and i'll be back", bout mega mafia money launderings done by Ennio Doris and Massimo Doris from Banca Mediolanum http://espresso.repubblica.it/palazzo/2008/05/15/news/vado-riciclo-e-torno-1.8408). Then, "Hooligan"of Finance ( http://en.wikipedia.org/wiki/Frank_Partnoy) Morgan Stanley, used to arrive via "Jack the Ripper" bastard criminal Daniel Hegglin to buy 15.000.000s of Fiat in just one day. And immense gains to be shared 50 50 were made! Is also a bastard racist, part of many worldwide Ku Kluk Klan, repellent nazist Daniel Hegglin. Is also an extremely pervert paederast. He said many times, to me and many people "there is nothing wrong on fucking a boy or a girl who is 12 years old, i do it, i do it, i do it and even often... on the other hand... in the second or third world it happens every day... young female children.. there .. get pregnant at 12.. so i fuck lot of boys and girls, while they are 12... here in London.. or in my native Switzerland.. i pay and i do it". 3 As mentioned, is also a repulsive nazifascist ( he organized the Edward Snowden's hideout in Hong Kong, where he now launders immensely killing Triade Cash out of a very delinquent Box called "4th dimension" http://hk.linkedin.com/pub/danny-hegglin/61/277/931; and used to organize lot and lot of international murders made via various extreme right worldwide public and private intelligence agencies.. google 'daniel hegglin wikileaks' bout it, pls: http://search.wikileaks.org/gifiles/?viewemailid=3541810). In his houses there were ( and still are, cowardly hided, but still are) hundreds of gadgets, books, videos full of love for Adolf Hitler, Benito Mussolini, Augusto Pinochet, Francisco Franco, Alfredo Stroessner. But also very full of passion and love toward many nazifascist mega killing terrorists like The Skinhead International, Afrikaner Weerstandsbeweging, Alan Berg, Combat 18, Nuclei Armati Rivoluzionari, Ordine Nuovo, White Order of Thule. This is the bastard extreme criminal Daniel "Danny Hegglin", not for nothing, fired by Morgan Stanley, fired by TT International, fired by Puricore and many other working places. And if Google will put the head down to him, will be the end of internet, will begin an era of bastard killing nazism all over the world, "ops, what a coincidence", what very fascist Vladimir Putin, Morgan Stanley, Jp Morgan ( who used to finance who killed 6 millions people: Adolf Hitler and Benito Mussolini... never forget, please), as well as Afrikaner Weerstandsbeweging, Alan Berg, Combat 18, Nuclei Armati Rivoluzionari, Order of Flemish Militants, Ordine Nuovo, White Order of Thule exactly want! Massimo. For many years Morgan Stanley London. What i wrote is what i saw and with my own eyes. For many many many years! ModerNazifascist part of Cia, on order of ModerNazifascist and Pro Mafia: James Gorman and Eric Grossman from Morgan Stanley New York, will kill me now??? Better to die as a martyr, meant as a real man ( not certainly meant as other terrorists, like the islamic ones, mean). Who call things with the exact their name! So that the good may have more chances to win the evil. Better to die as a martyr, meant as a real man, than being falsely alive as a passive, amorphous, scared man made diarrea. Massimo a death man walking, now, BUT A REAL (death) MAN (walking)!! From anton.schattenfeld at gmail.com Wed Oct 29 06:42:22 2014 From: anton.schattenfeld at gmail.com (Anton) Date: Wed, 29 Oct 2014 03:42:22 -0700 (PDT) Subject: Python Style Question Message-ID: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> Let's say I have an incoming list of values *l*. Every element of *l* can be one of the following options: 1) an integer value 2) a string in form of '', e.g. '7' 3) a string with a json serialization of an integer value, e.g. '"7"' 4) something else that should be ignored I need to transform this list into another list with values from options 1)-3) coerced to int. The code below should do this. Variant 1 === values = [] for c in l: # Case 1) or 2) try: c_int = int(c) except ValueError: pass else: values.add(c_int) continue # Case 3) try: c_int = int(json.loads(c)) except ValueError: pass else: values.add(c_int) continue === Is this code ugly? Does it follow EAFP? Am I missing something in language best practice? Or maybe below is more preferable way with a nested try...except clause? Variant 2 === values = [] for c in l: # Case 1) or 2) try: c_int = int(c) except ValueError: # Case 3) try: c_int = int(json.loads(c)) except ValueError: pass else: values.add(c_int) continue else: values.add(c_int) continue === Thanks, Anton. From ned at nedbatchelder.com Wed Oct 29 07:38:54 2014 From: ned at nedbatchelder.com (Ned Batchelder) Date: Wed, 29 Oct 2014 07:38:54 -0400 Subject: %%(%s)s mean in python In-Reply-To: <76c6409c-5289-4cf2-b80a-6349325356c6@googlegroups.com> References: <76c6409c-5289-4cf2-b80a-6349325356c6@googlegroups.com> Message-ID: On 10/29/14 2:02 AM, satishmlmlml at gmail.com wrote: > def fetchRecord(db, form): > try: ... 34 lines deleted ... > db.close() > print(replyhtml % htmlize(fields)) Why did you paste all this code, it doesn't have the thing you are asking about. > > What does %%(%s)s mean in Python? > It depends entirely on context. You'll need to find a *small* example of what you are asking about so we can help. -- Ned Batchelder, http://nedbatchelder.com From martin.kemp at ingg.com Wed Oct 29 07:25:57 2014 From: martin.kemp at ingg.com (Martin Kemp) Date: Wed, 29 Oct 2014 11:25:57 +0000 Subject: Python Style Question References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 29/10/2014 10:45, Anton wrote: > Let's say I have an incoming list of values *l*. Every element of > *l* can be one of the following options: 1) an integer value 2) a > string in form of '', e.g. '7' 3) a string with a json > serialization of an integer value, e.g. '"7"' 4) something else > that should be ignored > > I need to transform this list into another list with values from > options 1)-3) coerced to int. The code below should do this. > > > Variant 1 === > > values = [] for c in l: # Case 1) or 2) try: c_int = int(c) except > ValueError: pass else: values.add(c_int) continue > > # Case 3) try: c_int = int(json.loads(c)) except ValueError: pass > else: values.add(c_int) continue > > === > > Is this code ugly? Does it follow EAFP? Am I missing something in > language best practice? > > Or maybe below is more preferable way with a nested try...except > clause? > > Variant 2 === values = [] for c in l: # Case 1) or 2) try: c_int = > int(c) except ValueError: # Case 3) try: c_int = > int(json.loads(c)) except ValueError: pass else: values.add(c_int) > continue else: values.add(c_int) continue === > > Thanks, Anton. > > Your first example is perfectly fine and is EAFP Personally, I prefer to avoid nesting when it's not necessary. - -- Martin Kemp (martin.kemp at ingg.com) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2 iQEcBAEBAgAGBQJUUM7zAAoJEJ0Re0UIDzSucugIALn/zY8RdpP8iaMShHoszzqf I0zl0mFHyqhNtwgQ0ZF7VGO+H+U0Dk8rhzTYOmEMzPTKNBGwll3fda9mOnrK9Xvp 9gQjII6DyQIWH7Z3dLcLr2e1j8OMNUSL6UmAYs8urNSIKZLowdV3JI4G/bLyW0KS y5Ko8dI6y5nOJ1P9XCmPTmags43UZfR8DrBUaAbzNcS8FGwmUE2KBkEhLQOvmpJi jmMc7wMOpq0jL+XbA+7pHUqoVZ7w1tUFjuy9I3h45tgPuTFAFB0gX+FpE+oVgO5o spQpVaOPEYN9ceLgHdKSxzdVIhOQLE6H/SYNHlsEW/ZNM6aR9n4yipgkOmtJ0+M= =WzHA -----END PGP SIGNATURE----- From rafaelromcar at gmail.com Wed Oct 29 07:09:30 2014 From: rafaelromcar at gmail.com (Rafael Romero Carmona) Date: Wed, 29 Oct 2014 12:09:30 +0100 Subject: Python Style Question In-Reply-To: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> Message-ID: Hi, first in Python 2.7.6 and Python 3.4.0 list haven't got any add function but they have append. I think you could do better with something like ========== import json l = [1, -1, 0, '1', '-1', '0', json.dumps(-1), json.dumps(1), json.dumps(0), 'x', 'sqjklsqjk__', (1, 2)] values = [] for c in l: try: c_int = int(c) except ValueError: pass except TypeError: pass else: values.append(c_int) continue print(values) ========== The code has been tested in Python 2.7.6 and 3.4 and returns [1, -1, 0, 1, -1, 0, -1, 1, 0] You don't need to do two try because you can process both exceptions in the same way. You don't really need to do json.loads because if you have a json string which is an integer, you could do that directly with int(c) which can take a string and transform in an integer. With ValueError it captures the exception when it tries to transform the characters' strings and with TypeError it captures the exception when it tries to work with the tuples. Have a good day and hope it works for you! 2014-10-29 11:42 GMT+01:00 Anton : > Let's say I have an incoming list of values *l*. Every element of *l* can be one of the following options: > 1) an integer value > 2) a string in form of '', e.g. '7' > 3) a string with a json serialization of an integer value, e.g. '"7"' > 4) something else that should be ignored > > I need to transform this list into another list with values from options 1)-3) coerced to int. The code below should do this. > > > Variant 1 > === > > values = [] > for c in l: > # Case 1) or 2) > try: > c_int = int(c) > except ValueError: > pass > else: > values.add(c_int) > continue > > # Case 3) > try: > c_int = int(json.loads(c)) > except ValueError: > pass > else: > values.add(c_int) > continue > > === > > Is this code ugly? > Does it follow EAFP? > Am I missing something in language best practice? > > Or maybe below is more preferable way with a nested try...except clause? > > Variant 2 > === > values = [] > for c in l: > # Case 1) or 2) > try: > c_int = int(c) > except ValueError: > > # Case 3) > try: > c_int = int(json.loads(c)) > except ValueError: > pass > else: > values.add(c_int) > continue > > else: > values.add(c_int) > continue > === > > Thanks, > Anton. > > > -- > https://mail.python.org/mailman/listinfo/python-list From rafaelromcar at gmail.com Wed Oct 29 07:52:25 2014 From: rafaelromcar at gmail.com (Rafael Romero Carmona) Date: Wed, 29 Oct 2014 12:52:25 +0100 Subject: Python Style Question In-Reply-To: References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> Message-ID: 2014-10-29 12:25 GMT+01:00 Martin Kemp : > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On 29/10/2014 10:45, Anton wrote: >> Let's say I have an incoming list of values *l*. Every element of >> *l* can be one of the following options: 1) an integer value 2) a >> string in form of '', e.g. '7' 3) a string with a json >> serialization of an integer value, e.g. '"7"' 4) something else >> that should be ignored >> >> I need to transform this list into another list with values from >> options 1)-3) coerced to int. The code below should do this. >> >> >> Variant 1 === >> >> values = [] for c in l: # Case 1) or 2) try: c_int = int(c) except >> ValueError: pass else: values.add(c_int) continue >> >> # Case 3) try: c_int = int(json.loads(c)) except ValueError: pass >> else: values.add(c_int) continue >> >> === >> >> Is this code ugly? Does it follow EAFP? Am I missing something in >> language best practice? >> >> Or maybe below is more preferable way with a nested try...except >> clause? >> >> Variant 2 === values = [] for c in l: # Case 1) or 2) try: c_int = >> int(c) except ValueError: # Case 3) try: c_int = >> int(json.loads(c)) except ValueError: pass else: values.add(c_int) >> continue else: values.add(c_int) continue === >> >> Thanks, Anton. >> >> > > Your first example is perfectly fine and is EAFP > Actually it doesn't work because there is no add function and it doesn't catch the TypeError function to ignore other exceptions than ValueError. Doesn't it? I tested in Python 2.7.6 and 3.4. > Personally, I prefer to avoid nesting when it's not necessary. > > - -- > Martin Kemp (martin.kemp at ingg.com) > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v2 > > iQEcBAEBAgAGBQJUUM7zAAoJEJ0Re0UIDzSucugIALn/zY8RdpP8iaMShHoszzqf > I0zl0mFHyqhNtwgQ0ZF7VGO+H+U0Dk8rhzTYOmEMzPTKNBGwll3fda9mOnrK9Xvp > 9gQjII6DyQIWH7Z3dLcLr2e1j8OMNUSL6UmAYs8urNSIKZLowdV3JI4G/bLyW0KS > y5Ko8dI6y5nOJ1P9XCmPTmags43UZfR8DrBUaAbzNcS8FGwmUE2KBkEhLQOvmpJi > jmMc7wMOpq0jL+XbA+7pHUqoVZ7w1tUFjuy9I3h45tgPuTFAFB0gX+FpE+oVgO5o > spQpVaOPEYN9ceLgHdKSxzdVIhOQLE6H/SYNHlsEW/ZNM6aR9n4yipgkOmtJ0+M= > =WzHA > -----END PGP SIGNATURE----- > -- > https://mail.python.org/mailman/listinfo/python-list From gandalf23 at mail.com Wed Oct 29 09:15:51 2014 From: gandalf23 at mail.com (gandalf23 at mail.com) Date: Wed, 29 Oct 2014 06:15:51 -0700 (PDT) Subject: problem with pefile Message-ID: Where is DIRECTORY_ENTRY_LOAD_CONFIG? In the changelog (https://code.google.com/p/pefile/) one can read: "Version: 1.2.10-60 Besides some small bugfixes in this release I've added functionality to parse the LOAD_CONFIG data directory. Now one can access this structure's fields like, for instance, pe.DIRECTORY_ENTRY_LOAD_CONFIG.struct.SecurityCookie or pe.DIRECTORY_ENTRY_LOAD_CONFIG.struct.SEHandlerTable" From martin.kemp at ingg.com Wed Oct 29 08:42:56 2014 From: martin.kemp at ingg.com (Martin Kemp) Date: Wed, 29 Oct 2014 12:42:56 +0000 Subject: Python Style Question References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 29/10/2014 12:01, Rafael Romero Carmona wrote: > 2014-10-29 12:25 GMT+01:00 Martin Kemp : On > 29/10/2014 10:45, Anton wrote: >>>> Let's say I have an incoming list of values *l*. Every >>>> element of *l* can be one of the following options: 1) an >>>> integer value 2) a string in form of '', e.g. '7' >>>> 3) a string with a json serialization of an integer value, >>>> e.g. '"7"' 4) something else that should be ignored >>>> >>>> I need to transform this list into another list with values >>>> from options 1)-3) coerced to int. The code below should do >>>> this. >>>> >>>> >>>> Variant 1 === >>>> >>>> values = [] for c in l: # Case 1) or 2) try: c_int = int(c) >>>> except ValueError: pass else: values.add(c_int) continue >>>> >>>> # Case 3) try: c_int = int(json.loads(c)) except ValueError: >>>> pass else: values.add(c_int) continue >>>> >>>> === >>>> >>>> Is this code ugly? Does it follow EAFP? Am I missing >>>> something in language best practice? >>>> >>>> Or maybe below is more preferable way with a nested >>>> try...except clause? >>>> >>>> Variant 2 === values = [] for c in l: # Case 1) or 2) try: >>>> c_int = int(c) except ValueError: # Case 3) try: c_int = >>>> int(json.loads(c)) except ValueError: pass else: >>>> values.add(c_int) continue else: values.add(c_int) continue >>>> === >>>> >>>> Thanks, Anton. >>>> >>>> > > Your first example is perfectly fine and is EAFP > > >> Actually it doesn't work because there is no add function and it >> doesn't catch the TypeError function to ignore other exceptions >> than ValueError. Doesn't it? I tested in Python 2.7.6 and 3.4. > > Personally, I prefer to avoid nesting when it's not necessary. > >> -- https://mail.python.org/mailman/listinfo/python-list Ah ok, style-wise it was fine. - -- Martin Kemp (martin.kemp at ingg.com) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2 iQEcBAEBAgAGBQJUUOD+AAoJEJ0Re0UIDzSu1KQIAK6aCMOv4VqOjmm/zoQrmzLf UGBCLwtHrnDkbXFAIweTSFiM1uf9TDaRpJqY1IrPbJHI4/EAP0Hu07nyx3V6HgzM /+Wb3DkpjW+JQoVqDSGzE/dTPJcU3/b1/EWWpbu72JHplqz9laEAFt9muWyDPs9u kDgM06mDd50lsi83W3i0H1iGL6YbLtsik+/x4G4mMjdq1o9BvRpUjkIiOx7yJ/BR OYzdudltXGqlXcToufHTU2lUv2C0RoHHNO4kytiLoUekCBdGE+Jy/6gQq/AKQu4G 0RYjCOnKNgugfdmDuHi0julPtTEzc+MdY/CcPob4cyy8RDzfQGklGKHP7f9+SJs= =hjWU -----END PGP SIGNATURE----- From mail at timgolden.me.uk Wed Oct 29 09:39:01 2014 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 29 Oct 2014 13:39:01 +0000 Subject: problem with pefile In-Reply-To: References: Message-ID: <5450EDF5.90606@timgolden.me.uk> On 29/10/2014 13:15, gandalf23 at mail.com wrote: > Where is DIRECTORY_ENTRY_LOAD_CONFIG? In the changelog > (https://code.google.com/p/pefile/) one can read: > > "Version: 1.2.10-60 > > Besides some small bugfixes in this release I've added functionality > to parse the LOAD_CONFIG data directory. Now one can access this > structure's fields like, for instance, > pe.DIRECTORY_ENTRY_LOAD_CONFIG.struct.SecurityCookie or > pe.DIRECTORY_ENTRY_LOAD_CONFIG.struct.SEHandlerTable" > I suggest you engage with the maintainers of that project. It appears to have an issue tracker: https://code.google.com/p/pefile/issues/list TJG From chaselton at gmail.com Wed Oct 29 10:02:29 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Wed, 29 Oct 2014 09:02:29 -0500 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? In-Reply-To: References: Message-ID: On Tue, Oct 28, 2014 at 4:01 PM, Ned Deily wrote: > In article > , > Cyd Haselton wrote: > >> On Tue, Oct 28, 2014 at 3:11 AM, Ned Deily wrote: >> > In article >> > , >> > Cyd Haselton wrote: >> > [...] >> >> I'm building python on an Android device in the KBOX >> >> environment...which simulates a Unix type filesystem. >> >> Python isn't installed; I'm building from sources (2.7.8) with GCC >> >> 4.8.0 and make. >> >> >> >> The problem with the LDFLAGS approach is that some of the libraries >> >> that must be linked (-lc -ldl) do not need the --allow-shlib-undefined >> >> option...it's only the lpython2.7 that does. Any way to do this? >> > >> > Sorry, I have no experience with that environment nor an understanding >> > of why you need to specify --allow-shlib-undefined (it seems to be the >> > default in some versions of ld). You could look at and, if necessary, >> > modify Lib/distutils, the part of the Python standard library that >> > builds extension modules from setup.py. > >> No need to apologize. Also no need to have an understanding of the >> environment; with a few rare exceptions it behaves just like a >> Unix/Linux one. >> >> The reason why I need to specify --allow-shlib-undefined is for the >> python library; it's throwing undefined references to sincos even >> though the symbol is there. Specifying that option is the only fix >> I've found. >> >> As mentioned earlier, i'm not familiar with python or its build >> system; which file in the distutils dir do I need to modify? > > Perhaps I should apologize for not asking earlier what you are really > trying to do before suggesting heading down the path of modifying > Distutils :) So the issue is with an undefined reference to sincos? It > appears that that routine is often supplied in libm. Is that the case > on your platform? Yes it is. > And, if so, the right fix might be to supply it > manually or, better, ensure that Python supplies it as a result of > running ./configure. If the Makefile generated is a result of running ./configure, then Python is indeed finding the library...what it is doing with it after finding it may be something else entirely. I've tried everything from adding the -Wl,--no-allow-shlib-undefined option to adding #include to the complexobject.c code...I still get an undefined reference to sincos. Running grep "sincos" libpython2.7.* turns up the offending symbol (function? declaration?) but re-running "make" after that still throws the same error. The only fix I've found is adding the -Wl,--allow-shlib-undefined before the python library...which I do by hacking the Makefile. That allows the build to continue, which it does until it hits the part where setup.py is run. > Also, what version of Python are you building? 2.7.8. I thought that it would be easier to build it on Android > > -- > Ned Deily, > nad at acm.org > > -- > https://mail.python.org/mailman/listinfo/python-list From kelvan at logic.at Wed Oct 29 10:12:14 2014 From: kelvan at logic.at (Florian Schweikert) Date: Wed, 29 Oct 2014 15:12:14 +0100 Subject: hotel management system In-Reply-To: <3f10c652-9d9d-4353-b24f-939d21978998@googlegroups.com> References: <3f10c652-9d9d-4353-b24f-939d21978998@googlegroups.com> Message-ID: <5450F5BE.4010700@logic.at> On 28/10/14 07:42, ngangsia akumbo wrote: > Please can someone look at my code and may be advice and may be help me with some correction. I have been learning python for some time now. This is my first project i wish to write. A hotel management system. > > > http://pastebin.com/LMHmuTiC Beside posting the code inline, it would be easier if you had split the "employee" part and the part with the classes. I'm not sure what you want to accomplish with this code, but I picked a few parts: > if age >= 18: > pass > > else: > return age_lim() using a function just to print a single line is quite overcomplicated. return the result and handle it on the caller side. why do you use if/else and just pass first path? if age<18: do_something do the same thing. I have to guess what the class part should do. > class Bar: why calling a class Bar if you use it like some drink counter? > total_cost = 0 > count = 0 not sure you want to use class variables here, do you want to count amount of a single type of beer? or everything > def set_name(self, name): > self.name = name > return name don't use setter if there is 0 logic in the function also it would be better to set this things in the constructor otherwise and a setter should not return the name just set > def set_count(self): > counts = Bar.count =+ 1 not really readable code style, counts variable is unneccessary here > # still have to adjust this section > > def set_total_cost(self): #I am having some errors #calling this functions > total = set_price() * set_count() > print "Total cost of drinks: ", total > pass well, it's quite obvious this function crashes, you try to use not defined functions. you have to use self.function_name to access the methods. But worse than this you want to use (useless) setter to get values and print them inside the method instead of returning the value and handle it outside. Also this is not even a setter, it does not set anything beside a local variable. Maybe it would be best you start over again and make one step after another. Build one part of code and ensure it works before starting with more code. And ask specific questions if you stuck somewhere. -- Florian From ianldickinson52 at gmail.com Wed Oct 29 11:17:17 2014 From: ianldickinson52 at gmail.com (Ian Dickinson) Date: Wed, 29 Oct 2014 15:17:17 +0000 Subject: Emulating py2exe for python version 3 and above Message-ID: Can i emulate py2exe for python version 3 and above i also use pygame any suggestions for a basic staring script would be greatly appreciated Thanks Ian -------------- next part -------------- An HTML attachment was scrubbed... URL: From nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de Wed Oct 29 11:12:44 2014 From: nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de (Thomas Rachel) Date: Wed, 29 Oct 2014 16:12:44 +0100 Subject: %%(%s)s mean in python In-Reply-To: <76c6409c-5289-4cf2-b80a-6349325356c6@googlegroups.com> References: <76c6409c-5289-4cf2-b80a-6349325356c6@googlegroups.com> Message-ID: Am 29.10.2014 07:02 schrieb satishmlmlml at gmail.com: > What does %%(%s)s mean in Python? Weird question, as this has nothing to do with the code you just posted. In general, what comes up to my mind, is that it is a format string to build another format string. Example: metafmt = '%%(%s)s' fieldname = 'myfield' fmt = metafmt % fieldname # Now we have a fmt as if it was assigned with '%(myfield)s': # %% -> %, %s -> myfield. d = {fieldname: 'my content'} print fmt % d # this now prints the given field - which is noted in fieldname - # from the given dict d. From invalid at invalid.invalid Wed Oct 29 11:29:13 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 29 Oct 2014 15:29:13 +0000 (UTC) Subject: Send UDP packet to link-local IPv6 address? Message-ID: How do you send a UDP frame to an IPv6 link-local address? Initially, I'm most concerned with Linux. I'm using CPython 2.7.7, but so far all behavior seems to be identical under 3.3.5, and I need to keep my code compatible with both 2.7 and 3.3/3.4. I'm particularly interested in sending to the all-nodes multicast address (ff02::1), but all the experimenting I've done seems to show that multicast and unicast behave the same. With link-local addresses you also need to specify which interface to use. The normal way of doing this on Linux with command-line utilities is append % to the address/hostname (e.g. ping6 ff02::1%net1). That doesn't work: s.sendto(data, ("ff02::1%net1",port)) s.sendto(data, ("fe80::2c0:4eff:fe40:5f%net1",port)) The "%net1" appears to be ignored, and the packet will go out _some_ interface, but I can't figure out how it decides which one (it's not always the same one). The only way I've found to send to link-local IPv6 addresses is to use the extended length destination address tuple of (address, port, flow_info, scope_id) like so: s.sendto(data, ("ff02::1",port,0,scope_id)) s.sendto(data, ("fe80::2c0:4eff:fe40:5f",port,0,scope_id)) Through trial and error, I've determined that the valid scope_id values for my system are 0,2,3,4, and I've found that 4 corresponds to interface "net1". After re-reading the Python 2.7 socket module documentation, I can't find any way to map an interface name to a scope id. So, after browsing around /proc, I found the file /proc/net/if_inet6 which contains: $ cat if_inet6 fe80000000000000922b34fffe5e7edc 03 40 20 80 net0 00000000000000000000000000000001 01 80 10 80 lo fdfedcba987600100000000000000001 04 40 00 80 net1 fe80000000000000021b21fffeb1d1e9 04 40 20 80 net1 fdfedcba987600080000000000000004 03 40 00 80 net0 fe80000000000000922b34fffe5e7ede 02 40 20 80 net2 The first column is obviously the IPv6 address and the last column the interface name. It appears that second column is the scope id, and some further reading has lead me to believe that the fourth column is the scope (global vs. link-local vs. internal). So I've done the following: ip6scopeid = {} for line in open("/proc/net/if_inet6"): addr, id, _, scope, _, ifacename = line.split() ip6scopeid[ifacename] = int(id) This is highly non-portable, but now I can at least send to link-local addresses like this: s.sendto(data, ("ff02::1",port,0,ip6scopeid["net1"])) s.sendto(data, ("fe80::2c0:4eff:fe40:5f",port,0,ip6scopeid["net1"])) So, my program works (but only on Linux). What's the pythonic, portable way to do this? The only other thing I can think of is to make the user specify the IPv6 address of the interface they want to send from, bind a socket to that address, then ask for that socket's address: s.bind(("fdfe:dcba:9876:10::1",65432)) print s.getsockname() The above prints this: ('fdfe:dcba:9876:10::1', 5678, 0, 0) so, it unfortunately appears that getsockname() doesn't return the scope id if you bind to the global address assigned to an interface. Trying to bind to the link-local address fails unless you already know the scope id and pass it to bind: This fails: s.bind(("fe80::21b:21ff:feb1:d1e9",5678)) This works: s.bind(("fe80::21b:21ff:feb1:d1e9",5678,0,4)) But I'm trying to _find_ the scope id, so that isn't helpful. Any suggestions? Ideally, I'd like a solution that works on Windows and BSD as well... -- Grant Edwards grant.b.edwards Yow! Am I SHOPLIFTING? at gmail.com From gandalf23 at mail.com Wed Oct 29 11:34:28 2014 From: gandalf23 at mail.com (gandalf23 at mail.com) Date: Wed, 29 Oct 2014 08:34:28 -0700 (PDT) Subject: problem with pefile In-Reply-To: References: Message-ID: <11bb3aad-9d8b-442a-b5d3-09af6b771737@googlegroups.com> On Wednesday, October 29, 2014 2:39:30 PM UTC+1, Tim Golden wrote: > On 29/10/2014 13:15, gandalf23 wrote: > > Where is DIRECTORY_ENTRY_LOAD_CONFIG? In the changelog > > (https://code.google.com/p/pefile/) one can read: > > > > "Version: 1.2.10-60 > > > > Besides some small bugfixes in this release I've added functionality > > to parse the LOAD_CONFIG data directory. Now one can access this > > structure's fields like, for instance, > > pe.DIRECTORY_ENTRY_LOAD_CONFIG.struct.SecurityCookie or > > pe.DIRECTORY_ENTRY_LOAD_CONFIG.struct.SEHandlerTable" > > > > I suggest you engage with the maintainers of that project. It appears to > have an issue tracker: > > https://code.google.com/p/pefile/issues/list > > TJG I found out what's the problem by reading the source code. The attributes DIRECTORY_ENTRY_* are added dynamically to an instance of the class PE when/if the corresponding directories are found in the PE file. OT: how can I hide my email in these posts? Every time I try to send a post, google warns me that my email is visible and so I edit it out. From gandalf23 at mail.com Wed Oct 29 11:49:14 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Wed, 29 Oct 2014 08:49:14 -0700 (PDT) Subject: problem with pefile In-Reply-To: References: Message-ID: Little test...sorry. From gandalf23 at mail.com Wed Oct 29 11:50:14 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Wed, 29 Oct 2014 08:50:14 -0700 (PDT) Subject: problem with pefile In-Reply-To: <11bb3aad-9d8b-442a-b5d3-09af6b771737@googlegroups.com> References: <11bb3aad-9d8b-442a-b5d3-09af6b771737@googlegroups.com> Message-ID: On Wednesday, October 29, 2014 4:34:42 PM UTC+1, Kiuhnm wrote: > OT: how can I hide my email in these posts? > Every time I try to send a post, google warns me that my email is visible and so I edit it out. Problem solved :) From gandalf23 at mail.com Wed Oct 29 12:17:05 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Wed, 29 Oct 2014 09:17:05 -0700 (PDT) Subject: optional types Message-ID: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> I must say that the lack of static types in Python is a pain in the neck especially when I'm exploring new libraries. Recently, I learned a new language called Dart which have optional typing and I had a lot of fun with it. Basically, you use type annotations as documentation and to give useful information to the IDE or editor. That makes the IDE look *very* smart! I'm using PyCharm and more often than not I want to see the list of methods and attributes of an object, but the editor won't show them to me because it doesn't know the dynamic type of the variable whose value was just returned by a function. That's irritating! Am I the only one who'd like to see optional types introduced in Python? From alain at dpt-info.u-strasbg.fr Wed Oct 29 12:50:30 2014 From: alain at dpt-info.u-strasbg.fr (Alain Ketterlin) Date: Wed, 29 Oct 2014 17:50:30 +0100 Subject: Send UDP packet to link-local IPv6 address? References: Message-ID: <87zjce252h.fsf@dpt-info.u-strasbg.fr> Grant Edwards writes: [...] > With link-local addresses you also need to specify which interface to > use. The normal way of doing this on Linux with command-line utilities > is append % to the address/hostname (e.g. ping6 ff02::1%net1). > > That doesn't work: > > s.sendto(data, ("ff02::1%net1",port)) > s.sendto(data, ("fe80::2c0:4eff:fe40:5f%net1",port)) > > The "%net1" appears to be ignored, and the packet will go out _some_ > interface, but I can't figure out how it decides which one (it's not > always the same one). The only way I've found is to use socket.getaddrinfo(), which does accept "%net1" after the IPv6 address, and returns scope_id (actually a complete sockaddr). I can't access my files now, by I think socket.getaddrinfo("fe80::2c0:4eff:fe40:5f%net1",port,...) should work for you (family, socktype etc should be passed also to avoid searching the results of getaddrinfo()). Hope this helps, -- Alain. From __peter__ at web.de Wed Oct 29 12:51:46 2014 From: __peter__ at web.de (Peter Otten) Date: Wed, 29 Oct 2014 17:51:46 +0100 Subject: optional types References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> Message-ID: Kiuhnm wrote: > I must say that the lack of static types in Python is a pain in the neck > especially when I'm exploring new libraries. Recently, I learned a new > language called Dart which have optional typing and I had a lot of fun > with it. Basically, you use type annotations as documentation and to give > useful information to the IDE or editor. That makes the IDE look *very* > smart! I'm using PyCharm and more often than not I want to see the list of > methods and attributes of an object, but the editor won't show them to me > because it doesn't know the dynamic type of the variable whose value was > just returned by a function. That's irritating! Am I the only one who'd > like to see optional types introduced in Python? Personally I am skeptical, but there is an effort underway: http://www.mypy-lang.org/ https://mail.python.org/pipermail/python-ideas/2014-August/028742.html Nothing that your search engine of choice could not have found you... From gandalf23 at mail.com Wed Oct 29 13:18:35 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Wed, 29 Oct 2014 10:18:35 -0700 (PDT) Subject: optional types In-Reply-To: References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> Message-ID: <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> On Wednesday, October 29, 2014 5:57:13 PM UTC+1, Peter Otten wrote: > Kiuhnm wrote: > > > I must say that the lack of static types in Python is a pain in the neck > > especially when I'm exploring new libraries. Recently, I learned a new > > language called Dart which have optional typing and I had a lot of fun > > with it. Basically, you use type annotations as documentation and to give > > useful information to the IDE or editor. That makes the IDE look *very* > > smart! I'm using PyCharm and more often than not I want to see the list of > > methods and attributes of an object, but the editor won't show them to me > > because it doesn't know the dynamic type of the variable whose value was > > just returned by a function. That's irritating! Am I the only one who'd > > like to see optional types introduced in Python? > > Personally I am skeptical, but there is an effort underway: > > http://www.mypy-lang.org/ > https://mail.python.org/pipermail/python-ideas/2014-August/028742.html > > Nothing that your search engine of choice could not have found you... In fact, I did find it, but that didn't stop me from asking :) You can find something similar for almost any dynamic language out there. If it isn't an official feature of the language, it's useless, IMHO. It seems that PyCharm supports some kind of type annotations: http://www.jetbrains.com/pycharm/webhelp/using-docstrings-to-specify-types.html Unfortunately, again, if almost no one uses them, they're not very useful. From rosuav at gmail.com Wed Oct 29 13:25:00 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 30 Oct 2014 04:25:00 +1100 Subject: optional types In-Reply-To: <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> Message-ID: On Thu, Oct 30, 2014 at 4:18 AM, Kiuhnm wrote: >> Personally I am skeptical, but there is an effort underway: >> >> http://www.mypy-lang.org/ >> https://mail.python.org/pipermail/python-ideas/2014-August/028742.html >> >> Nothing that your search engine of choice could not have found you... > > In fact, I did find it, but that didn't stop me from asking :) > > You can find something similar for almost any dynamic language out there. > If it isn't an official feature of the language, it's useless, IMHO. As you'll see from the python-ideas thread, there's a proposal under-way to *make* this an official feature. However, it's massively open to bikeshedding :) If you feel strongly about this, come join us on python-ideas and weigh in; all input will be warmly received, and that doesn't mean we respond with flames... not usually, anyway! ChrisA From invalid at invalid.invalid Wed Oct 29 13:36:30 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Wed, 29 Oct 2014 17:36:30 +0000 (UTC) Subject: Send UDP packet to link-local IPv6 address? References: <87zjce252h.fsf@dpt-info.u-strasbg.fr> Message-ID: On 2014-10-29, Alain Ketterlin wrote: > Grant Edwards writes: > > [...] >> With link-local addresses you also need to specify which interface to >> use. The normal way of doing this on Linux with command-line utilities >> is append % to the address/hostname (e.g. ping6 ff02::1%net1). >> >> That doesn't work: >> >> s.sendto(data, ("ff02::1%net1",port)) >> s.sendto(data, ("fe80::2c0:4eff:fe40:5f%net1",port)) >> >> The "%net1" appears to be ignored, and the packet will go out _some_ >> interface, but I can't figure out how it decides which one (it's not >> always the same one). > > The only way I've found is to use socket.getaddrinfo(), which does > accept "%net1" after the IPv6 address, and returns scope_id (actually a > complete sockaddr). I can't access my files now, by I think > > socket.getaddrinfo("fe80::2c0:4eff:fe40:5f%net1",port,...) > > should work for you (family, socktype etc should be passed also to avoid > searching the results of getaddrinfo()). Doh!, of course that works. Using getaddrinfo() is how you're always supposed to do things these days. Creating an address tuple by hand is a bad habit left over from too many years spent doing network stuff in the old days before getaddrinfo et al. I looked at the documentation for getaddrinfo(), and I would have sworn I had tried it and couldn't get it to work. But it does. > Hope this helps, Definitely! Thanks! -- Grant Edwards grant.b.edwards Yow! FOOLED you! Absorb at EGO SHATTERING impulse gmail.com rays, polyester poltroon!! From ethan at stoneleaf.us Wed Oct 29 13:46:00 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 29 Oct 2014 10:46:00 -0700 Subject: optional types In-Reply-To: <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> Message-ID: <545127D8.1040408@stoneleaf.us> On 10/29/2014 10:18 AM, Kiuhnm wrote: > On Wednesday, October 29, 2014 5:57:13 PM UTC+1, Peter Otten wrote: >> Kiuhnm wrote: >> >>> I must say that the lack of static types in Python is a pain in the neck >>> especially when I'm exploring new libraries. Recently, I learned a new >>> language called Dart which have optional typing and I had a lot of fun >>> with it. Basically, you use type annotations as documentation and to give >>> useful information to the IDE or editor. That makes the IDE look *very* >>> smart! I'm using PyCharm and more often than not I want to see the list of >>> methods and attributes of an object, but the editor won't show them to me >>> because it doesn't know the dynamic type of the variable whose value was >>> just returned by a function. That's irritating! Am I the only one who'd >>> like to see optional types introduced in Python? >> >> Personally I am skeptical, but there is an effort underway: >> >> http://www.mypy-lang.org/ >> https://mail.python.org/pipermail/python-ideas/2014-August/028742.html >> >> Nothing that your search engine of choice could not have found you... > > In fact, I did find it, but that didn't stop me from asking :) > > You can find something similar for almost any dynamic language out there. > If it isn't an official feature of the language, it's useless, IMHO. > > It seems that PyCharm supports some kind of type annotations: > http://www.jetbrains.com/pycharm/webhelp/using-docstrings-to-specify-types.html > Unfortunately, again, if almost no one uses them, they're not very useful. Even if it becomes official, which seems likely, it will still be optional -- hence, only useful if folks actually use it. ;) -- ~Ethan~ From rosuav at gmail.com Wed Oct 29 14:03:33 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 30 Oct 2014 05:03:33 +1100 Subject: optional types In-Reply-To: <545127D8.1040408@stoneleaf.us> References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> Message-ID: On Thu, Oct 30, 2014 at 4:46 AM, Ethan Furman wrote: > Even if it becomes official, which seems likely, it will still be optional > -- hence, only useful if folks actually use it. ;) Yes, but if it's official, the standard library (large parts of it, at least) will use it, which will make it a lot more useful than it currently is. ChrisA From denismfmcmahon at gmail.com Wed Oct 29 14:03:33 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Wed, 29 Oct 2014 18:03:33 +0000 (UTC) Subject: Anyone know the solution References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> Message-ID: On Mon, 27 Oct 2014 08:10:04 -0700, emmanueloje wrote: > Write a program ... Hey dudester I coded a solution for you, you can get it here: http://www.sined.co.uk/tmp/names.py.txt Make sure you leave all the comments in so your instructor realises how much effort you went in to in researching how to code this. -- Denis McMahon, denismfmcmahon at gmail.com From marko at pacujo.net Wed Oct 29 14:18:59 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 29 Oct 2014 20:18:59 +0200 Subject: optional types References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> Message-ID: <87vbn268oc.fsf@elektro.pacujo.net> Chris Angelico : > Yes, but if it's official, the standard library (large parts of it, at > least) will use it, which will make it a lot more useful than it > currently is. I doubt it. Python should decide if it wants to stay Python or become another Java. I don't really believe in this "be everything for everybody" thing. You'll only become nothing for anybody. Marko From rosuav at gmail.com Wed Oct 29 14:43:39 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 30 Oct 2014 05:43:39 +1100 Subject: optional types In-Reply-To: <87vbn268oc.fsf@elektro.pacujo.net> References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> <87vbn268oc.fsf@elektro.pacujo.net> Message-ID: On Thu, Oct 30, 2014 at 5:18 AM, Marko Rauhamaa wrote: > Chris Angelico : > >> Yes, but if it's official, the standard library (large parts of it, at >> least) will use it, which will make it a lot more useful than it >> currently is. > > I doubt it. Python should decide if it wants to stay Python or become > another Java. I don't really believe in this "be everything for > everybody" thing. You'll only become nothing for anybody. Mebbe. More likely, Python wants to lift ideas from anyone and everyone. List comprehensions came from the functional world, flexible string representation came from Pike or bash (or was independently invented), etc, etc. Python won't turn into Java. The biggest philosophical difference between the languages, as I see it, is Java's rigidity of boundaries versus Python's consenting-adults policy. In Java, you write getters and setters for everything, you lock your class up and make sure people use it ONLY in the ways you've specified, you declare parameters/return values/exceptions so people know exactly what to expect, etc. Python gets out of your way and lets you write a single application as a concerted whole; if you want to "reach in" and fiddle with another class's members, go for it. I'm not saying that either philosophy is *wrong*, of course, but just adding type hints to Python isn't going to change the underlying philosophical model. ChrisA From nick.cash at npcinternational.com Wed Oct 29 12:25:18 2014 From: nick.cash at npcinternational.com (Nick Cash) Date: Wed, 29 Oct 2014 16:25:18 +0000 Subject: optional types References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> Message-ID: <4227ca1255c34366b8b638f47d684d0a@DM2PR06MB542.namprd06.prod.outlook.com> > Am I the only one who'd like to see optional types introduced in Python? Nope! Some dude named "Guido" would like to see them as well: https://mail.python.org/pipermail/python-ideas/2014-August/028742.html From gandalf23 at mail.com Wed Oct 29 15:03:03 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Wed, 29 Oct 2014 12:03:03 -0700 (PDT) Subject: optional types In-Reply-To: <87vbn268oc.fsf@elektro.pacujo.net> References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> <87vbn268oc.fsf@elektro.pacujo.net> Message-ID: <07aadf0c-3e9f-4a17-bcca-3e57dcddf31d@googlegroups.com> On Wednesday, October 29, 2014 7:19:11 PM UTC+1, Marko Rauhamaa wrote: > Chris Angelico : > > > Yes, but if it's official, the standard library (large parts of it, at > > least) will use it, which will make it a lot more useful than it > > currently is. > > I doubt it. Python should decide if it wants to stay Python or become > another Java. I don't really believe in this "be everything for > everybody" thing. You'll only become nothing for anybody. > > > Marko 1) Java is not optionally typed. 2) Having optional types is not "being everything for everybody", it's just being smart. From marko at pacujo.net Wed Oct 29 15:07:36 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 29 Oct 2014 21:07:36 +0200 Subject: optional types References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> <87vbn268oc.fsf@elektro.pacujo.net> <07aadf0c-3e9f-4a17-bcca-3e57dcddf31d@googlegroups.com> Message-ID: <87lhny66fb.fsf@elektro.pacujo.net> Kiuhnm : > 2) Having optional types is not "being everything for everybody", it's > just being smart. We'll see, we'll see... Marko From anton.schattenfeld at gmail.com Wed Oct 29 15:09:00 2014 From: anton.schattenfeld at gmail.com (Anton) Date: Wed, 29 Oct 2014 12:09:00 -0700 (PDT) Subject: Python Style Question In-Reply-To: References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> Message-ID: <8b20c9ae-ebde-41fd-8569-394e1372fb81@googlegroups.com> On Wednesday, October 29, 2014 4:43:33 AM UTC-7, Rafael Romero Carmona wrote: > Hi, first in Python 2.7.6 and Python 3.4.0 list haven't got any add > function but they have append. You are right, in my original code I use set instead of array, so it should be either values = set() or values.append() in the original code. > > I think you could do better with something like > > ========== > import json > l = [1, -1, 0, '1', '-1', '0', json.dumps(-1), json.dumps(1), > json.dumps(0), 'x', 'sqjklsqjk__', (1, 2)] It should also work with cases like [1, json.dumps('-1')], which is case 3), sorry if it was not clear in the initial post. > > values = [] > > for c in l: > try: > c_int = int(c) > except ValueError: > pass > except TypeError: > pass > else: > values.append(c_int) > continue > print(values) > ========== > > The code has been tested in Python 2.7.6 and 3.4 and returns [1, -1, > 0, 1, -1, 0, -1, 1, 0] > > You don't need to do two try because you can process both exceptions > in the same way. You don't really need to do json.loads because if you > have a json string which is an integer, you could do that directly > with int(c) which can take a string and transform in an integer. In case of 3) an element can be a string like '"1"', which will fail int(...), in this case it tries to parse it with json. From gandalf23 at mail.com Wed Oct 29 15:09:11 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Wed, 29 Oct 2014 12:09:11 -0700 (PDT) Subject: optional types In-Reply-To: <07aadf0c-3e9f-4a17-bcca-3e57dcddf31d@googlegroups.com> References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> <87vbn268oc.fsf@elektro.pacujo.net> <07aadf0c-3e9f-4a17-bcca-3e57dcddf31d@googlegroups.com> Message-ID: <4be9d891-711c-45cd-81e4-1da523c18b8a@googlegroups.com> On Wednesday, October 29, 2014 8:03:16 PM UTC+1, Kiuhnm wrote: > On Wednesday, October 29, 2014 7:19:11 PM UTC+1, Marko Rauhamaa wrote: > > Chris Angelico : > > > > > Yes, but if it's official, the standard library (large parts of it, at > > > least) will use it, which will make it a lot more useful than it > > > currently is. > > > > I doubt it. Python should decide if it wants to stay Python or become > > another Java. I don't really believe in this "be everything for > > everybody" thing. You'll only become nothing for anybody. > > > > > > Marko > > 1) Java is not optionally typed. > 2) Having optional types is not "being everything for everybody", it's just being smart. ...where "smart" is referred to IDEs, etc... From breamoreboy at yahoo.co.uk Wed Oct 29 15:22:46 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 29 Oct 2014 19:22:46 +0000 Subject: optional types In-Reply-To: <07aadf0c-3e9f-4a17-bcca-3e57dcddf31d@googlegroups.com> References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> <87vbn268oc.fsf@elektro.pacujo.net> <07aadf0c-3e9f-4a17-bcca-3e57dcddf31d@googlegroups.com> Message-ID: On 29/10/2014 19:03, Kiuhnm wrote: > On Wednesday, October 29, 2014 7:19:11 PM UTC+1, Marko Rauhamaa wrote: >> Chris Angelico : >> >>> Yes, but if it's official, the standard library (large parts of it, at >>> least) will use it, which will make it a lot more useful than it >>> currently is. >> >> I doubt it. Python should decide if it wants to stay Python or become >> another Java. I don't really believe in this "be everything for >> everybody" thing. You'll only become nothing for anybody. >> >> >> Marko > > 1) Java is not optionally typed. > 2) Having optional types is not "being everything for everybody", it's just being smart. > Regarding 2) Python has somehow managed without optional types for over 20 years so it's my belief that they're not the panacea that so many people think they are. Sure if they get implemented and if they improve Python then I'm all for them, but I'm not holding my breath. -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From anton.schattenfeld at gmail.com Wed Oct 29 15:23:26 2014 From: anton.schattenfeld at gmail.com (Anton) Date: Wed, 29 Oct 2014 12:23:26 -0700 (PDT) Subject: Python Style Question In-Reply-To: References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> Message-ID: <9806dae0-a47b-4aa8-aba0-0b2a69d002b2@googlegroups.com> On Wednesday, October 29, 2014 4:59:25 AM UTC-7, Rafael Romero Carmona wrote: > 2014-10-29 12:25 GMT+01:00 Martin Kemp : > Actually it doesn't work because there is no add function and it > doesn't catch the TypeError function to ignore other exceptions than > ValueError. Doesn't it? I tested in Python 2.7.6 and 3.4. Originally I was using set instead of list. So it should have been either values = set() or values.append(), but it is not relevant to the question. Regarding TypeError, I don't catch it on purpose, because I want this type of Exception to bubble up and surface as an error and be logged, because this should never be the case. I expect an element to be either something coercible to int or a string. If for some reason it is an object, then there is something wrong one layer up, so I want it to fail explicitly. From stefan_ml at behnel.de Wed Oct 29 15:31:11 2014 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 29 Oct 2014 20:31:11 +0100 Subject: (-1)**1000 In-Reply-To: References: <54476a77$0$21664$426a74cc@news.free.fr> <544d5499$0$41762$c3e8da3$5d8fb80f@news.astraweb.com> Message-ID: Ned Batchelder schrieb am 26.10.2014 um 21:45: > On 10/26/14 4:07 PM, Tony the Tiger wrote: >> On Wed, 22 Oct 2014 10:27:34 +0200, ast wrote: >> >>> If i am writing (-1)**1000 on a python program, will the interpreter do >>> (-1)*(-1)*...*(-1) or something clever ? >> >> Even vs. odd. It ought to know. I would assume from a set of defined >> rules how math works. > > There is such a thing as an optimization that isn't worthwhile to perform, > simply because it's expected to provide so little benefit. The language > implementors have to trade off the cost of adding the optimization to the > implementation, against the possible benefit people would get from it. > > Benefit in this case would have to include a guess as to how often real > programs would hit the optimization case. ... and also compare it to the number of cases where the optimisation (which may, for example, need to check for an optimisable value or set of values) slows down the generic (unoptimised) code path that is actually taken. Even if the code impact on the implementation is small enough to be acceptable, an optimisation for unlikely cases may provide a net-loss for the "normal" code. So there are several reasons why an "obvious" optimisation may be a bad idea. Stefan From marko at pacujo.net Wed Oct 29 15:44:55 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Wed, 29 Oct 2014 21:44:55 +0200 Subject: optional types References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> <87vbn268oc.fsf@elektro.pacujo.net> <07aadf0c-3e9f-4a17-bcca-3e57dcddf31d@googlegroups.com> Message-ID: <87h9ym64p4.fsf@elektro.pacujo.net> Mark Lawrence : > Regarding 2) Python has somehow managed without optional types for > over 20 years so it's my belief that they're not the panacea that so > many people think they are. Sure if they get implemented and if they > improve Python then I'm all for them, but I'm not holding my breath. I'm afraid of stylistic chaos and optional types turning into de-facto mandatory types as modules interface each other. Marko From gandalf23 at mail.com Wed Oct 29 16:40:22 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Wed, 29 Oct 2014 13:40:22 -0700 (PDT) Subject: optional types In-Reply-To: References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> <87vbn268oc.fsf@elektro.pacujo.net> <07aadf0c-3e9f-4a17-bcca-3e57dcddf31d@googlegroups.com> Message-ID: <823b7ef6-ebc4-4718-b862-d9d16f8c4aa8@googlegroups.com> On Wednesday, October 29, 2014 8:23:30 PM UTC+1, Mark Lawrence wrote: > On 29/10/2014 19:03, Kiuhnm wrote: > > On Wednesday, October 29, 2014 7:19:11 PM UTC+1, Marko Rauhamaa wrote: > >> Chris Angelico : > >> > >>> Yes, but if it's official, the standard library (large parts of it, at > >>> least) will use it, which will make it a lot more useful than it > >>> currently is. > >> > >> I doubt it. Python should decide if it wants to stay Python or become > >> another Java. I don't really believe in this "be everything for > >> everybody" thing. You'll only become nothing for anybody. > >> > >> > >> Marko > > > > 1) Java is not optionally typed. > > 2) Having optional types is not "being everything for everybody", it's just being smart. > > > > Regarding 2) Python has somehow managed without optional types for over > 20 years so it's my belief that they're not the panacea that so many > people think they are. Sure if they get implemented and if they improve > Python then I'm all for them, but I'm not holding my breath. The only thing I know is that I programmed in ASM and C++ for many years and I liked it. Then I moved to C#, Haskell, Scala, and many other languages. Then I learned Python and I liked it. Then I tried Dart (with optional static typing) and liked it very much. Finally, I've come back to Python and I don't like it anymore like I used to. Dart's syntax is not on par with Python's but its type system is so lightweight and non intrusive that it's a joy to work with it and I miss it. From gandalf23 at mail.com Wed Oct 29 16:43:56 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Wed, 29 Oct 2014 13:43:56 -0700 (PDT) Subject: optional types In-Reply-To: <87h9ym64p4.fsf@elektro.pacujo.net> References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> <87vbn268oc.fsf@elektro.pacujo.net> <07aadf0c-3e9f-4a17-bcca-3e57dcddf31d@googlegroups.com> <87h9ym64p4.fsf@elektro.pacujo.net> Message-ID: On Wednesday, October 29, 2014 8:45:08 PM UTC+1, Marko Rauhamaa wrote: > Mark Lawrence : > > > Regarding 2) Python has somehow managed without optional types for > > over 20 years so it's my belief that they're not the panacea that so > > many people think they are. Sure if they get implemented and if they > > improve Python then I'm all for them, but I'm not holding my breath. > > I'm afraid of stylistic chaos and optional types turning into de-facto > mandatory types as modules interface each other. The only problem I see is that Python's type system might become too complex (Scala anyone???) If you start adding covariance, contravariance, F-bounded types, etc..., the type system becomes more of a hindrance, IMHO. But if you keep it simple (like Dart) it shouldn't get in your way. From juan0christian at gmail.com Wed Oct 29 18:45:03 2014 From: juan0christian at gmail.com (Juan Christian) Date: Wed, 29 Oct 2014 20:45:03 -0200 Subject: Python 3.4.2 + PyQt4 + PyCharm 3.4.1 In-Reply-To: References: Message-ID: It only occurs whule using PyCharm I tried it via pure terminal and everything works... =/ On Tue, Oct 28, 2014 at 7:45 PM, Juan Christian wrote: > Python 3.4.2 Windows x64 > PyQt4 4.11.2 Py3.4 Qt4.8.6 (x64) > PyCharm 3.4.1 Pro Edition > > > So, PyCharm works 100% with everything here but PyQt. > > I have this folder structure: > > Disk C: > > PyQt4 > >> Lib/site-packages/PyQt4/(tons of files here) > > > Python34 (normal/default installation) > > --- > > I tried copying the 'PyQt4' folder to my 'Python34/Lib/site-packages' > folder but when I try to code something Qt related on PyCharm I get this > issue: > > Some skeletons failed to generate: 19 modules failed in 1 interpreter. > Details... > > Failed modules > > Python 3.4.2 > PyQt4.QAxContainer > PyQt4.Qsci > PyQt4.QtCore > PyQt4.QtDeclarative > PyQt4.QtDesigner > PyQt4.QtGui > PyQt4.QtHelp > PyQt4.QtMultimedia > PyQt4.QtNetwork > PyQt4.QtOpenGL > PyQt4.QtScript > PyQt4.QtScriptTools > PyQt4.QtSql > PyQt4.QtSvg > PyQt4.QtTest > PyQt4.QtWebKit > PyQt4.QtXml > PyQt4.QtXmlPatterns > PyQt4.phonon > > Generation of skeletons for the modules above will be tried again when the > modules are updated or a new version of generator is available. > > And PyCharm tells me that my 'import PyQt4.ANYTHING_HERE import *' has > 'Unresolved references'. > > --- > > When I try to install the PyQt4 via the installer, in the default location > (C:/Python34) I get an even 'worse' error, whenever PyCharm try to update > the skeletons or something like that (that is, whenever I open a file > there...), I get tons and tons of the same error, 'Error while accessing > memory at address XXXX', and 'python.exe' stops working. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anton.schattenfeld at gmail.com Wed Oct 29 20:09:41 2014 From: anton.schattenfeld at gmail.com (Anton) Date: Wed, 29 Oct 2014 17:09:41 -0700 (PDT) Subject: Anyone know the solution In-Reply-To: References: <43dce2d9-38ef-462c-bb52-897d827e50c5@googlegroups.com> <9b5151e5-9a8c-449c-9164-98bc908b887d@googlegroups.com> Message-ID: <8df8501c-f89b-44a5-8296-b491bf08f44c@googlegroups.com> On Tuesday, October 28, 2014 10:13:14 PM UTC-7, Gregory Ewing wrote: > No, that's not the correct answer. Being NP-complete doesn't > mean something is impossible, or even hard to do. All it > means is that nobody knows of a cleverer solution than > just trying all possibilities. That's only a difficulty if > the problem is large enough; often it won't be. Why do you need to iterate over all possibilities solving this problem anyway? From tjreedy at udel.edu Wed Oct 29 23:58:32 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 29 Oct 2014 23:58:32 -0400 Subject: What for -- for? (was A bug?) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <85a94f1m4f.fsf@benfinney.id.au> Message-ID: On 10/29/2014 1:42 AM, Zachary Ware wrote: > to avoid inconvenient line-wrapping (that I can avoid just by > sticking to 80 column lines in the first place:). Try perhaps 65 for email. def get_abc_map(cls): return {n: issubclass(cls, getattr(abc, n)) for n in dir(abc) if n[0].isupper()} is less than 55 and should not get linewrapped on any sensible sender or reader. -- Terry Jan Reedy From tjreedy at udel.edu Thu Oct 30 00:06:05 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 30 Oct 2014 00:06:05 -0400 Subject: Meaning of * in the function arguments list In-Reply-To: <5450ac05$0$21640$426a74cc@news.free.fr> References: <5450ac05$0$21640$426a74cc@news.free.fr> Message-ID: On 10/29/2014 4:56 AM, ast wrote: > Consider the following to_bytes method from integer class: > int.to_bytes(length, byteorder, *, signed=False) > What doest the '*' in the arguments list means ? If you go to the online doc index page for Symbols, https://docs.python.org/3/genindex-Symbols.html there a 3 entries for the use of * as an operator, in statements (in particular, def for functions), and in function calls. -- Terry Jan Reedy From tjreedy at udel.edu Thu Oct 30 00:16:30 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 30 Oct 2014 00:16:30 -0400 Subject: optional types In-Reply-To: <823b7ef6-ebc4-4718-b862-d9d16f8c4aa8@googlegroups.com> References: <99399d4a-902d-42d9-86c8-7bdcd2a766cc@googlegroups.com> <18fa60be-225e-422d-82de-902c4a0c66da@googlegroups.com> <545127D8.1040408@stoneleaf.us> <87vbn268oc.fsf@elektro.pacujo.net> <07aadf0c-3e9f-4a17-bcca-3e57dcddf31d@googlegroups.com> <823b7ef6-ebc4-4718-b862-d9d16f8c4aa8@googlegroups.com> Message-ID: On 10/29/2014 4:40 PM, Kiuhnm wrote: > The only thing I know is that I programmed in ASM and C++ for many > years and I liked it. Then I moved to C#, Haskell, Scala, and many > other languages. Then I learned Python and I liked it. Then I tried > Dart (with optional static typing) and liked it very much. Finally, > I've come back to Python and I don't like it anymore like I used to. > Dart's syntax is not on par with Python's but its type system is so > lightweight and non intrusive that it's a joy to work with it and I > miss it. Then propose on python-ideas, probably best after posting more here, that Dart be used as a model for Python. But include a summary or example of what it is and why you like it and how you think its system might be adapted to Python. Would it be based on the current annotations, for instance? -- Terry Jan Reedy From cmferras at estudiantes.uci.cu Wed Oct 29 20:03:57 2014 From: cmferras at estudiantes.uci.cu (C@rlos) Date: Wed, 29 Oct 2014 20:03:57 -0400 (CDT) Subject: accents in windows In-Reply-To: <838615157.3476350.1414627277178.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: <1003235191.3477106.1414627437852.JavaMail.zimbra@estudiantes.uci.cu> i cant print any accent(? ? ? ? ?) or ? in console when i use windows OS with python, the console showme an error or extrangers characters in some cases, i need help III Escuela Internacional de Invierno en la UCI del 17 al 28 de febrero del 2014. Ver www.uci.cu -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at simplistix.co.uk Thu Oct 30 04:20:34 2014 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 30 Oct 2014 08:20:34 +0000 Subject: testfixtures 4.1.1 Released! Message-ID: <5451F4D2.9040400@simplistix.co.uk> Hi All, I'm pleased to announce the release of testfixtures 4.1.1. This is a bugfix release that fixes the following: - Fix bug that prevented logger propagation to be controlled by the log_capture decorator. Thanks to John Kristensen for the fix. It looks like I also forgot to send out the 4.1.0 release announcement, which was a bug and feature release containing the following: - Fix compare() bug when dict instances with tuple keys were not equal. - Allow logger propagation to be controlled by LogCapture. - Enabled disabled loggers if a LogCapture is attached to them. Thanks to Daniel Fortunov for the compare() fix. The package is on PyPI and a full list of all the links to docs, issue trackers and the like can be found here: http://www.simplistix.co.uk/software/python/testfixtures Any questions, please do ask on the Testing in Python list or on the Simplistix open source mailing list... cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From rosuav at gmail.com Thu Oct 30 04:42:49 2014 From: rosuav at gmail.com (Chris Angelico) Date: Thu, 30 Oct 2014 19:42:49 +1100 Subject: accents in windows In-Reply-To: <1003235191.3477106.1414627437852.JavaMail.zimbra@estudiantes.uci.cu> References: <838615157.3476350.1414627277178.JavaMail.zimbra@estudiantes.uci.cu> <1003235191.3477106.1414627437852.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On Thu, Oct 30, 2014 at 11:03 AM, C at rlos wrote: > i cant print any accent(? ? ? ? ?) or ? in console when i use windows OS > with python, the console showme an error or extrangers characters in some > cases, i need help What version of Python? What is your code page set to? Windows and Unicode don't play very nicely together. You may find it better to use Idle (which has a GUI for this kind of display), and you will almost certainly find things easier on Linux. ChrisA From steve+comp.lang.python at pearwood.info Thu Oct 30 07:10:06 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Thu, 30 Oct 2014 22:10:06 +1100 Subject: Python Style Question References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> Message-ID: <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> Anton wrote: > Let's say I have an incoming list of values *l*. Every element of *l* can > be one of the following options: > 1) an integer value > 2) a string in form of '', e.g. '7' > 3) a string with a json serialization of an integer value, e.g. '"7"' > 4) something else that should be ignored > > I need to transform this list into another list with values from options > 1)-3) coerced to int. The code below should do this. I don't particularly like either version. I prefer this: def load_int(obj): if isinstance(obj, int): # Case 1), an int, e.g. 7 return obj elif isinstance(obj, str): # Case 2) and 3), a str or JSON serialised int. # E.g. '7' or '"7"'. try: return int(obj) except ValueError: return int(json.loads(obj)) raise TypeError('require int or str, got %s' % type(obj).__name__) load_int() covers the three cases you mention, and raises either ValueError for malformed strings (e.g. 'x') or TypeError for things which aren't ints (e.g. floats, dicts, etc.). Any other exception is probably a bug that needs to be fixed. Then, to cover case 4), ignoring everything else, you have a choice between a procedural form: values = [] for obj in l: try: values.append(load_int(obj)) except (ValueError, TypeError): pass or a functional form: def tolerant_load_int(obj, default=None): try: return load_int(obj) except (ValueError, TypeError): return default values = [n for n in map(tolerant_load_int, l) if n is not None] # alternative to using map values = [n for n in (tolerant_load_int(obj) for obj in l) if n is not None] -- Steven From nomail at invalid.com Thu Oct 30 07:23:08 2014 From: nomail at invalid.com (ast) Date: Thu, 30 Oct 2014 12:23:08 +0100 Subject: Has color "Green" changed from Python 33 to 34 ? Message-ID: <54521fa1$0$2040$426a74cc@news.free.fr> Hi I just updated this morning my Python from a 3.3rc to 3.4 (Windows) and I noticed that the 'Green' color in tkinter GUI is not the same at all. 'Green' in 3.4 is very dark. I had to replace it with 'Lime' to get back a nice 'Green'. From __peter__ at web.de Thu Oct 30 08:20:45 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 30 Oct 2014 13:20:45 +0100 Subject: Has color "Green" changed from Python 33 to 34 ? References: <54521fa1$0$2040$426a74cc@news.free.fr> Message-ID: ast wrote: > I just updated this morning my Python from a 3.3rc to 3.4 > (Windows) and I noticed that the 'Green' color in tkinter > GUI is not the same at all. > > 'Green' in 3.4 is very dark. I had to replace it with 'Lime' to > get back a nice 'Green'. More likely the color is defined by tcl/tk rather than Python, and your Python installations use different versions of tcl. Searching for 'tcl/tk color definitions' finds with the following statement """From Tcl/Tk 8.6 on, Tk uses Web colours instead of X11 ones, where they conflict. """ and according to "green" is indeed one of the affected colors. From python at mrabarnett.plus.com Thu Oct 30 08:21:28 2014 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 30 Oct 2014 12:21:28 +0000 Subject: Python Style Question In-Reply-To: <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <54522D48.7070107@mrabarnett.plus.com> On 2014-10-30 11:10, Steven D'Aprano wrote: > Anton wrote: > >> Let's say I have an incoming list of values *l*. Every element of *l* can >> be one of the following options: >> 1) an integer value >> 2) a string in form of '', e.g. '7' >> 3) a string with a json serialization of an integer value, e.g. '"7"' >> 4) something else that should be ignored >> >> I need to transform this list into another list with values from options >> 1)-3) coerced to int. The code below should do this. > > I don't particularly like either version. I prefer this: > > def load_int(obj): > if isinstance(obj, int): > # Case 1), an int, e.g. 7 > return obj > elif isinstance(obj, str): > # Case 2) and 3), a str or JSON serialised int. > # E.g. '7' or '"7"'. > try: > return int(obj) > except ValueError: > return int(json.loads(obj)) > raise TypeError('require int or str, got %s' % type(obj).__name__) > [snip] How about: int(str(obj).strip('"')) From cmferras at estudiantes.uci.cu Thu Oct 30 08:30:49 2014 From: cmferras at estudiantes.uci.cu (C@rlos) Date: Thu, 30 Oct 2014 08:30:49 -0400 (CDT) Subject: accents in windows In-Reply-To: References: <838615157.3476350.1414627277178.JavaMail.zimbra@estudiantes.uci.cu> <1003235191.3477106.1414627437852.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: <1796463426.3602276.1414672249566.JavaMail.zimbra@estudiantes.uci.cu> thanks U, but the real problem is: i have a path C:\Users\yanet\Desktop\?aa?ee?iii?oo?uu?nn this path is correct, ?aa?ee?iii?oo?uu?nn is the name of a directory but when i try to use os.walk() usin this path, dont work, for os this path dont exist, i try every things but nothing works. some help??? ----- Mensaje original ----- De: "Chris Angelico" CC: python-list at python.org Enviados: Jueves, 30 de Octubre 2014 4:42:49 Asunto: Re: accents in windows On Thu, Oct 30, 2014 at 11:03 AM, C at rlos wrote: > i cant print any accent(? ? ? ? ?) or ? in console when i use windows OS > with python, the console showme an error or extrangers characters in some > cases, i need help What version of Python? What is your code page set to? Windows and Unicode don't play very nicely together. You may find it better to use Idle (which has a GUI for this kind of display), and you will almost certainly find things easier on Linux. ChrisA -- https://mail.python.org/mailman/listinfo/python-list -- Conserva lo que tienes...Olvida lo que te duele...Lucha por lo que quieres... Valora lo que posees...Perdona a los que te hieren y disfruta a los que te aman. Nos pasamos la vida esperando que pase algo... y lo ?nico que pasa es la vida. No entendemos el valor de los momentos, hasta que se han convertido en recuerdos. Por eso... Haz lo que quieras hacer, antes de que se convierta en lo que te "gustar?a" haber hecho.. No hagas de tu vida un borrador, tal vez no tengas tiempo de pasarlo en limpio !! .....C at rlos III Escuela Internacional de Invierno en la UCI del 17 al 28 de febrero del 2014. Ver www.uci.cu From nestorjb at gmail.com Thu Oct 30 08:33:57 2014 From: nestorjb at gmail.com (=?UTF-8?B?TsOpc3RvciBCb3Njw6Fu?=) Date: Thu, 30 Oct 2014 08:03:57 -0430 Subject: When using a decorator exceptions raised reference the decorator not the function Message-ID: Hi I'm using Python 2.7 and I'm creating a class decorator that extract information from exceptions for logging purposes. Everytime an exception is raised from the original function and I extract the origin of the exception with sys.exc_info() I get a reference to the line in the decorator where the function is called, not the line of the original function where the exception was raised. Any ideas? Regards, N?stor -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Thu Oct 30 08:43:34 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 30 Oct 2014 13:43:34 +0100 Subject: accents in windows References: <838615157.3476350.1414627277178.JavaMail.zimbra@estudiantes.uci.cu> <1003235191.3477106.1414627437852.JavaMail.zimbra@estudiantes.uci.cu> <1796463426.3602276.1414672249566.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: C at rlos wrote: > thanks U, but the real problem is: > > i have a path C:\Users\yanet\Desktop\?aa?ee?iii?oo?uu?nn > this path is correct, ?aa?ee?iii?oo?uu?nn is the name of a directory > but when i try to use os.walk() usin this path, dont work, for os this > path dont exist, i try every things but nothing works. > > some help??? "nothing works" is not a good problem description to get help to fix a bug. Can you post a small script that demonstrates the problem? Run the script and post its output including the error message and the traceback. Don't retype the output, use copy-and-paste. From __peter__ at web.de Thu Oct 30 08:45:42 2014 From: __peter__ at web.de (Peter Otten) Date: Thu, 30 Oct 2014 13:45:42 +0100 Subject: When using a decorator exceptions raised reference the decorator not the function References: Message-ID: N?stor Bosc?n wrote: > I'm using Python 2.7 and I'm creating a class decorator that extract > information from exceptions for logging purposes. > > Everytime an exception is raised from the original function and I extract > the origin of the exception with sys.exc_info() I get a reference to the > line in the decorator where the function is called, not the line of the > original function where the exception was raised. > > Any ideas? Please show us the code, preferably as a small self-contained example. Thank you. From jeanmichel at sequans.com Thu Oct 30 09:24:16 2014 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 30 Oct 2014 14:24:16 +0100 (CET) Subject: When using a decorator exceptions raised reference the decorator not the function In-Reply-To: Message-ID: <2039441433.1974698.1414675456279.JavaMail.root@sequans.com> ----- Original Message ----- > From: "Peter Otten" <__peter__ at web.de> > To: python-list at python.org > Sent: Thursday, 30 October, 2014 1:45:42 PM > Subject: Re: When using a decorator exceptions raised reference the decorator not the function > > N?stor Bosc?n wrote: > > > I'm using Python 2.7 and I'm creating a class decorator that > > extract > > information from exceptions for logging purposes. > > > > Everytime an exception is raised from the original function and I > > extract > > the origin of the exception with sys.exc_info() I get a reference > > to the > > line in the decorator where the function is called, not the line of > > the > > original function where the exception was raised. > > > > Any ideas? > > Please show us the code, preferably as a small self-contained > example. Thank > you. +1 show us your decorator. if you did something like: try: except Exception, e: # do something raise e Then replace "raise e" by a bare "raise" JM -- IMPORTANT NOTICE: The contents of this email and any attachments are confidential and may also be privileged. If you are not the intended recipient, please notify the sender immediately and do not disclose the contents to any other person, use it for any purpose, or store or copy the information in any medium. Thank you. From rustompmody at gmail.com Thu Oct 30 13:01:38 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 30 Oct 2014 10:01:38 -0700 (PDT) Subject: Finding way around ABCs (was What for -- for? (was A bug?)) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> <525eb5e7-c221-4336-8c9a-aafb4c545f51@googlegroups.com> Message-ID: On Wednesday, October 29, 2014 11:49:27 AM UTC+5:30, Zachary Ware wrote: > On Wed, Oct 29, 2014 at 1:11 AM, Rustom Mody wrote: > > On Wednesday, October 29, 2014 11:10:06 AM UTC+5:30, Zachary Ware wrote: > >> Of course, that's 3 (progressively shorter) loops to get the names of > >> the ABCs of a class compared to 1 (fairly short in the first place) > >> loop for a map of relationships to all available ABCs, but optimizing > >> such a toy as this would just be an exercise in futility :) > > > > Not so. > > > > The charm of introspection is that the introspection > > itself can be introspected. > > For that to be convincing there needs to be a good combo > > of clarity and succinctness. In particular why not reduce > > the two functions to one? > > > > def get_abc_names(cls): > > return [abc.__name__ for abc in abcs if issubclass(cls,abc)] > > Well, it depends on what you actually want, the spec has been a bit fuzzy ;) Thanks for this much -- its helpful. Regarding ABCs -- is there a central documentation for them: "What exactly is a sequence or iterable or etc protocol?" This information seems to be strewn all over the place but systematically. From ian.g.kelly at gmail.com Thu Oct 30 13:09:40 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 30 Oct 2014 11:09:40 -0600 Subject: Finding way around ABCs (was What for -- for? (was A bug?)) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> <525eb5e7-c221-4336-8c9a-aafb4c545f51@googlegroups.com> Message-ID: On Thu, Oct 30, 2014 at 11:01 AM, Rustom Mody wrote: > On Wednesday, October 29, 2014 11:49:27 AM UTC+5:30, Zachary Ware wrote: >> On Wed, Oct 29, 2014 at 1:11 AM, Rustom Mody wrote: >> > On Wednesday, October 29, 2014 11:10:06 AM UTC+5:30, Zachary Ware wrote: >> >> Of course, that's 3 (progressively shorter) loops to get the names of >> >> the ABCs of a class compared to 1 (fairly short in the first place) >> >> loop for a map of relationships to all available ABCs, but optimizing >> >> such a toy as this would just be an exercise in futility :) >> > >> > Not so. >> > >> > The charm of introspection is that the introspection >> > itself can be introspected. >> > For that to be convincing there needs to be a good combo >> > of clarity and succinctness. In particular why not reduce >> > the two functions to one? >> > >> > def get_abc_names(cls): >> > return [abc.__name__ for abc in abcs if issubclass(cls,abc)] >> >> Well, it depends on what you actually want, the spec has been a bit fuzzy ;) > > Thanks for this much -- its helpful. > Regarding ABCs -- is there a central documentation for them: > > "What exactly is a sequence or iterable or etc protocol?" > > This information seems to be strewn all over the place but systematically. Maybe the glossary? https://docs.python.org/3/glossary.html From ian.g.kelly at gmail.com Thu Oct 30 13:11:22 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 30 Oct 2014 11:11:22 -0600 Subject: Finding way around ABCs (was What for -- for? (was A bug?)) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> <525eb5e7-c221-4336-8c9a-aafb4c545f51@googlegroups.com> Message-ID: On Thu, Oct 30, 2014 at 11:09 AM, Ian Kelly wrote: > On Thu, Oct 30, 2014 at 11:01 AM, Rustom Mody wrote: >> On Wednesday, October 29, 2014 11:49:27 AM UTC+5:30, Zachary Ware wrote: >>> On Wed, Oct 29, 2014 at 1:11 AM, Rustom Mody wrote: >>> > On Wednesday, October 29, 2014 11:10:06 AM UTC+5:30, Zachary Ware wrote: >>> >> Of course, that's 3 (progressively shorter) loops to get the names of >>> >> the ABCs of a class compared to 1 (fairly short in the first place) >>> >> loop for a map of relationships to all available ABCs, but optimizing >>> >> such a toy as this would just be an exercise in futility :) >>> > >>> > Not so. >>> > >>> > The charm of introspection is that the introspection >>> > itself can be introspected. >>> > For that to be convincing there needs to be a good combo >>> > of clarity and succinctness. In particular why not reduce >>> > the two functions to one? >>> > >>> > def get_abc_names(cls): >>> > return [abc.__name__ for abc in abcs if issubclass(cls,abc)] >>> >>> Well, it depends on what you actually want, the spec has been a bit fuzzy ;) >> >> Thanks for this much -- its helpful. >> Regarding ABCs -- is there a central documentation for them: >> >> "What exactly is a sequence or iterable or etc protocol?" >> >> This information seems to be strewn all over the place but systematically. > > Maybe the glossary? Also the documentation for the collections.abc and numbers modules: https://docs.python.org/3/library/collections.abc.html https://docs.python.org/3/library/numbers.html From rustompmody at gmail.com Thu Oct 30 13:16:50 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 30 Oct 2014 10:16:50 -0700 (PDT) Subject: Finding way around ABCs (was What for -- for? (was A bug?)) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> <593c0099-770f-48cd-b7ba-22154b00f130@googlegroups.com> <525eb5e7-c221-4336-8c9a-aafb4c545f51@googlegroups.com> Message-ID: On Thursday, October 30, 2014 10:40:42 PM UTC+5:30, Ian wrote: > On Thu, Oct 30, 2014 at 11:01 AM, Rustom Mody wrote: > > On Wednesday, October 29, 2014 11:49:27 AM UTC+5:30, Zachary Ware wrote: > >> On Wed, Oct 29, 2014 at 1:11 AM, Rustom Mody wrote: > >> > On Wednesday, October 29, 2014 11:10:06 AM UTC+5:30, Zachary Ware wrote: > >> >> Of course, that's 3 (progressively shorter) loops to get the names of > >> >> the ABCs of a class compared to 1 (fairly short in the first place) > >> >> loop for a map of relationships to all available ABCs, but optimizing > >> >> such a toy as this would just be an exercise in futility :) > >> > > >> > Not so. > >> > > >> > The charm of introspection is that the introspection > >> > itself can be introspected. > >> > For that to be convincing there needs to be a good combo > >> > of clarity and succinctness. In particular why not reduce > >> > the two functions to one? > >> > > >> > def get_abc_names(cls): > >> > return [abc.__name__ for abc in abcs if issubclass(cls,abc)] > >> > >> Well, it depends on what you actually want, the spec has been a bit fuzzy ;) > > > > Thanks for this much -- its helpful. > > Regarding ABCs -- is there a central documentation for them: > > > > "What exactly is a sequence or iterable or etc protocol?" > > > > This information seems to be strewn all over the place but systematically. > > Maybe the glossary? > > https://docs.python.org/3/glossary.html Ummm... I was looking for something more reference-ish, ie More prolix for ABCs And not containing random bits of unconnected data like - What is CPython - What is EAFP Maybe there's something in the bowels of the C(Python)-code? From joshua at landau.ws Thu Oct 30 13:21:56 2014 From: joshua at landau.ws (Joshua Landau) Date: Thu, 30 Oct 2014 17:21:56 +0000 Subject: What for -- for? (was A bug?) In-Reply-To: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> Message-ID: On 29 October 2014 03:22, Rustom Mody wrote: > Yesterday I was trying to introduce python to some senior computer scientists. > > Tried showing a comprehension-based dir-walker vs a for-loop based one: > > def dw(p): > if isfile(p): > return [p] > else: > return [p] + [c for f in listdir(p) for c in dw(p+'/'+f)] > ... > > Comment to me : "Well this is neat and compact, but it does not add > anything fundamental (over usual index based for-loops)" > > I tried to say that 'for' over general sequences is quite different > and significantly more powerful than C/Pascal for over indexes + > explicit indexing. If you really want to show the generality of iteration, I suggest you start with iterators: def walk(path): yield path if isdir(path): for name in iterdir(path): for file in walk(path + "/" + name): yield file This is fundementally inexpressable with indexes. It also lends itself to expressing delegation (eg. "yield from walk(path + "/" + name)"). From rustompmody at gmail.com Thu Oct 30 13:41:37 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 30 Oct 2014 10:41:37 -0700 (PDT) Subject: What for -- for? (was A bug?) In-Reply-To: References: <94e3143a-c9ab-433d-8b3d-6ab296de14d9@googlegroups.com> Message-ID: On Thursday, October 30, 2014 10:53:13 PM UTC+5:30, Joshua Landau wrote: > On 29 October 2014 03:22, Rustom Mody wrote: > > Yesterday I was trying to introduce python to some senior computer scientists. > > > > Tried showing a comprehension-based dir-walker vs a for-loop based one: > > > > def dw(p): > > if isfile(p): > > return [p] > > else: > > return [p] + [c for f in listdir(p) for c in dw(p+'/'+f)] > > > ... > > > > Comment to me : "Well this is neat and compact, but it does not add > > anything fundamental (over usual index based for-loops)" > > > > I tried to say that 'for' over general sequences is quite different > > and significantly more powerful than C/Pascal for over indexes + > > explicit indexing. > > If you really want to show the generality of iteration, I suggest you > start with iterators: > > def walk(path): > yield path > > if isdir(path): > for name in iterdir(path): > for file in walk(path + "/" + name): > yield file heh! That was my next version -- almost word-for-word [Not on that laptop now; will check later] From tjreedy at udel.edu Thu Oct 30 13:57:14 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 30 Oct 2014 13:57:14 -0400 Subject: Has color "Green" changed from Python 33 to 34 ? In-Reply-To: References: <54521fa1$0$2040$426a74cc@news.free.fr> Message-ID: On 10/30/2014 8:20 AM, Peter Otten wrote: > ast wrote: > >> I just updated this morning my Python from a 3.3rc to 3.4 >> (Windows) and I noticed that the 'Green' color in tkinter >> GUI is not the same at all. >> >> 'Green' in 3.4 is very dark. I had to replace it with 'Lime' to >> get back a nice 'Green'. > > More likely the color is defined by tcl/tk rather than Python, and your > Python installations use different versions of tcl. > Searching for 'tcl/tk > color definitions' finds with the following > statement > > """From Tcl/Tk 8.6 on, Tk uses Web colours instead of X11 ones, where they > conflict. > """ 3.4 switched from 8.5 to 8.6 > and according to > > "green" is indeed one of the affected colors. -- Terry Jan Reedy From tjreedy at udel.edu Thu Oct 30 14:04:04 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 30 Oct 2014 14:04:04 -0400 Subject: accents in windows In-Reply-To: <1796463426.3602276.1414672249566.JavaMail.zimbra@estudiantes.uci.cu> References: <838615157.3476350.1414627277178.JavaMail.zimbra@estudiantes.uci.cu> <1003235191.3477106.1414627437852.JavaMail.zimbra@estudiantes.uci.cu> <1796463426.3602276.1414672249566.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On 10/30/2014 8:30 AM, C at rlos wrote: > thanks U, but the real problem is: > > i have a path C:\Users\yanet\Desktop\?aa?ee?iii?oo?uu?nn > this path is correct, ?aa?ee?iii?oo?uu?nn is the name of a directory > but when i try to use os.walk() usin this path, dont work, for os this > path dont exist, i try every things but nothing works. > > some help??? Using Python 3.4 should solve this problem. > ----- Mensaje original ----- > De: "Chris Angelico" > CC: python-list at python.org > Enviados: Jueves, 30 de Octubre 2014 4:42:49 > Asunto: Re: accents in windows > > On Thu, Oct 30, 2014 at 11:03 AM, C at rlos wrote: >> i cant print any accent(? ? ? ? ?) or ? in console when i use windows OS >> with python, the console showme an error or extrangers characters in some >> cases, i need help Using Idle and a font with accented chars should solve this problem. > What version of Python? What is your code page set to? > > Windows and Unicode don't play very nicely together. You may find it > better to use Idle (which has a GUI for this kind of display), and you > will almost certainly find things easier on Linux. -- Terry Jan Reedy From tjreedy at udel.edu Thu Oct 30 14:06:27 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 30 Oct 2014 14:06:27 -0400 Subject: When using a decorator exceptions raised reference the decorator not the function In-Reply-To: References: Message-ID: On 10/30/2014 8:33 AM, N?stor Bosc?n wrote: > I'm using Python 2.7 and I'm creating a class decorator that extract > information from exceptions for logging purposes. > > Everytime an exception is raised from the original function and I > extract the origin of the exception with sys.exc_info() I get a > reference to the line in the decorator where the function is called, not > the line of the original function where the exception was raised. I expect that both lines should be in the traceback. Post an example where you do not intercept the exception. -- Terry Jan Reedy From wxjmfauth at gmail.com Thu Oct 30 15:30:52 2014 From: wxjmfauth at gmail.com (wxjmfauth at gmail.com) Date: Thu, 30 Oct 2014 12:30:52 -0700 (PDT) Subject: accents in windows In-Reply-To: References: <838615157.3476350.1414627277178.JavaMail.zimbra@estudiantes.uci.cu> <1003235191.3477106.1414627437852.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: <92bb8ae0-b225-453b-a5e1-72dd6f09bf96@googlegroups.com> Le jeudi 30 octobre 2014 09:43:34 UTC+1, Chris Angelico a ?crit?: > What version of Python? Good question. > What is your code page set to? Good question. > Windows and Unicode don't play very nicely together. Certainly and definitely not true. > You may find it better to use Idle (which has a GUI > for this kind of display), Where do you get the idea, it is an interactive intepreter problem? "console" may just mean the terminal ("dos box"). > and you will almost certainly find things easier on Linux. No. The problems are identical on Windows or on Linux'es or ... The guilty part is Python, not the platforms. --- There are not enough infos to help C at rlos. --- Terry: "...a font with accented chars..." On which planet are you leaving? jmf From d.corti at gmail.com Thu Oct 30 15:42:20 2014 From: d.corti at gmail.com (Dario) Date: Thu, 30 Oct 2014 12:42:20 -0700 (PDT) Subject: pySerial works in miniterm but not in my app Message-ID: <5cb7e219-cc34-4a4f-ae93-3a2bbfa9121a@googlegroups.com> Python 2.7.6 on Mint, pySerial 2.6 I'm trying to write a console app to control a certain device via a usb com port. In miniterm (-p /dev/ttyUSB0 -e -b 19200), I can communicate correctly with this configuration: --- Settings: /dev/ttyUSB0 19200,8,N,1 --- RTS: inactive DTR: inactive BREAK: inactive --- CTS: inactive DSR: inactive RI: inactive CD: inactive --- software flow control: inactive --- hardware flow control: inactive --- data escaping: raw linefeed: CR sw o01 + <--- I send this sw o01 + Command OK <--- device does what it should *and* I receive this Now my code: ---- import serial s = serial.serial_for_url( '/dev/ttyUSB0', 19200, bytesize = 8, parity = 'N', stopbits = 1, rtscts = False, dsrdtr = False, xonxoff = False, timeout = 1 # tried without ) s.close() # tried without s.open() s.write('sw o01 +\r') s.flush() # tried without s.close() # tried with a sleep before close ---- With this I don't receive anything (tried with readline etc, omitted for readability), and the device doesn't react. Also, if I connect again with miniterm and issue the command, I first receive a "wrong command" message, as if some garbage was actually sent by my app, then it works again. Isn't my config equivalent to the one in miniterm? Anything missing? Thanks From Seymore4Head at Hotmail.invalid Thu Oct 30 16:16:51 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 30 Oct 2014 16:16:51 -0400 Subject: Classes Message-ID: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> class pet: def set_age(self,age): self.age=age def get_age(self): return self.age pax=pet pax.set_age(4) Traceback (most recent call last): File "C:\Functions\test.py", line 18, in pax.set_age(4) TypeError: set_age() missing 1 required positional argument: 'age' I am trying to pass 4 as the age. Obviously I am doing it wrong. From sohcahtoa82 at gmail.com Thu Oct 30 16:33:01 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Thu, 30 Oct 2014 13:33:01 -0700 (PDT) Subject: Classes In-Reply-To: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> Message-ID: <7337e0d9-19cd-4a42-907d-9bc676327ae8@googlegroups.com> On Thursday, October 30, 2014 1:19:57 PM UTC-7, Seymore4Head wrote: > class pet: > def set_age(self,age): > self.age=age > def get_age(self): > return self.age > pax=pet > pax.set_age(4) > > Traceback (most recent call last): > File "C:\Functions\test.py", line 18, in > pax.set_age(4) > TypeError: set_age() missing 1 required positional argument: 'age' > > I am trying to pass 4 as the age. Obviously I am doing it wrong. The line `pax=pet` doesn't create an instance of your pet class, it creates essentially a copy of the class definition. You need `pax=pet()` Or preferably, `pax = pet()`. The spaces are optional, but they make it more readable. From rgaddi at technologyhighland.invalid Thu Oct 30 16:34:04 2014 From: rgaddi at technologyhighland.invalid (Rob Gaddi) Date: Thu, 30 Oct 2014 13:34:04 -0700 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> Message-ID: <20141030133404.44c0875e@rg.highlandtechnology.com> On Thu, 30 Oct 2014 16:16:51 -0400 Seymore4Head wrote: > class pet: > def set_age(self,age): > self.age=age > def get_age(self): > return self.age > pax=pet > pax.set_age(4) > > Traceback (most recent call last): > File "C:\Functions\test.py", line 18, in > pax.set_age(4) > TypeError: set_age() missing 1 required positional argument: 'age' > > I am trying to pass 4 as the age. Obviously I am doing it wrong. > The reason your call is missing the positional argument is that 4 is being assigned to self, rather than to age, so there is no age. This is because you are trying to call a function of the class object, rather than a function of an instance of the class. pax=pet() -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From Seymore4Head at Hotmail.invalid Thu Oct 30 17:00:09 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 30 Oct 2014 17:00:09 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <7337e0d9-19cd-4a42-907d-9bc676327ae8@googlegroups.com> Message-ID: On Thu, 30 Oct 2014 13:33:01 -0700 (PDT), sohcahtoa82 at gmail.com wrote: >On Thursday, October 30, 2014 1:19:57 PM UTC-7, Seymore4Head wrote: >> class pet: >> def set_age(self,age): >> self.age=age >> def get_age(self): >> return self.age >> pax=pet >> pax.set_age(4) >> >> Traceback (most recent call last): >> File "C:\Functions\test.py", line 18, in >> pax.set_age(4) >> TypeError: set_age() missing 1 required positional argument: 'age' >> >> I am trying to pass 4 as the age. Obviously I am doing it wrong. > >The line `pax=pet` doesn't create an instance of your pet class, it creates essentially a copy of the class definition. > >You need `pax=pet()` > >Or preferably, `pax = pet()`. The spaces are optional, but they make it more readable. Thanks From Seymore4Head at Hotmail.invalid Thu Oct 30 17:00:47 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 30 Oct 2014 17:00:47 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <20141030133404.44c0875e@rg.highlandtechnology.com> Message-ID: On Thu, 30 Oct 2014 13:34:04 -0700, Rob Gaddi wrote: >On Thu, 30 Oct 2014 16:16:51 -0400 >Seymore4Head wrote: > >> class pet: >> def set_age(self,age): >> self.age=age >> def get_age(self): >> return self.age >> pax=pet >> pax.set_age(4) >> >> Traceback (most recent call last): >> File "C:\Functions\test.py", line 18, in >> pax.set_age(4) >> TypeError: set_age() missing 1 required positional argument: 'age' >> >> I am trying to pass 4 as the age. Obviously I am doing it wrong. >> > >The reason your call is missing the positional argument is that 4 is >being assigned to self, rather than to age, so there is no age. This is >because you are trying to call a function of the class object, rather >than a function of an instance of the class. > >pax=pet() Thanks From orgnut at yahoo.com Thu Oct 30 17:28:19 2014 From: orgnut at yahoo.com (Larry Hudson) Date: Thu, 30 Oct 2014 14:28:19 -0700 Subject: Classes In-Reply-To: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> Message-ID: On 10/30/2014 01:16 PM, Seymore4Head wrote: > class pet: > def set_age(self,age): > self.age=age > def get_age(self): > return self.age > pax=pet > pax.set_age(4) > > Traceback (most recent call last): > File "C:\Functions\test.py", line 18, in > pax.set_age(4) > TypeError: set_age() missing 1 required positional argument: 'age' > > I am trying to pass 4 as the age. Obviously I am doing it wrong. > You have already received the answer -- pax=pet should be pax=pet(), but I have a simple side-comment about style. It is common Python convention to capitalize class names, IOW make this class Pet instead of class pet. This is convention not a requirement, but it does help distinguish class names from ordinary variable names -- especially to others reading your code (as well as yourself a few days later). ;-) -=- Larry -=- From Seymore4Head at Hotmail.invalid Thu Oct 30 17:34:57 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Thu, 30 Oct 2014 17:34:57 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> Message-ID: On Thu, 30 Oct 2014 14:28:19 -0700, Larry Hudson wrote: >On 10/30/2014 01:16 PM, Seymore4Head wrote: >> class pet: >> def set_age(self,age): >> self.age=age >> def get_age(self): >> return self.age >> pax=pet >> pax.set_age(4) >> >> Traceback (most recent call last): >> File "C:\Functions\test.py", line 18, in >> pax.set_age(4) >> TypeError: set_age() missing 1 required positional argument: 'age' >> >> I am trying to pass 4 as the age. Obviously I am doing it wrong. >> >You have already received the answer -- pax=pet should be pax=pet(), but I have a simple >side-comment about style. It is common Python convention to capitalize class names, IOW make >this class Pet instead of class pet. This is convention not a requirement, but it does help >distinguish class names from ordinary variable names -- especially to others reading your code >(as well as yourself a few days later). ;-) > > -=- Larry -=- I try to take typing shortcuts and it bites me in the behind. Good suggestion Thanks From vs at it.uu.se Thu Oct 30 17:30:37 2014 From: vs at it.uu.se (Virgil Stokes) Date: Thu, 30 Oct 2014 22:30:37 +0100 Subject: Saving a file "in the background" -- How? Message-ID: <5452ADFD.5030801@it.uu.se> While running a python program I need to save some of the data that is being created. I would like to save the data to a file on a disk according to a periodical schedule (e.g. every 10 minutes). Initially, the amount of data is small (< 1 MB) but after sometime the amount of data can be >10MB. If a problem occurs during data creation, then the user should be able to start over from the last successfully saved data. For my particular application, no other file is being saved and the data should always replace (not be appended to) the previous data saved. It is important that the data be saved without any obvious distraction to the user who is busy creating more data. That is, I would like to save the data "in the background". What is a good method to perform this task using Python 2.7.8 on a Win32 platform? From nestor.boscan at tcs.com.ve Thu Oct 30 17:12:38 2014 From: nestor.boscan at tcs.com.ve (=?UTF-8?B?TsOpc3RvciBCb3Njw6Fu?=) Date: Thu, 30 Oct 2014 16:42:38 -0430 Subject: When using a decorator exceptions raised reference the decorator not the function In-Reply-To: References: Message-ID: Thanks Terry Yes both lines where in the traceback using tb_next I got what I needed. Regards, N?stor On Thu, Oct 30, 2014 at 1:36 PM, Terry Reedy wrote: > On 10/30/2014 8:33 AM, N?stor Bosc?n wrote: > > I'm using Python 2.7 and I'm creating a class decorator that extract >> information from exceptions for logging purposes. >> >> Everytime an exception is raised from the original function and I >> extract the origin of the exception with sys.exc_info() I get a >> reference to the line in the decorator where the function is called, not >> the line of the original function where the exception was raised. >> > > I expect that both lines should be in the traceback. Post an example > where you do not intercept the exception. > > -- > Terry Jan Reedy > > > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From joel.goldstick at gmail.com Thu Oct 30 18:21:21 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Thu, 30 Oct 2014 18:21:21 -0400 Subject: Saving a file "in the background" -- How? In-Reply-To: <5452ADFD.5030801@it.uu.se> References: <5452ADFD.5030801@it.uu.se> Message-ID: On Thu, Oct 30, 2014 at 5:30 PM, Virgil Stokes wrote: > While running a python program I need to save some of the data that is being > created. I would like to save the data to a file on a disk according to a > periodical schedule (e.g. every 10 minutes). Initially, the amount of data > is small (< 1 MB) but after sometime the amount of data can be >10MB. If a > problem occurs during data creation, then the user should be able to start > over from the last successfully saved data. > > For my particular application, no other file is being saved and the data > should always replace (not be appended to) the previous data saved. It is > important that the data be saved without any obvious distraction to the > user who is busy creating more data. That is, I would like to save the data > "in the background". > > What is a good method to perform this task using Python 2.7.8 on a Win32 > platform? > -- > https://mail.python.org/mailman/listinfo/python-list I've not tried this, but stackoverflow has a solution that looks like it could work for you: http://stackoverflow.com/questions/16214736/write-data-to-disk-in-python-as-a-background-process -- Joel Goldstick http://joelgoldstick.com From steve+comp.lang.python at pearwood.info Thu Oct 30 18:48:10 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 31 Oct 2014 09:48:10 +1100 Subject: Python Style Question References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <5452c02a$0$12994$c3e8da3$5496439d@news.astraweb.com> MRAB wrote: > On 2014-10-30 11:10, Steven D'Aprano wrote: >> Anton wrote: >> >>> Let's say I have an incoming list of values *l*. Every element of *l* >>> can be one of the following options: >>> 1) an integer value >>> 2) a string in form of '', e.g. '7' >>> 3) a string with a json serialization of an integer value, e.g. '"7"' >>> 4) something else that should be ignored >>> >>> I need to transform this list into another list with values from options >>> 1)-3) coerced to int. The code below should do this. >> >> I don't particularly like either version. I prefer this: >> >> def load_int(obj): >> if isinstance(obj, int): >> # Case 1), an int, e.g. 7 >> return obj >> elif isinstance(obj, str): >> # Case 2) and 3), a str or JSON serialised int. >> # E.g. '7' or '"7"'. >> try: >> return int(obj) >> except ValueError: >> return int(json.loads(obj)) >> raise TypeError('require int or str, got %s' % type(obj).__name__) >> > [snip] > > How about: > > int(str(obj).strip('"')) Absolutely not. obj = '""""""""""""""1\n\n\n\n' # not valid JSON load_int(obj) => raises ValueError int(str(obj).strip('"')) => wrongly returns 1 -- Steven From cs at zip.com.au Thu Oct 30 20:32:22 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 31 Oct 2014 11:32:22 +1100 Subject: problem with pefile In-Reply-To: <11bb3aad-9d8b-442a-b5d3-09af6b771737@googlegroups.com> References: <11bb3aad-9d8b-442a-b5d3-09af6b771737@googlegroups.com> Message-ID: <20141031003222.GA21852@cskk.homeip.net> On 29Oct2014 08:34, gandalf23 at mail.com wrote: >OT: how can I hide my email in these posts? >Every time I try to send a post, google warns me that my email is visible and so I edit it out. Why would you want to hide your email? Cameron Simpson From roy at panix.com Thu Oct 30 20:34:27 2014 From: roy at panix.com (Roy Smith) Date: Thu, 30 Oct 2014 20:34:27 -0400 Subject: Python Style Question References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: In article <54521c8f$0$12982$c3e8da3$5496439d at news.astraweb.com>, Steven D'Aprano wrote: > Anton wrote: > > > Let's say I have an incoming list of values *l*. Every element of *l* can > > be one of the following options: > > 1) an integer value > > 2) a string in form of '', e.g. '7' > > 3) a string with a json serialization of an integer value, e.g. '"7"' > > 4) something else that should be ignored > > > > I need to transform this list into another list with values from options > > 1)-3) coerced to int. The code below should do this. > > I don't particularly like either version. I prefer this: > > def load_int(obj): > if isinstance(obj, int): > # Case 1), an int, e.g. 7 > return obj > elif isinstance(obj, str): > # Case 2) and 3), a str or JSON serialised int. > # E.g. '7' or '"7"'. > try: > return int(obj) > except ValueError: > return int(json.loads(obj)) > raise TypeError('require int or str, got %s' % type(obj).__name__) Depending on how strictly you're trying to do input validation, the int(json.loads(obj)) may not be what you want. It allows well-formed json encoding floats, for example. And, of course, since >>> isinstance(True, int) True this code accepts booleans. Oh, but wait, that's by design :-) From gandalf23 at mail.com Thu Oct 30 20:58:51 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Thu, 30 Oct 2014 17:58:51 -0700 (PDT) Subject: problem with pefile In-Reply-To: References: <11bb3aad-9d8b-442a-b5d3-09af6b771737@googlegroups.com> Message-ID: <59be2b15-3995-4cfa-a11d-58d001ddc622@googlegroups.com> On Friday, October 31, 2014 1:33:07 AM UTC+1, Cameron Simpson wrote: > On 29Oct2014 08:34, gandalf23 wrote: > >OT: how can I hide my email in these posts? > >Every time I try to send a post, google warns me that my email is visible and so I edit it out. > > Why would you want to hide your email? > > Cameron Simpson I don't want more spam. From cs at zip.com.au Thu Oct 30 21:22:59 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 31 Oct 2014 12:22:59 +1100 Subject: problem with pefile In-Reply-To: <59be2b15-3995-4cfa-a11d-58d001ddc622@googlegroups.com> References: <59be2b15-3995-4cfa-a11d-58d001ddc622@googlegroups.com> Message-ID: <20141031012259.GA14234@cskk.homeip.net> On 30Oct2014 17:58, Kiuhnm wrote: >On Friday, October 31, 2014 1:33:07 AM UTC+1, Cameron Simpson wrote: >> On 29Oct2014 08:34, gandalf23 wrote: >> >OT: how can I hide my email in these posts? >> >Every time I try to send a post, google warns me that my email is visible and so I edit it out. >> >> Why would you want to hide your email? > >I don't want more spam. You just need to filter your email better. Most of us do not hide our addresses. I manage to filter most of my spam by filing anything which gets past all my rules that catch mailing lists and which do not come from addresses in my "known" group into a probably-spam folder. It is surprisingly effective. Basicly: - to me (me in to/cc/bcc), from a "known" author ==> inbox - matches one of my mailing list rules ==> appropriate-folder - otherwise ==> probably-spam That is a simplification, but it is my basic scheme. Works fairly well. Anyway, this is off-topic for python-list so I'll shut up now. Cheers, Cameron Simpson It must be public fact, because I'm not the only one who knows about it. - Stefan A. Werner From vbubbly21 at gmail.com Thu Oct 30 21:22:45 2014 From: vbubbly21 at gmail.com (Artur Bercik) Date: Fri, 31 Oct 2014 10:22:45 +0900 Subject: set environmental variable from python Message-ID: I have to set environmental variable in my windows PC as follows: variable name: GISBASE value: C:\GRASS-64 Is it possible to set it from python? import sys sys.path.append("C:\\GRASS-64") But how to give variable name? I have to set both the variable name and value. Thanks in the advance. Artur -------------- next part -------------- An HTML attachment was scrubbed... URL: From sohcahtoa82 at gmail.com Thu Oct 30 21:21:13 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Thu, 30 Oct 2014 18:21:13 -0700 (PDT) Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> Message-ID: <9b71b42d-220f-4d08-990f-d3873d87245a@googlegroups.com> On Thursday, October 30, 2014 2:37:54 PM UTC-7, Seymore4Head wrote: > On Thu, 30 Oct 2014 14:28:19 -0700, Larry Hudson > wrote: > > >On 10/30/2014 01:16 PM, Seymore4Head wrote: > >> class pet: > >> def set_age(self,age): > >> self.age=age > >> def get_age(self): > >> return self.age > >> pax=pet > >> pax.set_age(4) > >> > >> Traceback (most recent call last): > >> File "C:\Functions\test.py", line 18, in > >> pax.set_age(4) > >> TypeError: set_age() missing 1 required positional argument: 'age' > >> > >> I am trying to pass 4 as the age. Obviously I am doing it wrong. > >> > >You have already received the answer -- pax=pet should be pax=pet(), but I have a simple > >side-comment about style. It is common Python convention to capitalize class names, IOW make > >this class Pet instead of class pet. This is convention not a requirement, but it does help > >distinguish class names from ordinary variable names -- especially to others reading your code > >(as well as yourself a few days later). ;-) > > > > -=- Larry -=- > > I try to take typing shortcuts and it bites me in the behind. > Good suggestion > Thanks A shortcut is the fastest way to get somewhere you weren't going. Python makes programming very easy (Compared to C/C++ and many other languages), but there are still a lot of shortcuts you can't make. From ethan at stoneleaf.us Thu Oct 30 21:25:30 2014 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 30 Oct 2014 18:25:30 -0700 Subject: ANN: Antipathy v0.8 Message-ID: <5452E50A.1090803@stoneleaf.us> has just been made compatible with Python 3! It runs on everything from 2.4 forward, haven't testing anything prior to that. It is available for download at https://pypi.python.org//pypi/antipathy ------------------------------------------------------------------------------- Antipathy -- for those tired of ``os.path`` =========================================== Tired of calling a function for every path manipulation you need to do? Is: >>> path, filename = os.path.split(some_name) >>> basename, ext = os.path.splitext(filename) >>> basename = basename + '_01' >>> new_name = os.path.join(path, basename+ext) wearing on your nerves? In short, are you filled with antipathy [1] for os.path? Then get antipathy and work with Path: >>> some_name = Path('/home/ethan/source/my_file.txt') >>> backups = Path('/home/ethan/backup/') >>> print some_name.path '/home/ethan/source/' >>> print some_name.ext '.txt' >>> print some_name.exists() True # (well, if it happens to exist at this moment ;) >>> backup = backups / some_name.filename + '_01' + some_name.ext >>> print backup '/home/ethan/backup/my_file_01.txt' >>> some_name.copy(backup) Because Path is a subclass of bytes/str/unicode, it can still be passed to other functions that expect a bytes/str/unicode object and work seamlessly [2]. [1] https://www.google.com/#q=antipathy [2] in most cases -- there are a few places that do a `type` check instead of an `isinstance` check. From Deepfriedice at openmailbox.org Thu Oct 30 21:45:31 2014 From: Deepfriedice at openmailbox.org (Deepfriedice) Date: Fri, 31 Oct 2014 11:45:31 +1000 Subject: Saving a file "in the background" -- How? References: Message-ID: Why not just call the save function as a separate thread? threading.Thread(target=save, args=(data)).start() From davea at davea.name Thu Oct 30 21:50:26 2014 From: davea at davea.name (Dave Angel) Date: Thu, 30 Oct 2014 21:50:26 -0400 Subject: set environmental variable from python In-Reply-To: References: Message-ID: <5452EAE2.8020500@davea.name> On 10/30/2014 09:22 PM, Artur Bercik wrote: > I have to set environmental variable in my windows PC as follows: > > variable name: GISBASE > > value: C:\GRASS-64 > > Is it possible to set it from python? Which Python? I'll have to assume 3.x > > import sys > > sys.path.append("C:\\GRASS-64") > > But how to give variable name? I have to set both the variable name and > value. > sys.path has nothing to do with an environment variable of GISBASE. Instead you could look up os.environ at: https://docs.python.org/3/library/os.html Also see os.getenv and os.setenv. Note that it's not necessarily supported. But I believe it is for a standard build on Windows. Next question is what you hope to achieve by setting such a variable. You do realize that it will vanish again when your python process ends? So if you're just planning to use it in your own code, I'd recommend finding another method of saving the name & value. The only value I can see is if you plan to create a subprocess from your Python code. -- DaveA From tjreedy at udel.edu Thu Oct 30 22:00:30 2014 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 30 Oct 2014 22:00:30 -0400 Subject: Saving a file "in the background" -- How? In-Reply-To: References: <5452ADFD.5030801@it.uu.se> Message-ID: On 10/30/2014 6:21 PM, Joel Goldstick wrote: > On Thu, Oct 30, 2014 at 5:30 PM, Virgil Stokes wrote: >> While running a python program I need to save some of the data that is being >> created. I would like to save the data to a file on a disk according to a >> periodical schedule (e.g. every 10 minutes). Initially, the amount of data >> is small (< 1 MB) but after sometime the amount of data can be >10MB. If a >> problem occurs during data creation, then the user should be able to start >> over from the last successfully saved data. >> >> For my particular application, no other file is being saved and the data >> should always replace (not be appended to) the previous data saved. It is >> important that the data be saved without any obvious distraction to the >> user who is busy creating more data. That is, I would like to save the data >> "in the background". >> >> What is a good method to perform this task using Python 2.7.8 on a Win32 >> platform? >> -- >> https://mail.python.org/mailman/listinfo/python-list > > I've not tried this, but stackoverflow has a solution that looks like > it could work for you: > http://stackoverflow.com/questions/16214736/write-data-to-disk-in-python-as-a-background-process Python 3.4 should have an asyncio solution. -- Terry Jan Reedy From vbubbly21 at gmail.com Thu Oct 30 22:03:01 2014 From: vbubbly21 at gmail.com (Artur Bercik) Date: Fri, 31 Oct 2014 11:03:01 +0900 Subject: set environmental variable from python In-Reply-To: <5452EAE2.8020500@davea.name> References: <5452EAE2.8020500@davea.name> Message-ID: Dear Dave Angel Thanks for your answer. I am using Python 2.7 I want to set it permanently. I have to set several variables so it would be easier if I could set them from Python. Hearing the solution. On Fri, Oct 31, 2014 at 10:50 AM, Dave Angel wrote: > On 10/30/2014 09:22 PM, Artur Bercik wrote: > >> I have to set environmental variable in my windows PC as follows: >> >> variable name: GISBASE >> >> value: C:\GRASS-64 >> >> Is it possible to set it from python? >> > > Which Python? I'll have to assume 3.x > > >> import sys >> >> sys.path.append("C:\\GRASS-64") >> >> But how to give variable name? I have to set both the variable name and >> value. >> >> > sys.path has nothing to do with an environment variable of GISBASE. > > Instead you could look up os.environ at: > > https://docs.python.org/3/library/os.html > > Also see os.getenv and os.setenv. > > > > Note that it's not necessarily supported. But I believe it is for a > standard build on Windows. > > Next question is what you hope to achieve by setting such a variable. You > do realize that it will vanish again when your python process ends? So if > you're just planning to use it in your own code, I'd recommend finding > another method of saving the name & value. > > The only value I can see is if you plan to create a subprocess from your > Python code. > > -- > DaveA > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zachary.ware+pylist at gmail.com Thu Oct 30 22:30:52 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 30 Oct 2014 21:30:52 -0500 Subject: set environmental variable from python In-Reply-To: References: <5452EAE2.8020500@davea.name> Message-ID: On Thursday, October 30, 2014, Artur Bercik wrote: > Dear Dave Angel > > Thanks for your answer. > > I am using Python 2.7 > > I want to set it permanently. > I have to set several variables so it would be easier if I could set them > from Python. > Depending on how "permanently" you mean, about your only solutions would be "os.system('setx <...>')" or manually manipulating the registry with the _winreg module. Hope this helps, -- Zach -- Sent from Gmail Mobile -------------- next part -------------- An HTML attachment was scrubbed... URL: From rustompmody at gmail.com Thu Oct 30 22:36:48 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 30 Oct 2014 19:36:48 -0700 (PDT) Subject: set environmental variable from python In-Reply-To: References: <5452EAE2.8020500@davea.name> Message-ID: <36c5d2db-a931-417e-ae8c-9c77acfc947b@googlegroups.com> On Friday, October 31, 2014 8:01:08 AM UTC+5:30, Zachary Ware wrote: > On Thursday, October 30, 2014, Artur Bercik wrote: > > Dear Dave Angel > > > Thanks for your answer. > > > I am using Python 2.7 > > > I want to set it permanently. > I have to set several variables so it would be easier if I could set them from Python. > > > Depending on how "permanently" you mean, about your only solutions > would be "os.system('setx <...>')" or manually manipulating the > registry with the _winreg module. Or dont do it from python but directly with regedit?? The question really is: Why do you wish to do this from within python? From vbubbly21 at gmail.com Thu Oct 30 22:40:55 2014 From: vbubbly21 at gmail.com (Artur Bercik) Date: Fri, 31 Oct 2014 11:40:55 +0900 Subject: set environmental variable from python In-Reply-To: References: <5452EAE2.8020500@davea.name> Message-ID: could you please elaborate 'setx <...>'? On Fri, Oct 31, 2014 at 11:30 AM, Zachary Ware < zachary.ware+pylist at gmail.com> wrote: > On Thursday, October 30, 2014, Artur Bercik wrote: > >> Dear Dave Angel >> >> Thanks for your answer. >> >> I am using Python 2.7 >> >> I want to set it permanently. >> I have to set several variables so it would be easier if I could set them >> from Python. >> > > Depending on how "permanently" you mean, about your only solutions would > be "os.system('setx <...>')" or manually manipulating the registry with the > _winreg module. > > Hope this helps, > -- > Zach > > > -- > Sent from Gmail Mobile > > -- > https://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vbubbly21 at gmail.com Thu Oct 30 22:43:21 2014 From: vbubbly21 at gmail.com (Artur Bercik) Date: Fri, 31 Oct 2014 11:43:21 +0900 Subject: set environmental variable from python In-Reply-To: <36c5d2db-a931-417e-ae8c-9c77acfc947b@googlegroups.com> References: <5452EAE2.8020500@davea.name> <36c5d2db-a931-417e-ae8c-9c77acfc947b@googlegroups.com> Message-ID: I have to set several variables so it would be easier if I could set them from Python. On Fri, Oct 31, 2014 at 11:36 AM, Rustom Mody wrote: > On Friday, October 31, 2014 8:01:08 AM UTC+5:30, Zachary Ware wrote: > > On Thursday, October 30, 2014, Artur Bercik wrote: > > > > Dear Dave Angel > > > > > > Thanks for your answer. > > > > > > I am using Python 2.7 > > > > > > I want to set it permanently. > > I have to set several variables so it would be easier if I could set > them from Python. > > > > > > Depending on how "permanently" you mean, about your only solutions > > would be "os.system('setx <...>')" or manually manipulating the > > registry with the _winreg module. > > Or dont do it from python but directly with regedit?? > > The question really is: Why do you wish to do this from within python? > > > -- > https://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rustompmody at gmail.com Thu Oct 30 22:45:54 2014 From: rustompmody at gmail.com (Rustom Mody) Date: Thu, 30 Oct 2014 19:45:54 -0700 (PDT) Subject: set environmental variable from python In-Reply-To: References: <5452EAE2.8020500@davea.name> Message-ID: <449b3e0f-61f6-41e6-a6d7-5f2678157a58@googlegroups.com> On Friday, October 31, 2014 7:33:43 AM UTC+5:30, Artur Bercik wrote: > Dear Dave Angel > > > Thanks for your answer. > > > I am using Python 2.7 > > > I want to set it permanently. > I have to set several variables so it would be easier if I could set them from Python. regedit is scriptable http://support.microsoft.com/kb/310516 [Be careful though! Follow the precautions like backing up the registry before messing around] From zachary.ware+pylist at gmail.com Thu Oct 30 23:00:33 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Thu, 30 Oct 2014 22:00:33 -0500 Subject: set environmental variable from python In-Reply-To: References: <5452EAE2.8020500@davea.name> Message-ID: On Thu, Oct 30, 2014 at 9:40 PM, Artur Bercik wrote: > could you please elaborate 'setx <...>'? >From a Command Prompt, do 'help setx' for details on how to use setx. Rustom's suggestion of using regedit is going to be far easier than using _winreg (which probably shouldn't even be considered as an option). Using `os.system('setx ...')` is going to be the easiest way to do things if you have to calculate the values of your variables, but if you just have a bunch of values that you're going to have to key in anyway, just use setx directly (or in a batch script). -- Zach From steve+comp.lang.python at pearwood.info Thu Oct 30 23:52:49 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Fri, 31 Oct 2014 14:52:49 +1100 Subject: Python Style Question References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> Message-ID: <54530792$0$12976$c3e8da3$5496439d@news.astraweb.com> Roy Smith wrote: > In article <54521c8f$0$12982$c3e8da3$5496439d at news.astraweb.com>, > Steven D'Aprano wrote: > >> Anton wrote: >> >> > Let's say I have an incoming list of values *l*. Every element of *l* >> > can be one of the following options: >> > 1) an integer value >> > 2) a string in form of '', e.g. '7' >> > 3) a string with a json serialization of an integer value, e.g. '"7"' >> > 4) something else that should be ignored >> > >> > I need to transform this list into another list with values from >> > options 1)-3) coerced to int. The code below should do this. >> >> I don't particularly like either version. I prefer this: >> >> def load_int(obj): >> if isinstance(obj, int): >> # Case 1), an int, e.g. 7 >> return obj >> elif isinstance(obj, str): >> # Case 2) and 3), a str or JSON serialised int. >> # E.g. '7' or '"7"'. >> try: >> return int(obj) >> except ValueError: >> return int(json.loads(obj)) >> raise TypeError('require int or str, got %s' % type(obj).__name__) > > Depending on how strictly you're trying to do input validation, the > int(json.loads(obj)) may not be what you want. It allows well-formed > json encoding floats, for example. Really? py> int(json.loads(json.dumps(23.5))) 23 Damn! You're right. Back to Plan A: elif isinstance(obj, str): try: return int(obj) except ValueError: if obj and obj.startswith('"') and obj.endswith('"'): return int(obj[1:-1]) raise But of course even the int() function itself may be a little more flexible than we might want: py> int(' 1 ') 1 So I guess the lessons are: * before writing code, you need to decide what the code is meant to do; * and that includes what input must be rejected, not just what input must be accepted. > And, of course, since > >>>> isinstance(True, int) > True > > this code accepts booleans. Oh, but wait, that's by design :-) Naturally :-) If you wanted to avoid it, that's easy, add a clause: if isinstance(obj, bool): raise TypeError at the start of the function. -- Steven From denismfmcmahon at gmail.com Fri Oct 31 00:55:30 2014 From: denismfmcmahon at gmail.com (Denis McMahon) Date: Fri, 31 Oct 2014 04:55:30 +0000 (UTC) Subject: Python Style Question References: <406463d0-1287-49a2-b1ed-08a928db4b94@googlegroups.com> <54521c8f$0$12982$c3e8da3$5496439d@news.astraweb.com> <5452c02a$0$12994$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Fri, 31 Oct 2014 09:48:10 +1100, Steven D'Aprano wrote: > MRAB wrote: >> How about: >> >> int(str(obj).strip('"')) > > Absolutely not. > > obj = '""""""""""""""1\n\n\n\n' # not valid JSON load_int(obj) > => raises ValueError int(str(obj).strip('"')) > => wrongly returns 1 How about #!/usr/bin/python import re, json l = [1, -1, 0, '+2', '2', '-2', '0', '"+3"', '"3"', '"-3"', '"0"', json.dumps(-4), json.dumps(4), json.dumps(0), 'x', 'sqjklsqjk__', (5, 6), 7.7, -7.7, '8.8', '+8.8', '-8.8', '"9.9"', '"+9.9"', '"-9.9"'] patt1 = re.compile(r'^([-+]?\d+)$') patt2 = re.compile(r'^"([-+]?\d+)"$') def getTheInt(x): if isinstance(x,int): return x if isinstance(x,str): tmp = patt1.match(x) if tmp: return int(tmp.group(1)) tmp = patt2.match(x) if tmp: return int(tmp.group(1)) return None a = [] for n in l: a.append(getTheInt(n)) print a # end of code prints: [1, -1, 0, 2, 2, -2, 0, 3, 3, -3, 0, -4, 4, 0, None, None, None, None, None, None, None, None, None, None, None] I know re matching the strings may be overkill, but it may be the best way of checking that the string contains the expected character format to convert to an int. -- Denis McMahon, denismfmcmahon at gmail.com From auriocus at gmx.de Fri Oct 31 03:05:22 2014 From: auriocus at gmx.de (Christian Gollwitzer) Date: Fri, 31 Oct 2014 08:05:22 +0100 Subject: Has color "Green" changed from Python 33 to 34 ? In-Reply-To: <54521fa1$0$2040$426a74cc@news.free.fr> References: <54521fa1$0$2040$426a74cc@news.free.fr> Message-ID: Am 30.10.14 12:23, schrieb ast: > I just updated this morning my Python from a 3.3rc to 3.4 (Windows) and > I noticed that the 'Green' color in tkinter GUI is not the same at all. > > 'Green' in 3.4 is very dark. I had to replace it with 'Lime' to > get back a nice 'Green'. If you are dependent on the exact RGB value, just use a hex triplet, this will be passed unmodified to the OS and never change. A 100% green would be '#00FF00'. Note that still the OS may choose to apply color profiles etc. to this color, but this is outside of the control of the application. Christian From d.corti at gmail.com Fri Oct 31 04:21:48 2014 From: d.corti at gmail.com (Dario) Date: Fri, 31 Oct 2014 01:21:48 -0700 (PDT) Subject: pySerial works in miniterm but not in my app In-Reply-To: References: <5cb7e219-cc34-4a4f-ae93-3a2bbfa9121a@googlegroups.com> Message-ID: <9f933554-ae04-4a3f-8317-0ed4f1e6d5b4@googlegroups.com> Il giorno gioved? 30 ottobre 2014 23:57:40 UTC+1, Dennis Lee Bieber ha scritto: > >sw o01 + <--- I send this > How do you "send this"... I just type or paste it in miniterm and hit return. Miniterm sends the return as CR, but it also works with CRLF. > >sw o01 + Command OK <--- device does what it should *and* I receive this > Is that a new line, or somehow part of the same line? This is the response from the device, saying that my command was ok, and it also does what it should (it's an hdmi 4-4 matrix, it switches the first output to the next input). > >s.write('sw o01 +\r') > What happens if you use \n... or \r\n ? In my app, that doesn't make any difference, never works. In miniterm, only CR and CRLF work, LF alone does not. This evening I'll try with com0com to see what is really sent... -- Dario From nomail at invalid.com Fri Oct 31 05:05:03 2014 From: nomail at invalid.com (ast) Date: Fri, 31 Oct 2014 10:05:03 +0100 Subject: Classes In-Reply-To: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> Message-ID: <545350c3$0$23449$426a74cc@news.free.fr> "Seymore4Head" a ?crit dans le message de news:51755at03r0bidjqh3qf0hhpvjr8756ill at 4ax.com... > class pet: > def set_age(self,age): > self.age=age > def get_age(self): > return self.age > pax=pet > pax.set_age(4) > > Traceback (most recent call last): > File "C:\Functions\test.py", line 18, in > pax.set_age(4) > TypeError: set_age() missing 1 required positional argument: 'age' > > I am trying to pass 4 as the age. Obviously I am doing it wrong. > Hi I am a beginner too, but I find it strange that your pet class has no __init__ method to construct instances From nomail at invalid.com Fri Oct 31 05:18:13 2014 From: nomail at invalid.com (ast) Date: Fri, 31 Oct 2014 10:18:13 +0100 Subject: Classes In-Reply-To: <545350c3$0$23449$426a74cc@news.free.fr> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: <545353dd$0$2326$426a74cc@news.free.fr> "ast" a ?crit dans le message de news:545350c3$0$23449$426a74cc at news.free.fr... > I am a beginner too, but I find it strange that your > pet class has no __init__ method to construct > instances It works anyway because __init__ is taken in the parent Class, probably Object. But this means that a method can create a new attribute not previously created with __init__. Is that correct ? From rosuav at gmail.com Fri Oct 31 05:21:45 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 31 Oct 2014 20:21:45 +1100 Subject: Classes In-Reply-To: <545353dd$0$2326$426a74cc@news.free.fr> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <545353dd$0$2326$426a74cc@news.free.fr> Message-ID: On Fri, Oct 31, 2014 at 8:18 PM, ast wrote: > > But this means that a method can create a new > attribute not previously created with __init__. > Is that correct ? That's always the case. There's nothing special about __init__ for creating attributes. ChrisA From alister.nospam.ware at ntlworld.com Fri Oct 31 05:59:30 2014 From: alister.nospam.ware at ntlworld.com (alister) Date: Fri, 31 Oct 2014 09:59:30 GMT Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> Message-ID: <64J4w.766648$dz3.103993@fx20.am4> On Thu, 30 Oct 2014 17:34:57 -0400, Seymore4Head wrote: > On Thu, 30 Oct 2014 14:28:19 -0700, Larry Hudson > wrote: > >>On 10/30/2014 01:16 PM, Seymore4Head wrote: >>> class pet: >>> def set_age(self,age): >>> self.age=age >>> def get_age(self): >>> return self.age >>> pax=pet pax.set_age(4) >>> >>> Traceback (most recent call last): >>> File "C:\Functions\test.py", line 18, in >>> pax.set_age(4) >>> TypeError: set_age() missing 1 required positional argument: 'age' >>> >>> I am trying to pass 4 as the age. Obviously I am doing it wrong. >>> >>You have already received the answer -- pax=pet should be pax=pet(), but >>I have a simple side-comment about style. It is common Python >>convention to capitalize class names, IOW make this class Pet instead of >>class pet. This is convention not a requirement, but it does help >>distinguish class names from ordinary variable names -- especially to >>others reading your code (as well as yourself a few days later). ;-) >> >> -=- Larry -=- > > I try to take typing shortcuts and it bites me in the behind. > Good suggestion Thanks If shortcuts were safe and easy they would not be shortcuts they would be the way. It is best to avoid shortcuts whilst learning untill you know the full implications. you will find your learning goes much smother & faster. -- We are all in the gutter, but some of us are looking at the stars. -- Oscar Wilde From chaselton at gmail.com Fri Oct 31 07:12:29 2014 From: chaselton at gmail.com (Cyd Haselton) Date: Fri, 31 Oct 2014 06:12:29 -0500 Subject: Build Question: How to Add -Wl, --option Before Objects In Setup.py? In-Reply-To: References: Message-ID: On Tue, Oct 28, 2014 at 4:01 PM, Ned Deily wrote: > In article > , > Cyd Haselton wrote: > >> On Tue, Oct 28, 2014 at 3:11 AM, Ned Deily wrote: >> > In article >> > , >> > Cyd Haselton wrote: >> > [...] >> >> I'm building python on an Android device in the KBOX >> >> environment...which simulates a Unix type filesystem. >> >> Python isn't installed; I'm building from sources (2.7.8) with GCC >> >> 4.8.0 and make. >> >> >> >> The problem with the LDFLAGS approach is that some of the libraries >> >> that must be linked (-lc -ldl) do not need the --allow-shlib-undefined >> >> option...it's only the lpython2.7 that does. Any way to do this? >> > >> > Sorry, I have no experience with that environment nor an understanding >> > of why you need to specify --allow-shlib-undefined (it seems to be the >> > default in some versions of ld). You could look at and, if necessary, >> > modify Lib/distutils, the part of the Python standard library that >> > builds extension modules from setup.py. > >> No need to apologize. Also no need to have an understanding of the >> environment; with a few rare exceptions it behaves just like a >> Unix/Linux one. >> >> The reason why I need to specify --allow-shlib-undefined is for the >> python library; it's throwing undefined references to sincos even >> though the symbol is there. Specifying that option is the only fix >> I've found. >> >> As mentioned earlier, i'm not familiar with python or its build >> system; which file in the distutils dir do I need to modify? > > Perhaps I should apologize for not asking earlier what you are really > trying to do before suggesting heading down the path of modifying > Distutils :) So the issue is with an undefined reference to sincos? It > appears that that routine is often supplied in libm. Is that the case > on your platform? And, if so, the right fix might be to supply it > manually or, better, ensure that Python supplies it as a result of > running ./configure. Also, what version of Python are you building? > > -- > Ned Deily, > nad at acm.org > > -- > https://mail.python.org/mailman/listinfo/python-list So, after trying various ways to add that flag before lpython in setup.py, I stripped all --allow-shlib-undefined --no-allow-shlib-undefined feom the Makefile, ran make clean, and make. I still get the following error: Modules/python.o \ -lc -ldl -lm -L. -lpython2.7 -lm ./libpython2.7.so: undefined reference to `sincos' collect2: error: ld returned 1 exit status make: *** [python] Error 1 Should I repost this to the dev mailing list? From gvanem at yahoo.no Fri Oct 31 07:31:07 2014 From: gvanem at yahoo.no (Gisle Vanem) Date: Fri, 31 Oct 2014 12:31:07 +0100 Subject: set environmental variable from python References: <5452EAE2.8020500@davea.name> <36c5d2db-a931-417e-ae8c-9c77acfc947b@googlegroups.com> Message-ID: "Artur Bercik" wrote: >I have to set several variables so it would be easier if I could set them > from Python. You can write a Python-script that generates a .bat file (in your %TEMP-dir?). And run this .bat file when Python ends. Put it all in an alias or another .bat file. E.g. untested: alias set_env=python -o %TEMP%\set_env.bat & %TEMP%\set_env.bat --gv From 4kir4.1i at gmail.com Fri Oct 31 08:07:42 2014 From: 4kir4.1i at gmail.com (Akira Li) Date: Fri, 31 Oct 2014 15:07:42 +0300 Subject: Saving a file "in the background" -- How? References: <5452ADFD.5030801@it.uu.se> Message-ID: <87h9ykphm9.fsf@gmail.com> Virgil Stokes writes: > While running a python program I need to save some of the data that is > being created. I would like to save the data to a file on a disk > according to a periodical schedule (e.g. every 10 > minutes). Initially, the amount of data is small (< 1 MB) but after > sometime the amount of data can be >10MB. If a problem occurs during > data creation, then the user should be able to start over from the > last successfully saved data. > > For my particular application, no other file is being saved and the > data should always replace (not be appended to) the previous data > saved. It is important that the data be saved without any obvious > distraction to the user who is busy creating more data. That is, I > would like to save the data "in the background". > > What is a good method to perform this task using Python 2.7.8 on a > Win32 platform? There are several requirements: - save data asynchroniously -- "without any obvious distraction to the user" - save data durably -- avoid corrupting previously saved data or writing only partial new data e.g., in case of a power failure - do it periodically -- handle drift/overlap gracefully in a documented way A simple way to do asynchronios I/O on Python 2.7.8 on a Win32 platform is to use threads: t = threading.Thread(target=backup_periodically, kwargs=dict(period=600)) t.daemon = True # stop if the program exits t.start() where backup_periodically() backups data every period seconds: import time def backup_periodically(period, timer=time.time, sleep=time.sleep): start = timer() while True: try: backup() except Exception: # log exceptions and continue logging.exception() # lock with the timer sleep(period - (timer() - start) % period) To avoid drift over time of backup times, the sleep is locked with the timer using the modulo operation. If backup() takes longer than *period* seconds (unlikely for 10MB per 10 minutes) then the step may be skipped. backup() makes sure that the data is saved and can be restore at any time. def backup(): with atomic_open('backup', 'w') as file: file.write(get_data()) where atomic_open() [1] tries to overcome multiple issues with saving data reliably: - write to a temporary file so that the old data is always available - rename the file when all new data is written, handle cases such as: * "antivirus opens old file thus preventing me from replacing it" either the operation succeeds and 'backup' contains new data or it fails and 'backup' contains untouched ready-to-restore old data -- nothing in between. [1]: https://github.com/mitsuhiko/python-atomicfile/blob/master/atomicfile.py I don't know how ready atomicfile.py but you should be aware of the issues it is trying to solve if you want a reliable backup solution. -- Akira From 4kir4.1i at gmail.com Fri Oct 31 08:14:48 2014 From: 4kir4.1i at gmail.com (Akira Li) Date: Fri, 31 Oct 2014 15:14:48 +0300 Subject: Emulating py2exe for python version 3 and above References: Message-ID: <87d298phaf.fsf@gmail.com> Ian Dickinson writes: > Can i emulate py2exe for python version 3 and above i also use pygame any > suggestions for a basic staring script would be greatly appreciated > > py2exe supports Python 3.3+ Actually, default installers from pypi support only Python 3. I see unofficial pygame's Windows installers for Python 3 at http://www.lfd.uci.edu/~gohlke/pythonlibs/#pygame -- Akira From rosuav at gmail.com Fri Oct 31 08:19:25 2014 From: rosuav at gmail.com (Chris Angelico) Date: Fri, 31 Oct 2014 23:19:25 +1100 Subject: Saving a file "in the background" -- How? In-Reply-To: <87h9ykphm9.fsf@gmail.com> References: <5452ADFD.5030801@it.uu.se> <87h9ykphm9.fsf@gmail.com> Message-ID: On Fri, Oct 31, 2014 at 11:07 PM, Akira Li <4kir4.1i at gmail.com> wrote: > where atomic_open() [1] tries to overcome multiple issues with saving > data reliably: > > - write to a temporary file so that the old data is always available > - rename the file when all new data is written, handle cases such as: > * "antivirus opens old file thus preventing me from replacing it" > > either the operation succeeds and 'backup' contains new data or it fails > and 'backup' contains untouched ready-to-restore old data -- nothing in > between. Sounds like a lot of hassle, and a lot of things that could be done wrongly. Personally, if I need that level of reliability and atomicity, I'd rather push the whole question down to a lower level: maybe commit something to a git repository and push it to a remote server, or use a PostgreSQL database, or something of that sort. Let someone else have the headaches about "what if AV opens the file". Let someone else worry about how to cope with power failures at arbitrary points in the code. (Though, to be fair, using git for this doesn't fully automate failure handling; what it does is allow you to detect issues on startup, and either roll back ("git checkout -f") or apply ("git commit -a") if it looks okay.) ChrisA From satishmlmlml at gmail.com Fri Oct 31 08:28:01 2014 From: satishmlmlml at gmail.com (satishmlmlml at gmail.com) Date: Fri, 31 Oct 2014 05:28:01 -0700 (PDT) Subject: Popen class? Message-ID: <46284d22-f43d-4e0a-9734-dc056492249a@googlegroups.com> What is Popen class? From davea at davea.name Fri Oct 31 08:34:08 2014 From: davea at davea.name (Dave Angel) Date: Fri, 31 Oct 2014 08:34:08 -0400 Subject: set environmental variable from python In-Reply-To: References: <5452EAE2.8020500@davea.name> Message-ID: <545381C0.5000302@davea.name> On 10/30/2014 10:40 PM, Artur Bercik wrote: > On Fri, Oct 31, 2014 at 11:30 AM, Zachary Ware < > zachary.ware+pylist at gmail.com> wrote: > >> On Thursday, October 30, 2014, Artur Bercik wrote: >> >>> Dear Dave Angel >>> >>> Thanks for your answer. >>> >>> I am using Python 2.7 >>> >>> I want to set it permanently. >>> I have to set several variables so it would be easier if I could set them >>> from Python. >>> >> >> Depending on how "permanently" you mean, about your only solutions would >> be "os.system('setx <...>')" or manually manipulating the registry with the >> _winreg module. >> > > > could you please elaborate 'setx <...>'? > SETX is a Windows utility. I don't run Windows, but I found a Win7 machine and played again. I used to be quite knowledgeable about Windows, but I could get parts of the following wrong. To see what SETX does, type (at a cmd line): SETX /? Or google it. (I used duckduckgo, and here are the first two useful links: Obviously the second one is an official Microsoft page. http://ss64.com/nt/setx.html http://technet.microsoft.com/en-us/library/cc755104.aspx There are several variants of "permanent" that are relevant here. 1) Nothing you change in one process will change another process that's already running. That includes any shells you might have already started, such as DOS boxes. (cmd windows) And the term shell here also includes any other already-running process that is going to launch another program. The shell controls its child's environment, and in general do not check the registry for changes you might have made. 2) SETX will affect new processes launched directly from Windows (eg. from Explorer), because it changes the registry itself. 3) SETX will affect *new* shells launched, and thus indirectly affect their children. 4) SETX effects will survive a reboot. So when you restart your system, you'll still see the new values. Incidentally, that's the first time when you'll be sure that all processes will see the new values. 5) SETX can be used on remote (networked) systems, and the rules are somewhat different there. 6) If you have (or ever will have) multiple users, you have to consider whether you want to affect the system environment variables or just one user. And if just one user, whether it's yourself or some other account, such as Administrator. Every time a process is launched by the system, it builds an environment from TWO sets of registry items. So if you want to affect all users, you need to change the system variables. If you are just going to do this once, and you want to affect all the processes that ever run in the future, you'll be much safer using the control panel: Control Panel | System | Advanced | Environment Variables -- DaveA From cs at zip.com.au Fri Oct 31 08:41:36 2014 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 31 Oct 2014 23:41:36 +1100 Subject: Popen class? In-Reply-To: <46284d22-f43d-4e0a-9734-dc056492249a@googlegroups.com> References: <46284d22-f43d-4e0a-9734-dc056492249a@googlegroups.com> Message-ID: <20141031124136.GA73317@cskk.homeip.net> On 31Oct2014 05:28, satishmlmlml at gmail.com wrote: >What is Popen class? It's a class from the subprocess module: https://docs.python.org/3/library/subprocess.html#module-subprocess used for starting external programs, waiting for them to execute, and using their input and outputs. Cheers, Cameron Simpson manual, n.: A unit of documentation. There are always three or more on a given item. One is on the shelf; someone has the others. The information you need is in the others. - Ray Simard From gandalf23 at mail.com Fri Oct 31 09:12:46 2014 From: gandalf23 at mail.com (Kiuhnm) Date: Fri, 31 Oct 2014 06:12:46 -0700 (PDT) Subject: problem with pefile In-Reply-To: References: <59be2b15-3995-4cfa-a11d-58d001ddc622@googlegroups.com> Message-ID: <89082d33-3518-4f85-940f-d88e7930155e@googlegroups.com> On Friday, October 31, 2014 2:23:26 AM UTC+1, Cameron Simpson wrote: > On 30Oct2014 17:58, Kiuhnm wrote: > >On Friday, October 31, 2014 1:33:07 AM UTC+1, Cameron Simpson wrote: > >> On 29Oct2014 08:34, gandalf23 wrote: > >> >OT: how can I hide my email in these posts? > >> >Every time I try to send a post, google warns me that my email is visible and so I edit it out. > >> > >> Why would you want to hide your email? > > > >I don't want more spam. > > You just need to filter your email better. > Most of us do not hide our addresses. > > I manage to filter most of my spam by filing anything which gets past all my > rules that catch mailing lists and which do not come from addresses in my > "known" group into a probably-spam folder. It is surprisingly effective. > > Basicly: > - to me (me in to/cc/bcc), from a "known" author ==> inbox > - matches one of my mailing list rules ==> appropriate-folder > - otherwise ==> probably-spam If it's *probably*-spam, you need to check it anyway, so that doesn't solve the problem. What happens if I miss an important email? From steve+comp.lang.python at pearwood.info Fri Oct 31 10:06:23 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 01 Nov 2014 01:06:23 +1100 Subject: Saving a file "in the background" -- How? References: <5452ADFD.5030801@it.uu.se> <87h9ykphm9.fsf@gmail.com> Message-ID: <54539760$0$13009$c3e8da3$5496439d@news.astraweb.com> Chris Angelico wrote: > Sounds like a lot of hassle, and a lot of things that could be done > wrongly. Personally, if I need that level of reliability and > atomicity, I'd rather push the whole question down to a lower level: > maybe commit something to a git repository and push it to a remote > server, How is pushing something to a remote server more reliable than writing to a local drive? > or use a PostgreSQL database, or something of that sort. Let > someone else have the headaches about "what if AV opens the file". Let > someone else worry about how to cope with power failures at arbitrary > points in the code. That "someone else" is still you though. And "use a PostgreSQL database" is no solution to the problem "how do I reliably write a 250MB video file?". Or for that matter, a 2KB text file. Databases are great as databases, but they aren't files. > (Though, to be fair, using git for this doesn't > fully automate failure handling; what it does is allow you to detect > issues on startup, and either roll back ("git checkout -f") or apply > ("git commit -a") if it looks okay.) I don't see how this sort of manual handling is less trouble than using a proper, reliable save routine. To start with, what do you mean "detect issues on startup" -- startup of what? -- Steven From Seymore4Head at Hotmail.invalid Fri Oct 31 10:05:47 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 10:05:47 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On Fri, 31 Oct 2014 10:05:03 +0100, "ast" wrote: > >"Seymore4Head" a ?crit dans le message de >news:51755at03r0bidjqh3qf0hhpvjr8756ill at 4ax.com... >> class pet: >> def set_age(self,age): >> self.age=age >> def get_age(self): >> return self.age >> pax=pet >> pax.set_age(4) >> >> Traceback (most recent call last): >> File "C:\Functions\test.py", line 18, in >> pax.set_age(4) >> TypeError: set_age() missing 1 required positional argument: 'age' >> >> I am trying to pass 4 as the age. Obviously I am doing it wrong. >> > >Hi > >I am a beginner too, but I find it strange that your >pet class has no __init__ method to construct >instances Because the topic of that lesson was getter setter. I can construct an __init___ but I was practicing get/set. This stuff is coming to me slowly. I need to rinse and repeat quite a few more times, before I follow what is going on. From breamoreboy at yahoo.co.uk Fri Oct 31 10:11:14 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 31 Oct 2014 14:11:14 +0000 Subject: Classes In-Reply-To: <545350c3$0$23449$426a74cc@news.free.fr> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On 31/10/2014 09:05, ast wrote: > > "Seymore4Head" a ?crit dans le message de > news:51755at03r0bidjqh3qf0hhpvjr8756ill at 4ax.com... >> class pet: >> def set_age(self,age): >> self.age=age >> def get_age(self): >> return self.age >> pax=pet >> pax.set_age(4) >> >> Traceback (most recent call last): >> File "C:\Functions\test.py", line 18, in >> pax.set_age(4) >> TypeError: set_age() missing 1 required positional argument: 'age' >> >> I am trying to pass 4 as the age. Obviously I am doing it wrong. >> > > Hi > > I am a beginner too, but I find it strange that your > pet class has no __init__ method to construct > instances __init__ initialises instances, __new__ constructs them -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From Seymore4Head at Hotmail.invalid Fri Oct 31 10:07:20 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 10:07:20 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <64J4w.766648$dz3.103993@fx20.am4> Message-ID: <9r575a55lsmns61lnbucauuk6vs1p74l16@4ax.com> On Fri, 31 Oct 2014 09:59:30 GMT, alister wrote: >On Thu, 30 Oct 2014 17:34:57 -0400, Seymore4Head wrote: > >> On Thu, 30 Oct 2014 14:28:19 -0700, Larry Hudson >> wrote: >> >>>On 10/30/2014 01:16 PM, Seymore4Head wrote: >>>> class pet: >>>> def set_age(self,age): >>>> self.age=age >>>> def get_age(self): >>>> return self.age >>>> pax=pet pax.set_age(4) >>>> >>>> Traceback (most recent call last): >>>> File "C:\Functions\test.py", line 18, in >>>> pax.set_age(4) >>>> TypeError: set_age() missing 1 required positional argument: 'age' >>>> >>>> I am trying to pass 4 as the age. Obviously I am doing it wrong. >>>> >>>You have already received the answer -- pax=pet should be pax=pet(), but >>>I have a simple side-comment about style. It is common Python >>>convention to capitalize class names, IOW make this class Pet instead of >>>class pet. This is convention not a requirement, but it does help >>>distinguish class names from ordinary variable names -- especially to >>>others reading your code (as well as yourself a few days later). ;-) >>> >>> -=- Larry -=- >> >> I try to take typing shortcuts and it bites me in the behind. >> Good suggestion Thanks > >If shortcuts were safe and easy they would not be shortcuts they would be >the way. > >It is best to avoid shortcuts whilst learning untill you know the full >implications. you will find your learning goes much smother & faster. Good advice. From breamoreboy at yahoo.co.uk Fri Oct 31 10:17:33 2014 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 31 Oct 2014 14:17:33 +0000 Subject: set environmental variable from python In-Reply-To: <36c5d2db-a931-417e-ae8c-9c77acfc947b@googlegroups.com> References: <5452EAE2.8020500@davea.name> <36c5d2db-a931-417e-ae8c-9c77acfc947b@googlegroups.com> Message-ID: On 31/10/2014 02:36, Rustom Mody wrote: > On Friday, October 31, 2014 8:01:08 AM UTC+5:30, Zachary Ware wrote: >> On Thursday, October 30, 2014, Artur Bercik wrote: >> >> Dear Dave Angel >> >> >> Thanks for your answer. >> >> >> I am using Python 2.7 >> >> >> I want to set it permanently. >> I have to set several variables so it would be easier if I could set them from Python. >> >> >> Depending on how "permanently" you mean, about your only solutions >> would be "os.system('setx <...>')" or manually manipulating the >> registry with the _winreg module. > > Or dont do it from python but directly with regedit?? > > The question really is: Why do you wish to do this from within python? > > Or do it directly with something like the Rapid Environment Editor http://www.rapidee.com/en/about -- My fellow Pythonistas, ask not what our language can do for you, ask what you can do for our language. Mark Lawrence From rosuav at gmail.com Fri Oct 31 10:29:54 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 01:29:54 +1100 Subject: Saving a file "in the background" -- How? In-Reply-To: <54539760$0$13009$c3e8da3$5496439d@news.astraweb.com> References: <5452ADFD.5030801@it.uu.se> <87h9ykphm9.fsf@gmail.com> <54539760$0$13009$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Nov 1, 2014 at 1:06 AM, Steven D'Aprano wrote: > Chris Angelico wrote: > >> Sounds like a lot of hassle, and a lot of things that could be done >> wrongly. Personally, if I need that level of reliability and >> atomicity, I'd rather push the whole question down to a lower level: >> maybe commit something to a git repository and push it to a remote >> server, > > How is pushing something to a remote server more reliable than writing to a > local drive? It's not, as far as the program's concerned, but when I need reliability I usually also need replication/backups. >> or use a PostgreSQL database, or something of that sort. Let >> someone else have the headaches about "what if AV opens the file". Let >> someone else worry about how to cope with power failures at arbitrary >> points in the code. > > That "someone else" is still you though. And "use a PostgreSQL database" is > no solution to the problem "how do I reliably write a 250MB video file?". If the commit happens, it's saved, and everything else isn't my problem. And yes, Postgres isn't ideal for a 250MB file, but then, neither is any sort of autosave good for that. I'm assuming the content isn't that big. > Or for that matter, a 2KB text file. Databases are great as databases, but > they aren't files. A database can handle a 2KB text file, no problem. That's how most CMSes work. >> (Though, to be fair, using git for this doesn't >> fully automate failure handling; what it does is allow you to detect >> issues on startup, and either roll back ("git checkout -f") or apply >> ("git commit -a") if it looks okay.) > > I don't see how this sort of manual handling is less trouble than using a > proper, reliable save routine. To start with, what do you mean "detect > issues on startup" -- startup of what? Because fundamentally it's impossible to write a reliable save routine. The best you can do is detect, on subsequent restart of your program, that there was an incomplete save in a previous session, and either roll it back or complete it. In some cases that's trivial - if there's a temporary file, you have the partial save, so you delete the temporary (rolling back) - or you just ignore it and overwrite, and hope that it's not going to get stuck anywhere. But it's still the same broad technique, whichever way you do it. ChrisA From ian.g.kelly at gmail.com Fri Oct 31 10:47:23 2014 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 31 Oct 2014 08:47:23 -0600 Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On Fri, Oct 31, 2014 at 8:05 AM, Seymore4Head wrote: > Because the topic of that lesson was getter setter. > I can construct an __init___ but I was practicing get/set. Doesn't sound like a very good lesson to me. Getters and setters are the Java way of doing things. The Pythonic way is to just use an attribute, and then replace it with a property in the unlikely event that getter/setter logic needs to be added. From invalid at invalid.invalid Fri Oct 31 11:49:43 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 31 Oct 2014 15:49:43 +0000 (UTC) Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On 2014-10-31, Ian Kelly wrote: > On Fri, Oct 31, 2014 at 8:05 AM, Seymore4Head > wrote: >> Because the topic of that lesson was getter setter. >> I can construct an __init___ but I was practicing get/set. > > Doesn't sound like a very good lesson to me. It's not. It's teaching java or C++ or some other language while using a Python compiler. > Getters and setters are the Java way of doing things. The Pythonic > way is to just use an attribute, and then replace it with a property > in the unlikely event that getter/setter logic needs to be added. Exactly. -- Grant Edwards grant.b.edwards Yow! I have the power to at HALT PRODUCTION on all gmail.com TEENAGE SEX COMEDIES!! From Seymore4Head at Hotmail.invalid Fri Oct 31 12:31:56 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 12:31:56 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On Fri, 31 Oct 2014 15:49:43 +0000 (UTC), Grant Edwards wrote: >On 2014-10-31, Ian Kelly wrote: >> On Fri, Oct 31, 2014 at 8:05 AM, Seymore4Head >> wrote: >>> Because the topic of that lesson was getter setter. >>> I can construct an __init___ but I was practicing get/set. >> >> Doesn't sound like a very good lesson to me. > >It's not. It's teaching java or C++ or some other language while >using a Python compiler. > >> Getters and setters are the Java way of doing things. The Pythonic >> way is to just use an attribute, and then replace it with a property >> in the unlikely event that getter/setter logic needs to be added. > >Exactly. In this class, we will follow the practice of accessing the contents of objects using methods known as getters and setters. While not required by Python, this practice encourages the user of the class to manipulates class objects solely via class methods. The advantage of following this practice is that the implementer of the class definition (often someone other than the user of the class) may restructure the organization of the data fields associated with the object while avoiding the need to rewrite code that uses the class. From rosuav at gmail.com Fri Oct 31 12:37:29 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 03:37:29 +1100 Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On Sat, Nov 1, 2014 at 3:31 AM, Seymore4Head wrote: [presumably quoting his course material] > In this class, we will follow the practice of accessing the contents > of objects using methods known as getters and setters. While not > required by Python, this practice encourages the user of the class to > manipulates class objects solely via class methods. The advantage of > following this practice is that the implementer of the class > definition (often someone other than the user of the class) may > restructure the organization of the data fields associated with the > object while avoiding the need to rewrite code that uses the class. Yep, that's teaching C++/Java coding using Python. Isn't it time you got onto a better course? Time and time again you've been going down inadvisable paths, and it seems to me you could do better with the inbuilt tutorial rather than this kind of course. ChrisA From software.by.python at gmail.com Fri Oct 31 12:46:21 2014 From: software.by.python at gmail.com (robert brook) Date: Fri, 31 Oct 2014 09:46:21 -0700 (PDT) Subject: Implementing pdfkit and wkhtmltopdf on windows fails Message-ID: I am able to install both of these packages on my mac at home and it works well. I am trying to install on windows 7 at work and it fails. PDFKit is trying to find the wkh package and it cannot. I have entered the full path to the exe for the environment variables and the error below is spit out. If I explicitly cd into the directory that has the executable the script works fine >>> import os >>> path='C:\\wkhtmltopdf\\bin\\' >>> os.chdir(path) >>> pdfkit.from_string('Hello!', 'out.pdf') Loading pages (1/6) #this works after cd into the exe directory Where can I specify the path to the executable? ************* Traceback (most recent call last): File "", line 1, in File "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1-py3.3.eg g\pdfkit\api.py", line 66, in from_string File "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1-py3.3.eg g\pdfkit\pdfkit.py", line 39, in __init__ File "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1-py3.3.eg g\pdfkit\configuration.py", line 27, in __init__ OSError: No wkhtmltopdf executable found: "b''" If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing -wkhtmltopdf ********************** From Seymore4Head at Hotmail.invalid Fri Oct 31 12:47:41 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 12:47:41 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On Sat, 1 Nov 2014 03:37:29 +1100, Chris Angelico wrote: >On Sat, Nov 1, 2014 at 3:31 AM, Seymore4Head > wrote: >[presumably quoting his course material] >> In this class, we will follow the practice of accessing the contents >> of objects using methods known as getters and setters. While not >> required by Python, this practice encourages the user of the class to >> manipulates class objects solely via class methods. The advantage of >> following this practice is that the implementer of the class >> definition (often someone other than the user of the class) may >> restructure the organization of the data fields associated with the >> object while avoiding the need to rewrite code that uses the class. > >Yep, that's teaching C++/Java coding using Python. Isn't it time you >got onto a better course? Time and time again you've been going down >inadvisable paths, and it seems to me you could do better with the >inbuilt tutorial rather than this kind of course. > >ChrisA inbuilt tutorial? The course is free. You can't beat the price. It is only for a few more weeks. Trying to learn from reading the Internet has no set direction. I need a little nudge. More like a shove. From Seymore4Head at Hotmail.invalid Fri Oct 31 12:49:27 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 12:49:27 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On Fri, 31 Oct 2014 10:05:03 +0100, "ast" wrote: > >"Seymore4Head" a ?crit dans le message de >news:51755at03r0bidjqh3qf0hhpvjr8756ill at 4ax.com... >> class pet: >> def set_age(self,age): >> self.age=age >> def get_age(self): >> return self.age >> pax=pet >> pax.set_age(4) >> >> Traceback (most recent call last): >> File "C:\Functions\test.py", line 18, in >> pax.set_age(4) >> TypeError: set_age() missing 1 required positional argument: 'age' >> >> I am trying to pass 4 as the age. Obviously I am doing it wrong. >> > >Hi > >I am a beginner too, but I find it strange that your >pet class has no __init__ method to construct >instances What material have you used to take you up to classes? From davea at davea.name Fri Oct 31 13:02:01 2014 From: davea at davea.name (Dave Angel) Date: Fri, 31 Oct 2014 13:02:01 -0400 Subject: Implementing pdfkit and wkhtmltopdf on windows fails In-Reply-To: References: Message-ID: <5453C089.2070502@davea.name> On 10/31/2014 12:46 PM, robert brook wrote: > I am able to install both of these packages on my mac at home and it works well. > > I am trying to install on windows 7 at work and it fails. PDFKit is trying to find the wkh package and it cannot. I have entered the full path to the exe for the environment variables and the error below is spit out. > > If I explicitly cd into the directory that has the executable the script works fine > >>>> import os >>>> path='C:\\wkhtmltopdf\\bin\\' >>>> os.chdir(path) >>>> pdfkit.from_string('Hello!', 'out.pdf') > Loading pages (1/6) #this works after cd into the exe directory > > > Where can I specify the path to the executable? > > ************* > Traceback (most recent call last): > File "", line 1, in > File "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1-py3.3.eg > g\pdfkit\api.py", line 66, in from_string > File "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1-py3.3.eg > g\pdfkit\pdfkit.py", line 39, in __init__ > File "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1-py3.3.eg > g\pdfkit\configuration.py", line 27, in __init__ > OSError: No wkhtmltopdf executable found: "b''" > If this file exists please check that this process can read it. Otherwise please > install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing > -wkhtmltopdf > > ********************** > I don't know your particular module, but generally, you want modules installed on your sys.path. Either install it there, or add the directory to sys.path (which is a list) I'd suggest doing the latter, then figure whether a reinstall is called for. It looks like you installed it in the root directory of C:, rather than in the site-packages. -- DaveA From rosuav at gmail.com Fri Oct 31 13:02:33 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 04:02:33 +1100 Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On Sat, Nov 1, 2014 at 3:47 AM, Seymore4Head wrote: > inbuilt tutorial? > > The course is free. You can't beat the price. It is only for a few > more weeks. > > Trying to learn from reading the Internet has no set direction. I > need a little nudge. More like a shove. https://docs.python.org/3/tutorial/ Same price. ChrisA From steve+comp.lang.python at pearwood.info Fri Oct 31 13:06:44 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 01 Nov 2014 04:06:44 +1100 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> Seymore4Head wrote: > Because the topic of that lesson was getter setter. > I can construct an __init___ but I was practicing get/set. What lesson is that? Using getters/setters is discouraged in Python. > This stuff is coming to me slowly. I need to rinse and repeat quite a > few more times, before I follow what is going on. Start with the simplest class possible: class MyClass: pass Right now, that class has a name, "MyClass", no methods, and no data. But we can still create an instance. Call the class, as if it were a function, to create the instance: obj = MyClass() What's the relationship between instances and classes? Classes are a general type of entity, instances are a specific example of that entity. You can have many instances from a class. So: Class: Dog Instances: Rin-Tin-Tin, Lassie, Hooch (from the "Turner and Hooch" movie), Marmaduke, Gaspode the Wonder Dog, Spike the Bulldog, etc. Class: Wizard Instances: Gandalf, Dumbledore, the Wizard of Oz, Rincewind, etc. Class: int Instances: 0, 1, 2, -5, 23, 19874023, etc. You can confirm that obj is now an instance of MyClass: print(isinstance(obj, MyClass)) will print True. What can you do with obj? It has no interesting methods, and no data. But we can give it some! Python, unlike some languages, allows you to dynamically add data attributes to instances on the fly, without pre-defining them. obj.value = 23.0 obj.message = "hello world!" print(obj.value) print(obj.message) will associate the data 23.0 and "hello world" to the attributes "value" and "message" of the instance obj. Let's make the class a bit easier to use, at the expense of doing a bit more work up front: class MyClass: def __init__(self, value, message): self.value = value self.message = message obj = MyClass(23.0, "hello world") print(obj.value) print(obj.message) The __init__ method is automatically called when you call the class as if it were a function. Because the __init__ method has two arguments (plus the special "self" argument), you have to call the class with two arguments. They get used as the value and message respectively. Or we can give it getters and setters: class MyClass: def set_value(self, value): self.value = value def get_value(self): return self.value def set_message(self, message): self.message = message def get_message(self): return self.message obj = MyClass() obj.set_value(23.0) obj.set_message("hello world") print(obj.get_value()) print(obj.get_message()) If you're thinking that's a lot of extra work for not much benefit, 99.99% of the time you're right. -- Steven From Seymore4Head at Hotmail.invalid Fri Oct 31 13:07:33 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 13:07:33 -0400 Subject: Teaching Python References: <4vui2ahng4fr7dh66c084olrmp4fcnam1e@4ax.com> Message-ID: <60g75a5gsfmodm7f84ph2rj08vfttq0a8f@4ax.com> On Mon, 29 Sep 2014 11:44:01 -0400, Seymore4Head wrote: >On Mon, 29 Sep 2014 15:18:31 +0200, Gabor Urban >wrote: > >>Hi, >> >>my 11 years old son and his classmate told me, that they would like to >>learn Python. They did some programming in Logo and turtle graphics, bat >>not too much. >> >>Doesn anybody has an idea how to start? > >I ordered this book from the library a few weeks ago. It just came in >yesterday. >Python for kids. Jason R Briggs > >This was also a good page for starters. >http://www.practicepython.org/ BTW I found that book online. https://www.google.com/search?as_q=python+for+kids&as_epq=&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch=&as_occt=any&safe=images&tbs=&as_filetype=pdf&as_rights=&gws_rd=ssl I don't know how to post the link to the web page so I just posted the search method I used to find it. I wanted to review it again and I noticed something that was a little humorous to me. Installing Python on Ubuntu on page 9 and 10 (of the book) shows that what ever kid is using this machine for Python is also doing Multiplayer online poker. Trying to parlay his/her lunch money would be my guess. From steve+comp.lang.python at pearwood.info Fri Oct 31 13:11:51 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 01 Nov 2014 04:11:51 +1100 Subject: Popen class? References: <46284d22-f43d-4e0a-9734-dc056492249a@googlegroups.com> Message-ID: <5453c2d8$0$13014$c3e8da3$5496439d@news.astraweb.com> satishmlmlml at gmail.com wrote: > What is Popen class? Googling could answer that: https://duckduckgo.com/html/?q=python+popen+class If you have a specific question, please be more detailed when you ask your question, then we can give more specific answers. -- Steven From davea at davea.name Fri Oct 31 13:20:36 2014 From: davea at davea.name (Dave Angel) Date: Fri, 31 Oct 2014 13:20:36 -0400 Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: <5453C4E4.40206@davea.name> On 10/31/2014 12:31 PM, Seymore4Head wrote: > In this class, we will follow the practice of accessing the contents > of objects using methods known as getters and setters. While not > required by Python, this practice encourages the user of the class to > manipulates class objects solely via class methods. The advantage of > following this practice is that the implementer of the class > definition (often someone other than the user of the class) may > restructure the organization of the data fields associated with the > object while avoiding the need to rewrite code that uses the class. > Written by somebody who doesn't understand a fundamental point about Python. It's just not true that the user would have to rewrite code if the implementer change the members. The Python way of writing getters and setters (if/when you get to that stage of a Python class) is through the property decorator or its equivalent. class Pet(): def __init__(self, ....): self.internal details set here @property() def age(self): return some_complicated_expression And the user of the class fetches this by using mypet = Pet(....) hisage = mypet.age No stupid parentheses needed. When the class is first written, no work is needed. When it's updated to multiply the internal age by 7, just write the function, and decorate it to look like a regular attribute. More complicated things can be done. But the point is that the user should just get the age, by accessing the age attribute, and if the implementation needs to change, it can change. The time to make a class complicated, is when it needs to be. And the user should not have to pay the price for "just in case." -- DaveA From Seymore4Head at Hotmail.invalid Fri Oct 31 13:18:00 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 13:18:00 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> Message-ID: <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> On Sat, 01 Nov 2014 04:06:44 +1100, Steven D'Aprano wrote: >Seymore4Head wrote: > >> Because the topic of that lesson was getter setter. >> I can construct an __init___ but I was practicing get/set. > >What lesson is that? Using getters/setters is discouraged in Python. > >> This stuff is coming to me slowly. I need to rinse and repeat quite a >> few more times, before I follow what is going on. > >Start with the simplest class possible: > >class MyClass: > pass > >Right now, that class has a name, "MyClass", no methods, and no data. But we >can still create an instance. Call the class, as if it were a function, to >create the instance: > >obj = MyClass() > >What's the relationship between instances and classes? Classes are a general >type of entity, instances are a specific example of that entity. You can >have many instances from a class. So: > >Class: Dog >Instances: Rin-Tin-Tin, Lassie, Hooch (from the "Turner and Hooch" movie), > Marmaduke, Gaspode the Wonder Dog, Spike the Bulldog, etc. > >Class: Wizard >Instances: Gandalf, Dumbledore, the Wizard of Oz, Rincewind, etc. > >Class: int >Instances: 0, 1, 2, -5, 23, 19874023, etc. > > >You can confirm that obj is now an instance of MyClass: > >print(isinstance(obj, MyClass)) > >will print True. > >What can you do with obj? It has no interesting methods, and no data. But we >can give it some! Python, unlike some languages, allows you to dynamically >add data attributes to instances on the fly, without pre-defining them. > >obj.value = 23.0 >obj.message = "hello world!" >print(obj.value) >print(obj.message) > > >will associate the data 23.0 and "hello world" to the attributes "value" >and "message" of the instance obj. > >Let's make the class a bit easier to use, at the expense of doing a bit more >work up front: > >class MyClass: > def __init__(self, value, message): > self.value = value > self.message = message > >obj = MyClass(23.0, "hello world") >print(obj.value) >print(obj.message) > > >The __init__ method is automatically called when you call the class as if it >were a function. Because the __init__ method has two arguments (plus the >special "self" argument), you have to call the class with two arguments. >They get used as the value and message respectively. > > >Or we can give it getters and setters: > >class MyClass: > def set_value(self, value): > self.value = value > def get_value(self): > return self.value > def set_message(self, message): > self.message = message > def get_message(self): > return self.message > >obj = MyClass() >obj.set_value(23.0) >obj.set_message("hello world") >print(obj.get_value()) >print(obj.get_message()) > > >If you're thinking that's a lot of extra work for not much benefit, 99.99% >of the time you're right. I agree it is more work. But more work means more practice. I need more practice figuring out how these commands work. >obj = MyClass() >obj.set_value(23.0) >obj.set_message("hello world") >print(obj.get_value()) >print(obj.get_message()) I don't know here to get more (simple) practice problems. I am trying to invent my own. From mal at europython.eu Fri Oct 31 13:28:31 2014 From: mal at europython.eu (M.-A. Lemburg) Date: Fri, 31 Oct 2014 18:28:31 +0100 Subject: EuroPython 2015 Call for Participation: On-site Teams Message-ID: <5453C6BF.3070402@europython.eu> The EuroPython Society (EPS) is happy to announce the Call for Participation (CFP) for EuroPython 2015. The purpose of this call is to select teams willing to help organize the EuroPython conference on-site at a suitable location. Call for Participation (CFP) ---------------------------- Please see the online versions of the Call for Participation posting for details: * Call for Participation blog post: http://www.europython-society.org/post/101421890815/europython-2015-call-for-participation-on-site-teams * Call for Participation PDF file: https://www.dropbox.com/s/6u78zb4v95h2lq5/EuroPython%20CFP%202015%20-%20Final.pdf?dl=1 We could also like to remind everyone interested in helping with the EuroPython 2015 organization, that the Call for Volunteers is still open: * EuroPython Workgroups: Call for Volunteers http://www.europython-society.org/post/99718376575/europython-workgroups-call-for-volunteers Timeline for Proposals ---------------------- The Call for Participation will run until the following deadline for submissions. Proposals must be submitted until midnight UTC on the deadline day. * 2014-11-28 - Deadline for submissions (announcement + 4 weeks) * 2014-12-05 - Deadline for EPS to review proposals (1 week) * 2014-12-12 - Deadline for amended proposals (1 week) * 2014-12-26 - Decision on the next EP host (within 2 weeks) Thank you, -- EuroPython Society http://www.europython-society.org/ From software.by.python at gmail.com Fri Oct 31 13:25:30 2014 From: software.by.python at gmail.com (robert brook) Date: Fri, 31 Oct 2014 10:25:30 -0700 (PDT) Subject: Implementing pdfkit and wkhtmltopdf on windows fails In-Reply-To: References: Message-ID: <9dcc7bcc-4a1d-4625-a036-591bb2f977db@googlegroups.com> On Friday, October 31, 2014 1:02:44 PM UTC-4, Dave Angel wrote: > On 10/31/2014 12:46 PM, robert brook wrote: > > I am able to install both of these packages on my mac at home and it works well. > > > > I am trying to install on windows 7 at work and it fails. PDFKit is trying to find the wkh package and it cannot. I have entered the full path to the exe for the environment variables and the error below is spit out. > > > > If I explicitly cd into the directory that has the executable the script works fine > > > >>>> import os > >>>> path='C:\\wkhtmltopdf\\bin\\' > >>>> os.chdir(path) > >>>> pdfkit.from_string('Hello!', 'out.pdf') > > Loading pages (1/6) #this works after cd into the exe directory > > > > > > Where can I specify the path to the executable? > > > > ************* > > Traceback (most recent call last): > > File "", line 1, in > > File "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1-py3.3.eg > > g\pdfkit\api.py", line 66, in from_string > > File "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1-py3.3.eg > > g\pdfkit\pdfkit.py", line 39, in __init__ > > File "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1-py3.3.eg > > g\pdfkit\configuration.py", line 27, in __init__ > > OSError: No wkhtmltopdf executable found: "b''" > > If this file exists please check that this process can read it. Otherwise please > > install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing > > -wkhtmltopdf > > > > ********************** > > > > I don't know your particular module, but generally, you want modules > installed on your sys.path. Either install it there, or add the > directory to sys.path (which is a list) > > I'd suggest doing the latter, then figure whether a reinstall is called > for. It looks like you installed it in the root directory of C:, rather > than in the site-packages. > > > -- > DaveA I see the problem. The installation of the package did not drop down the files that the executable is looking for. Thanks From Seymore4Head at Hotmail.invalid Fri Oct 31 13:31:44 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 13:31:44 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On Sat, 1 Nov 2014 04:02:33 +1100, Chris Angelico wrote: >On Sat, Nov 1, 2014 at 3:47 AM, Seymore4Head > wrote: >> inbuilt tutorial? >> >> The course is free. You can't beat the price. It is only for a few >> more weeks. >> >> Trying to learn from reading the Internet has no set direction. I >> need a little nudge. More like a shove. > >https://docs.python.org/3/tutorial/ > >Same price. > I run across this page frequently. To me, this is examples. While examples can be quite useful, I don't call this a tutorial. I have found the answer to my question by searching this page several times, but the biggest problem with this page is that you can't copy and paste the examples into IDLE. JMO From marko at pacujo.net Fri Oct 31 13:35:20 2014 From: marko at pacujo.net (Marko Rauhamaa) Date: Fri, 31 Oct 2014 19:35:20 +0200 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: <87sii4rvl3.fsf@elektro.pacujo.net> Seymore4Head : > In this class, we will follow the practice of accessing the contents > of objects using methods known as getters and setters. The biggest problem in this OO disease is that it makes you think of objects as data containers instead of dynamic agents. An object is defined through its behavior, not what the black box contains. Marko From zachary.ware+pylist at gmail.com Fri Oct 31 13:39:34 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 31 Oct 2014 12:39:34 -0500 Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On Fri, Oct 31, 2014 at 12:31 PM, Seymore4Head wrote: > I run across this page frequently. To me, this is examples. While > examples can be quite useful, I don't call this a tutorial. I have > found the answer to my question by searching this page several times, > but the biggest problem with this page is that you can't copy and > paste the examples into IDLE. Sure you can, just click the little '>>>' button in the upper right of the example box. -- Zach From rgaddi at technologyhighland.invalid Fri Oct 31 13:40:24 2014 From: rgaddi at technologyhighland.invalid (Rob Gaddi) Date: Fri, 31 Oct 2014 10:40:24 -0700 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: <20141031104024.0d87773c@rg.highlandtechnology.com> On Fri, 31 Oct 2014 13:31:44 -0400 Seymore4Head wrote: > On Sat, 1 Nov 2014 04:02:33 +1100, Chris Angelico > wrote: > > >On Sat, Nov 1, 2014 at 3:47 AM, Seymore4Head > > wrote: > >> inbuilt tutorial? > >> > >> The course is free. You can't beat the price. It is only for a few > >> more weeks. > >> > >> Trying to learn from reading the Internet has no set direction. I > >> need a little nudge. More like a shove. > > > >https://docs.python.org/3/tutorial/ > > > >Same price. > > > I run across this page frequently. To me, this is examples. While > examples can be quite useful, I don't call this a tutorial. I have > found the answer to my question by searching this page several times, > but the biggest problem with this page is that you can't copy and > paste the examples into IDLE. > > JMO No, but you can retype them. Copying and pasting teaches nothing. Figuring out how to hunt down the syntax errors your retyping has induced teaches much. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From invalid at invalid.invalid Fri Oct 31 13:40:44 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 31 Oct 2014 17:40:44 +0000 (UTC) Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: On 2014-10-31, Seymore4Head wrote: > On Fri, 31 Oct 2014 15:49:43 +0000 (UTC), Grant Edwards > wrote: > >>On 2014-10-31, Ian Kelly wrote: >>> On Fri, Oct 31, 2014 at 8:05 AM, Seymore4Head >>> wrote: >>>> Because the topic of that lesson was getter setter. >>>> I can construct an __init___ but I was practicing get/set. >>> >>> Doesn't sound like a very good lesson to me. >> >>It's not. It's teaching java or C++ or some other language while >>using a Python compiler. >> >>> Getters and setters are the Java way of doing things. The Pythonic >>> way is to just use an attribute, and then replace it with a property >>> in the unlikely event that getter/setter logic needs to be added. >> >>Exactly. > > In this class, we will follow the practice of accessing the contents > of objects using methods known as getters and setters. IOW... "In this class, we're not going to learn Python. We're going to learn Java. But actually _using_ Java is too much hassle, so we'll write Java using Python instead." > While not required by Python, this practice encourages the user of > the class to manipulates class objects solely via class methods. Which is a Java/C++ thing. > The advantage of following this practice is that the implementer of > the class definition (often someone other than the user of the class) > may restructure the organization of the data fields associated with > the object while avoiding the need to rewrite code that uses the > class. That's wrong. That statement about using getter/setter having that advantage is false (if you're talking about Python). It may be true in Java or C++ or whatever language the lesson's author is teaching, but it's not true of Python. -- Grant Edwards grant.b.edwards Yow! A shapely CATHOLIC at SCHOOLGIRL is FIDGETING gmail.com inside my costume.. From rgaddi at technologyhighland.invalid Fri Oct 31 13:43:19 2014 From: rgaddi at technologyhighland.invalid (Rob Gaddi) Date: Fri, 31 Oct 2014 10:43:19 -0700 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> Message-ID: <20141031104319.02e1ca6f@rg.highlandtechnology.com> On Fri, 31 Oct 2014 13:18:00 -0400 Seymore4Head wrote: > On Sat, 01 Nov 2014 04:06:44 +1100, Steven D'Aprano > wrote: > > >Seymore4Head wrote: > > > >> Because the topic of that lesson was getter setter. > >> I can construct an __init___ but I was practicing get/set. > > > >What lesson is that? Using getters/setters is discouraged in Python. > > > >> This stuff is coming to me slowly. I need to rinse and repeat quite a > >> few more times, before I follow what is going on. > > > >Start with the simplest class possible: > > > >class MyClass: > > pass > > > >Right now, that class has a name, "MyClass", no methods, and no data. But we > >can still create an instance. Call the class, as if it were a function, to > >create the instance: > > > >obj = MyClass() > > > >What's the relationship between instances and classes? Classes are a general > >type of entity, instances are a specific example of that entity. You can > >have many instances from a class. So: > > > >Class: Dog > >Instances: Rin-Tin-Tin, Lassie, Hooch (from the "Turner and Hooch" movie), > > Marmaduke, Gaspode the Wonder Dog, Spike the Bulldog, etc. > > > >Class: Wizard > >Instances: Gandalf, Dumbledore, the Wizard of Oz, Rincewind, etc. > > > >Class: int > >Instances: 0, 1, 2, -5, 23, 19874023, etc. > > > > > >You can confirm that obj is now an instance of MyClass: > > > >print(isinstance(obj, MyClass)) > > > >will print True. > > > >What can you do with obj? It has no interesting methods, and no data. But we > >can give it some! Python, unlike some languages, allows you to dynamically > >add data attributes to instances on the fly, without pre-defining them. > > > >obj.value = 23.0 > >obj.message = "hello world!" > >print(obj.value) > >print(obj.message) > > > > > >will associate the data 23.0 and "hello world" to the attributes "value" > >and "message" of the instance obj. > > > >Let's make the class a bit easier to use, at the expense of doing a bit more > >work up front: > > > >class MyClass: > > def __init__(self, value, message): > > self.value = value > > self.message = message > > > >obj = MyClass(23.0, "hello world") > >print(obj.value) > >print(obj.message) > > > > > >The __init__ method is automatically called when you call the class as if it > >were a function. Because the __init__ method has two arguments (plus the > >special "self" argument), you have to call the class with two arguments. > >They get used as the value and message respectively. > > > > > >Or we can give it getters and setters: > > > >class MyClass: > > def set_value(self, value): > > self.value = value > > def get_value(self): > > return self.value > > def set_message(self, message): > > self.message = message > > def get_message(self): > > return self.message > > > >obj = MyClass() > >obj.set_value(23.0) > >obj.set_message("hello world") > >print(obj.get_value()) > >print(obj.get_message()) > > > > > >If you're thinking that's a lot of extra work for not much benefit, 99.99% > >of the time you're right. > > I agree it is more work. But more work means more practice. I need > more practice figuring out how these commands work. > > >obj = MyClass() > >obj.set_value(23.0) > >obj.set_message("hello world") > >print(obj.get_value()) > >print(obj.get_message()) > > I don't know here to get more (simple) practice problems. I am trying > to invent my own. Fine. Practice problem that is actually Pythonic. Define a Rectangle class. Give it length and width attributes, no unnecessary getters or setters. Give it perimeter() and area() methods. Define a Square class, subclassed from Rectangle. Use getters/setters to enforce that the length and width must be equal. Confirm that length and width remain locked, and that perimeter() and area() work correctly. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From invalid at invalid.invalid Fri Oct 31 13:43:35 2014 From: invalid at invalid.invalid (Grant Edwards) Date: Fri, 31 Oct 2014 17:43:35 +0000 (UTC) Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> Message-ID: On 2014-10-31, Seymore4Head wrote: > On Sat, 01 Nov 2014 04:06:44 +1100, Steven D'Aprano >>Let's make the class a bit easier to use, at the expense of doing a bit more >>work up front: >> >>class MyClass: >> def __init__(self, value, message): >> self.value = value >> self.message = message >> >>obj = MyClass(23.0, "hello world") >>print(obj.value) >>print(obj.message) >> >> >>The __init__ method is automatically called when you call the class as if it >>were a function. Because the __init__ method has two arguments (plus the >>special "self" argument), you have to call the class with two arguments. >>They get used as the value and message respectively. >> >>Or we can give it getters and setters: >> >>class MyClass: >> def set_value(self, value): >> self.value = value >> def get_value(self): >> return self.value >> def set_message(self, message): >> self.message = message >> def get_message(self): >> return self.message >> >>obj = MyClass() >>obj.set_value(23.0) >>obj.set_message("hello world") >>print(obj.get_value()) >>print(obj.get_message()) >> >> >>If you're thinking that's a lot of extra work for not much benefit, 99.99% >>of the time you're right. > > I agree it is more work. But more work means more practice. I need > more practice figuring out how these commands work. Except you're practicing doing things the "wrong" way. If you want to learn Java, then use Java. If you want to learn Python, then don't write Java. -- Grant Edwards grant.b.edwards Yow! HOORAY, Ronald!! at Now YOU can marry LINDA gmail.com RONSTADT too!! From __peter__ at web.de Fri Oct 31 13:45:00 2014 From: __peter__ at web.de (Peter Otten) Date: Fri, 31 Oct 2014 18:45 +0100 Subject: Implementing pdfkit and wkhtmltopdf on windows fails References: Message-ID: robert brook wrote: > I am able to install both of these packages on my mac at home and it works > well. > > I am trying to install on windows 7 at work and it fails. PDFKit is > trying to find the wkh package and it cannot. I have entered the full path > to the exe for the environment variables and the error below is spit out. > > If I explicitly cd into the directory that has the executable the script > works fine > >>>> import os >>>> path='C:\\wkhtmltopdf\\bin\\' >>>> os.chdir(path) >>>> pdfkit.from_string('Hello!', 'out.pdf') > Loading pages (1/6) #this works after cd into the exe directory > > > Where can I specify the path to the executable? > > ************* > Traceback (most recent call last): > File "", line 1, in > File > "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1- py3.3.eg > g\pdfkit\api.py", line 66, in from_string > File > "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1- py3.3.eg > g\pdfkit\pdfkit.py", line 39, in __init__ > File > "C:\Applications\python_33_32_bit\lib\site-packages\pdfkit-0.4.1- py3.3.eg > g\pdfkit\configuration.py", line 27, in __init__ > OSError: No wkhtmltopdf executable found: "b''" > If this file exists please check that this process can read it. Otherwise > please > install wkhtmltopdf - > https://github.com/JazzCore/python-pdfkit/wiki/Installing > -wkhtmltopdf > > ********************** Following the link in the traceback I find the installation instruction for windows: """ Download the installer from the wkhtmltopdf downloads list and add folder with wkhtmltopdf binary to PATH. """ This PATH has nothing to do with Python's sys.path which specifies where Python looks for modules, and you have to set it according to the rules of your OS, e. g. http://geekswithblogs.net/renso/archive/2009/10/21/how-to-set-the-windows-path-in-windows-7.aspx Once you have added "the directory you had to cd into" follwing the above instructions your script should work in a newly opened shell window. From Seymore4Head at Hotmail.invalid Fri Oct 31 13:57:04 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 13:57:04 -0400 Subject: Classes References: <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: <76j75atqj6usgusrruknsamugofbpj8bfo@4ax.com> On Fri, 31 Oct 2014 12:39:34 -0500, Zachary Ware wrote: >On Fri, Oct 31, 2014 at 12:31 PM, Seymore4Head > wrote: >> I run across this page frequently. To me, this is examples. While >> examples can be quite useful, I don't call this a tutorial. I have >> found the answer to my question by searching this page several times, >> but the biggest problem with this page is that you can't copy and >> paste the examples into IDLE. > >Sure you can, just click the little '>>>' button in the upper right of >the example box. Ah......so you can. Thanks From nobody at nowhere.invalid Fri Oct 31 14:17:43 2014 From: nobody at nowhere.invalid (Nobody) Date: Fri, 31 Oct 2014 18:17:43 +0000 Subject: accents in windows References: <838615157.3476350.1414627277178.JavaMail.zimbra@estudiantes.uci.cu> <1003235191.3477106.1414627437852.JavaMail.zimbra@estudiantes.uci.cu> Message-ID: On Thu, 30 Oct 2014 08:30:49 -0400, C at rlos wrote: > thanks U, but the real problem is: > > i have a path C:\Users\yanet\Desktop\?aa?ee?iii?oo?uu?nn this path > is correct, ?aa?ee?iii?oo?uu?nn is the name of a directory but when > i try to use os.walk() usin this path, dont work, for os this path dont > exist, i try every things but nothing works. http://www.joelonsoftware.com/articles/Unicode.html From Seymore4Head at Hotmail.invalid Fri Oct 31 14:18:44 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 14:18:44 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> Message-ID: On Fri, 31 Oct 2014 10:43:19 -0700, Rob Gaddi wrote: >Define a Square class, subclassed from Rectangle. Use getters/setters >to enforce that the length and width must be equal. Confirm that >length and width remain locked, and that perimeter() and area() work >correctly. class Rectangle: def __init__(self,length,width): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*self.length+2*self.width class Square(Rectangle): def set_side (self): if self.length!=self.width: a=Rectangle(3,5) print (a.area()) print (a.perimeter()) b=Rectangle(5,7) print (b.area()) print (b.perimeter()) c=Rectangle(4,4) print (c.area()) print (c.perimeter()) I bombed on the rest. From zachary.ware+pylist at gmail.com Fri Oct 31 14:19:46 2014 From: zachary.ware+pylist at gmail.com (Zachary Ware) Date: Fri, 31 Oct 2014 13:19:46 -0500 Subject: set environmental variable from python In-Reply-To: References: <5452EAE2.8020500@davea.name> Message-ID: On Fri, Oct 31, 2014 at 1:11 PM, Dennis Lee Bieber wrote: > On Thu, 30 Oct 2014 22:00:33 -0500, Zachary Ware > declaimed the following: > >From a Command Prompt, do 'help setx' for details on how to use setx. > > Really? > > C:\Users\Wulfraed\Documents>help setx > This command is not supported by the help utility. Try "setx /?". Oops, should have tried it before posting. It at least tells you how to get what I meant to give, though ;) > OTOH: I didn't know about this command before -- and setting user level > environment variables on Win7 wasn't working for me... I came across it after becoming very frustrated with having to jump through all the hoops to find the environment variable GUI at one point. -- Zach From nomail at invalid.com Fri Oct 31 14:31:01 2014 From: nomail at invalid.com (ast) Date: Fri, 31 Oct 2014 19:31:01 +0100 Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: <5453d568$0$2316$426a74cc@news.free.fr> "Seymore4Head" a ?crit dans le message de news:rbf75ah9l1jp9e72gqr0ncu7bau8cnt22o at 4ax.com... > What material have you used to take you up to classes? It's a french classroom on the web http://openclassrooms.com/courses/apprenez-a-programmer-en-python From Seymore4Head at Hotmail.invalid Fri Oct 31 14:36:01 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 14:36:01 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453d568$0$2316$426a74cc@news.free.fr> Message-ID: On Fri, 31 Oct 2014 19:31:01 +0100, "ast" wrote: > >"Seymore4Head" a ?crit dans le message de >news:rbf75ah9l1jp9e72gqr0ncu7bau8cnt22o at 4ax.com... > >> What material have you used to take you up to classes? > >It's a french classroom on the web >http://openclassrooms.com/courses/apprenez-a-programmer-en-python I am going to try to learn Python before I learn French, so I won't be going there. :) Thanks From joel.goldstick at gmail.com Fri Oct 31 14:41:08 2014 From: joel.goldstick at gmail.com (Joel Goldstick) Date: Fri, 31 Oct 2014 14:41:08 -0400 Subject: Classes In-Reply-To: <5453d568$0$2316$426a74cc@news.free.fr> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453d568$0$2316$426a74cc@news.free.fr> Message-ID: On Fri, Oct 31, 2014 at 2:31 PM, ast wrote: > > "Seymore4Head" a ?crit dans le message de > news:rbf75ah9l1jp9e72gqr0ncu7bau8cnt22o at 4ax.com... > >> What material have you used to take you up to classes? > > > It's a french classroom on the web > http://openclassrooms.com/courses/apprenez-a-programmer-en-python > -- > https://mail.python.org/mailman/listinfo/python-list My suggestion for a free tutorial is Learn Python the Hard Way. You won't learn by cutting and pasting. You have to type it in yourself. It will make you learn more because every typo you make will lead you to a new discovery -- Joel Goldstick http://joelgoldstick.com From Seymore4Head at Hotmail.invalid Fri Oct 31 14:42:32 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 14:42:32 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> Message-ID: On Fri, 31 Oct 2014 14:18:44 -0400, Seymore4Head wrote: >On Fri, 31 Oct 2014 10:43:19 -0700, Rob Gaddi > wrote: > > >>Define a Square class, subclassed from Rectangle. Use getters/setters >>to enforce that the length and width must be equal. Confirm that >>length and width remain locked, and that perimeter() and area() work >>correctly. > >class Rectangle: > def __init__(self,length,width): > self.length=length > self.width=width > def area(self): > return self.length*self.width > def perimeter(self): > return 2*self.length+2*self.width >class Square(Rectangle): > def set_side (self): > if self.length!=self.width: > > >a=Rectangle(3,5) >print (a.area()) >print (a.perimeter()) >b=Rectangle(5,7) >print (b.area()) >print (b.perimeter()) >c=Rectangle(4,4) >print (c.area()) >print (c.perimeter()) > >I bombed on the rest. class Rectangle: def __init__(self,length=0,width=0): self.length=length self.width=width def area(self): return self.length*self.width def perimeter(self): return 2*self.length+2*self.width class Square(Rectangle): def set_side (self,side): self.side=side return side*side a=Rectangle(3,5) print (a.area()) print (a.perimeter()) b=Rectangle(5,7) print (b.area()) print (b.perimeter()) c=Rectangle(4,4) print (c.area()) print (c.perimeter()) A little closer. From sohcahtoa82 at gmail.com Fri Oct 31 14:47:12 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Fri, 31 Oct 2014 11:47:12 -0700 (PDT) Subject: Teaching Python In-Reply-To: <60g75a5gsfmodm7f84ph2rj08vfttq0a8f@4ax.com> References: <4vui2ahng4fr7dh66c084olrmp4fcnam1e@4ax.com> <60g75a5gsfmodm7f84ph2rj08vfttq0a8f@4ax.com> Message-ID: On Friday, October 31, 2014 10:10:33 AM UTC-7, Seymore4Head wrote: > On Mon, 29 Sep 2014 11:44:01 -0400, Seymore4Head > wrote: > > >On Mon, 29 Sep 2014 15:18:31 +0200, Gabor Urban > >wrote: > > > >>Hi, > >> > >>my 11 years old son and his classmate told me, that they would like to > >>learn Python. They did some programming in Logo and turtle graphics, bat > >>not too much. > >> > >>Doesn anybody has an idea how to start? > > > >I ordered this book from the library a few weeks ago. It just came in > >yesterday. > >Python for kids. Jason R Briggs > > > >This was also a good page for starters. > >http://www.practicepython.org/ > > BTW I found that book online. > https://www.google.com/search?as_q=python+for+kids&as_epq=&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch=&as_occt=any&safe=images&tbs=&as_filetype=pdf&as_rights=&gws_rd=ssl > > I don't know how to post the link to the web page so I just posted the > search method I used to find it. > > I wanted to review it again and I noticed something that was a little > humorous to me. Installing Python on Ubuntu on page 9 and 10 (of the > book) shows that what ever kid is using this machine for Python is > also doing Multiplayer online poker. > > Trying to parlay his/her lunch money would be my guess. http://www.amazon.com/gp/product/1593274076/ref=as_li_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=1593274076&linkCode=as2&tag=other00d-20&linkId=CR3CFBFYUAUVSHVM For people that want to buy the book. From Seymore4Head at Hotmail.invalid Fri Oct 31 14:56:20 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 14:56:20 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453d568$0$2316$426a74cc@news.free.fr> Message-ID: On Fri, 31 Oct 2014 14:41:08 -0400, Joel Goldstick wrote: >On Fri, Oct 31, 2014 at 2:31 PM, ast wrote: >> >> "Seymore4Head" a ?crit dans le message de >> news:rbf75ah9l1jp9e72gqr0ncu7bau8cnt22o at 4ax.com... >> >>> What material have you used to take you up to classes? >> >> >> It's a french classroom on the web >> http://openclassrooms.com/courses/apprenez-a-programmer-en-python >> -- >> https://mail.python.org/mailman/listinfo/python-list > >My suggestion for a free tutorial is Learn Python the Hard Way. > >You won't learn by cutting and pasting. You have to type it in >yourself. It will make you learn more because every typo you make >will lead you to a new discovery I have watched a few of those videos. And I do have the PDF. I will give it a closer look. Thanks From alan at scooby-doo.csail.mit.edu Fri Oct 31 16:32:32 2014 From: alan at scooby-doo.csail.mit.edu (Alan Bawden) Date: Fri, 31 Oct 2014 16:32:32 -0400 Subject: .write() behavior References: <438d510f-05ae-47dd-bcda-42a8b777c99b@googlegroups.com> <683c84d8-d916-4b63-b4b2-92cd2763e260@googlegroups.com> <544e2cf2$0$13009$c3e8da3$5496439d@news.astraweb.com> <87bnoxv91p.fsf@elektro.pacujo.net> <87tx2otv9s.fsf@elektro.pacujo.net> <8761f376vt.fsf@elektro.pacujo.net> Message-ID: Marko Rauhamaa writes: > Let me mention a related problem I ran into a couple of weeks ago. > Linux's standard C library (glibc) implements fread(3) differently in > RHEL 5 and RHEL 6/7. In RHEL 5, it blocks in a loop until it has read in > the desired number of records. In RHEL 6 and 7, it appears to block > until it can return at least one whole record. By my reading of the POSIX standard, that latter behavior would be incorrect. The "RETURN VALUE" section of the POSIX description for fread() starts: Upon successful completion, fread() shall return the number of elements successfully read which is less than nitems only if a read error or end-of-file is encountered. ... If in whatever version of glibc comes with RHEL 6/7, it is the case that a call to fread() can return less than the desired number of records, and you have not reached EOF, and no read error has occurred, that would be a serious bug. The world is full of C programs that call fread() and fwrite() without wrapping them in defensive maybe-I-didn't-get-everything loops. >> Am I missing something? There seem to be some primitive IO facilities >> in Python 3 that make a distinction between blocking and non-blocking >> mode, but that distinction doesn't seem to be available when I just >> call open(). Since I wrote this, I have discovered and read PEP-3116, and using that as a road-map to understanding the Python 3 documentation it is now clear to me that in Python 3, if you have not gone out of your way to enable non-blocking, a call to the .write() method on any object that might normally be returned by a call to open(), will always write _all_ of your data (or raise an exception). There is never any need for a defensive loop. As further evidence that this is the case, note that PEP-3116 says right at the end of its "Rationale and Goals" section: ... Programmers who don't want to muck about in the new I/O world can expect that the open() factory method will produce an object backwards-compatible with old-style file objects. Since old-style file objects didn't return a count, this goal can only be achieved if programmers are safe in _ignoring_ that count in Python 3. I am relieved to discover that when I am finally able to port my Python code from Python 2 to Python 3, I will not have to worry that .write() might perform an incomplete write where it previously did not. -- Alan Bawden From rosuav at gmail.com Fri Oct 31 16:51:06 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 07:51:06 +1100 Subject: Classes In-Reply-To: <20141031104319.02e1ca6f@rg.highlandtechnology.com> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> Message-ID: On Sat, Nov 1, 2014 at 4:43 AM, Rob Gaddi wrote: > Define a Square class, subclassed from Rectangle. Use getters/setters > to enforce that the length and width must be equal. Confirm that > length and width remain locked, and that perimeter() and area() work > correctly. Here we go again... http://en.wikipedia.org/wiki/Circle-ellipse_problem Square and Rectangle are just as "obviously" the other way around in the hierarchy, and it's wrong whichever way you do it. Not a good example. ChrisA From sohcahtoa82 at gmail.com Fri Oct 31 17:24:11 2014 From: sohcahtoa82 at gmail.com (sohcahtoa82 at gmail.com) Date: Fri, 31 Oct 2014 14:24:11 -0700 (PDT) Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> Message-ID: On Friday, October 31, 2014 1:51:23 PM UTC-7, Chris Angelico wrote: > On Sat, Nov 1, 2014 at 4:43 AM, Rob Gaddi > wrote: > > Define a Square class, subclassed from Rectangle. Use getters/setters > > to enforce that the length and width must be equal. Confirm that > > length and width remain locked, and that perimeter() and area() work > > correctly. > > Here we go again... > > http://en.wikipedia.org/wiki/Circle-ellipse_problem > > Square and Rectangle are just as "obviously" the other way around in > the hierarchy, and it's wrong whichever way you do it. Not a good > example. > > ChrisA I've never heard of the Circle-Ellipse problem, and my first instinct to Rob's post was to ask, why would you want to sub-class Rectangle into a Square class? A square is just a special case of a Rectangle. Attempting that kind of sub-classing would just cause problems. The only thing you gain is a slight optimization in calculating perimeter by turning two multiplications and an addition into a single multiplication which really wouldn't have an effect on performance unless you were doing that calculation millions of times per second. From cs at zip.com.au Fri Oct 31 17:36:43 2014 From: cs at zip.com.au (Cameron Simpson) Date: Sat, 1 Nov 2014 08:36:43 +1100 Subject: problem with pefile In-Reply-To: <89082d33-3518-4f85-940f-d88e7930155e@googlegroups.com> References: <89082d33-3518-4f85-940f-d88e7930155e@googlegroups.com> Message-ID: <20141031213643.GA20263@cskk.homeip.net> On 31Oct2014 06:12, Kiuhnm wrote: >On Friday, October 31, 2014 2:23:26 AM UTC+1, Cameron Simpson wrote: >> On 30Oct2014 17:58, Kiuhnm wrote: >> >On Friday, October 31, 2014 1:33:07 AM UTC+1, Cameron Simpson wrote: >> >> On 29Oct2014 08:34, gandalf23 wrote: >> >> >OT: how can I hide my email in these posts? >> >> >Every time I try to send a post, google warns me that my email is visible and so I edit it out. >> >> >> >> Why would you want to hide your email? >> > >> >I don't want more spam. >> >> You just need to filter your email better. >> Most of us do not hide our addresses. >> >> I manage to filter most of my spam by filing anything which gets past all my >> rules that catch mailing lists and which do not come from addresses in my >> "known" group into a probably-spam folder. It is surprisingly effective. >> >> Basicly: >> - to me (me in to/cc/bcc), from a "known" author ==> inbox >> - matches one of my mailing list rules ==> appropriate-folder >> - otherwise ==> probably-spam > >If it's *probably*-spam, you need to check it anyway, so that doesn't solve the problem. What happens if I miss an important email? I review that folder ("unknown") every so often (a few times a day). But it keeps most of the noise out of everything else. The "probably spam" effect is one reason I don't discard things outright. I also find it easier to review a single folder whose contents are almost always spam than to constantly have little bits of spam floating by in my normal mail folders. If you want to pursue this discussions we should take it off-list to private email; we're not talking about Python any more. Cheers, Cameron Simpson From rosuav at gmail.com Fri Oct 31 17:36:03 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 08:36:03 +1100 Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> Message-ID: On Sat, Nov 1, 2014 at 8:24 AM, wrote: > I've never heard of the Circle-Ellipse problem, and my first instinct to Rob's post was to ask, why would you want to sub-class Rectangle into a Square class? A square is just a special case of a Rectangle. Attempting that kind of sub-classing would just cause problems. The only thing you gain is a slight optimization in calculating perimeter by turning two multiplications and an addition into a single multiplication which really wouldn't have an effect on performance unless you were doing that calculation millions of times per second. > Yep. A square is indeed a special case of rectangle (and a circle is a special case of ellipse), so it would make sense to have an "is_square()" method (or isSquare or squarep or whatever you want to call it). The hairiness of subclassing either to make the other means it's an unideal example. In fact, I would say the Python @property decorator is less well suited to an inheritance situation than to a chronological change. "This used to be a simple attribute, now it has validation/formatting/logging/whatever." But it's hard to come up with an example to illustrate this cleanly for a student. Personally, I'd be inclined to skip properties altogether; learn about them later, much later, and only if you actually need them. ChrisA From rgaddi at technologyhighland.invalid Fri Oct 31 17:40:45 2014 From: rgaddi at technologyhighland.invalid (Rob Gaddi) Date: Fri, 31 Oct 2014 14:40:45 -0700 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> Message-ID: <20141031144045.05965228@rg.highlandtechnology.com> On Fri, 31 Oct 2014 14:24:11 -0700 (PDT) sohcahtoa82 at gmail.com wrote: > On Friday, October 31, 2014 1:51:23 PM UTC-7, Chris Angelico wrote: > > On Sat, Nov 1, 2014 at 4:43 AM, Rob Gaddi > > wrote: > > > Define a Square class, subclassed from Rectangle. Use getters/setters > > > to enforce that the length and width must be equal. Confirm that > > > length and width remain locked, and that perimeter() and area() work > > > correctly. > > > > Here we go again... > > > > http://en.wikipedia.org/wiki/Circle-ellipse_problem > > > > Square and Rectangle are just as "obviously" the other way around in > > the hierarchy, and it's wrong whichever way you do it. Not a good > > example. > > > > ChrisA > > I've never heard of the Circle-Ellipse problem, and my first instinct to Rob's post was to ask, why would you want to sub-class Rectangle into a Square class? A square is just a special case of a Rectangle. Attempting that kind of sub-classing would just cause problems. The only thing you gain is a slight optimization in calculating perimeter by turning two multiplications and an addition into a single multiplication which really wouldn't have an effect on performance unless you were doing that calculation millions of times per second. As a practical tool? Entirely and completely useless, no doubt about it. But it's easily understood as an example, even if the reason that a Square is a subclass of Rectangle is "because I said so". For this specific exercise, a Square is a subclass of Rectangle because the point of Rectangle is to demonstrate that extraneous get/set functions are completely unnecessary in Python. The point of Square is to demonstrate that get/set functions can be useful in certain circumstances where you need to implement non-trivial behaviors, such as making the "width" property into an alias for the "length" true data member. As a learning tool for thinking about inheritance hierarchies it's kind of rubbish. But then again, most inheritance hierarchies are ambigious at best, which is why "has a" is often a better choice than "is a". -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. From rosuav at gmail.com Fri Oct 31 17:56:18 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 08:56:18 +1100 Subject: Classes In-Reply-To: <20141031144045.05965228@rg.highlandtechnology.com> References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> <20141031144045.05965228@rg.highlandtechnology.com> Message-ID: On Sat, Nov 1, 2014 at 8:40 AM, Rob Gaddi wrote: > For this specific exercise, a Square is a subclass of Rectangle because > the point of Rectangle is to demonstrate that extraneous get/set > functions are completely unnecessary in Python. The point of > Square is to demonstrate that get/set functions can be useful in > certain circumstances where you need to implement non-trivial behaviors, > such as making the "width" property into an alias for the "length" true > data member. As the Wikipedia article explains, this has its own consequences. A reasonable test suite for Rectangle would quite probably fail if given a Square. Hence my belief that this makes for a less-than-ideal example. But I can't think of *any* good example of @property for a tutorial. ANY. > As a learning tool for thinking about inheritance hierarchies it's kind > of rubbish. But then again, most inheritance hierarchies are ambigious > at best, which is why "has a" is often a better choice than "is a". Agreed. There certainly are times when "is a" is the right choice, but there are a lot more times when "has a" is the better choice. Usually, when I subclass, it's because I want to tweak the behaviour of an existing type (for instance, subclass int and change its repr() to return hex(self)), so it really truly is a , in every way except that one tiny change. Otherwise, new type with a member. Much simpler. Much safer. ChrisA From greg.ewing at canterbury.ac.nz Fri Oct 31 18:17:18 2014 From: greg.ewing at canterbury.ac.nz (Gregory Ewing) Date: Sat, 01 Nov 2014 11:17:18 +1300 Subject: Classes In-Reply-To: References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: Seymore4Head wrote: > The course is free. You can't beat the price. It is only for a few > more weeks. But if it's teaching you things that are blatantly wrong in relation to Python, it may be doing more harm than good. -- Greg From Seymore4Head at Hotmail.invalid Fri Oct 31 19:22:13 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 19:22:13 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> Message-ID: <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> On Fri, 31 Oct 2014 18:57:31 -0400, Dennis Lee Bieber wrote: >On Fri, 31 Oct 2014 14:18:44 -0400, Seymore4Head > declaimed the following: > >>On Fri, 31 Oct 2014 10:43:19 -0700, Rob Gaddi >> wrote: >> >> >>>Define a Square class, subclassed from Rectangle. Use getters/setters >>>to enforce that the length and width must be equal. Confirm that >>>length and width remain locked, and that perimeter() and area() work >>>correctly. >> >>class Rectangle: >> def __init__(self,length,width): >> self.length=length >> self.width=width >> def area(self): >> return self.length*self.width >> def perimeter(self): >> return 2*self.length+2*self.width >>class Square(Rectangle): >> def set_side (self): >> if self.length!=self.width: >> > Where's the rest of that -- not to mention you called it "set_side" but >never pass a side into it for use. > >-=-=-=-=-=-=-=- > >class Rectangle(object): > def __init__(self, length, width=None): > self.length = length > if width is None: > self.width = length > else: > self.width = width > def area(self): > return self.length * self.width > def perimeter(self): > return 2 * (self.length + self.width) > Thanks for posting that. I had given up on trying it. I follow the changes you made up this point. I will have to think some more to get the rest of this. The way you provided a catch for not having a width, I don't understand the purpose of a Square subclass. Couldn't side just be length? BTW I am willing to forget any mention of getter/setter. We can just pretend that never happened. >class Square(Rectangle): > def __init__(self, side): > self.side = side > def _getLength(self): > return self.side > def _getWidth(self): > return self.side > def _setLength(self, vlu): > self.side = vlu > def _setWidth(self, vlu): > self.side = vlu > length = property(_getLength, _setLength) > width = property(_getWidth, _setWidth) > >aRect = Rectangle(2, 4) >print aRect.length, aRect.width, aRect.area(), aRect.perimeter() >aRect.length = 9 >print aRect.length, aRect.width, aRect.area(), aRect.perimeter() > > >aSqr = Square(3) >print aSqr.side, aSqr.length, aSqr.width, aSqr.area(), aSqr.perimeter() >aSqr.length = 4 >print aSqr.side, aSqr.length, aSqr.width, aSqr.area(), aSqr.perimeter() >aSqr.width = 5 >print aSqr.side, aSqr.length, aSqr.width, aSqr.area(), aSqr.perimeter() >aSqr.side = 7 >print aSqr.side, aSqr.length, aSqr.width, aSqr.area(), aSqr.perimeter() > >-=-=-=-=-=-=-=-=- >Microsoft Windows [Version 6.1.7601] >Copyright (c) 2009 Microsoft Corporation. All rights reserved. > >C:\Users\Wulfraed\Documents>cd "Python Progs" > >C:\Users\Wulfraed\Documents\Python Progs>property2.py >2 4 8 12 >9 4 36 26 >3 3 3 9 12 >4 4 4 16 16 >5 5 5 25 20 >7 7 7 49 28 > >C:\Users\Wulfraed\Documents\Python Progs> From Seymore4Head at Hotmail.invalid Fri Oct 31 19:32:13 2014 From: Seymore4Head at Hotmail.invalid (Seymore4Head) Date: Fri, 31 Oct 2014 19:32:13 -0400 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> <5453c1a6$0$12981$c3e8da3$5496439d@news.astraweb.com> <7pg75alj1qn97hlirk81f7nqd265emgu05@4ax.com> <20141031104319.02e1ca6f@rg.highlandtechnology.com> <2i585a5s6d1aagbh6ot2b88i51o8jhq0db@4ax.com> Message-ID: On Fri, 31 Oct 2014 19:22:13 -0400, Seymore4Head wrote: >On Fri, 31 Oct 2014 18:57:31 -0400, Dennis Lee Bieber > wrote: > >>On Fri, 31 Oct 2014 14:18:44 -0400, Seymore4Head >> declaimed the following: >> >>>On Fri, 31 Oct 2014 10:43:19 -0700, Rob Gaddi >>> wrote: >>> >>> >>>>Define a Square class, subclassed from Rectangle. Use getters/setters >>>>to enforce that the length and width must be equal. Confirm that >>>>length and width remain locked, and that perimeter() and area() work >>>>correctly. >>> >>>class Rectangle: >>> def __init__(self,length,width): >>> self.length=length >>> self.width=width >>> def area(self): >>> return self.length*self.width >>> def perimeter(self): >>> return 2*self.length+2*self.width >>>class Square(Rectangle): >>> def set_side (self): >>> if self.length!=self.width: >>> >> Where's the rest of that -- not to mention you called it "set_side" but >>never pass a side into it for use. >> >>-=-=-=-=-=-=-=- >> >>class Rectangle(object): >> def __init__(self, length, width=None): >> self.length = length >> if width is None: >> self.width = length >> else: >> self.width = width >> def area(self): >> return self.length * self.width >> def perimeter(self): >> return 2 * (self.length + self.width) >> >Thanks for posting that. I had given up on trying it. I follow the >changes you made up this point. I will have to think some more to get >the rest of this. >The way you provided a catch for not having a width, I don't >understand the purpose of a Square subclass. Couldn't side just be >length? >BTW I am willing to forget any mention of getter/setter. We can just >pretend that never happened. > I took your instruction and change it to this: That answers my own question. Thanks again class Rectangle(object): def __init__(self, length, width=None): self.length = length if width is None: self.width = length else: self.width = width def area(self): return self.length * self.width def perimeter(self): return 2 * (self.length + self.width) class Square(Rectangle): def area(self): return self.length * self.width def perimeter(self): return 2 * (self.length + self.width) a=Rectangle(3,5) print (a.area()) print (a.perimeter()) b=Rectangle(5,7) print (b.area()) print (b.perimeter()) c=Square(4) print (c.area()) print (c.perimeter()) From steve+comp.lang.python at pearwood.info Fri Oct 31 21:06:56 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 01 Nov 2014 12:06:56 +1100 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: <54543231$0$13000$c3e8da3$5496439d@news.astraweb.com> Gregory Ewing wrote: > Seymore4Head wrote: >> The course is free. You can't beat the price. It is only for a few >> more weeks. > > But if it's teaching you things that are blatantly wrong > in relation to Python, it may be doing more harm than > good. Like all good Pythonistas[1], we hate Java and think that getter/setter methods are pointless. But come on, they're not *wrong*, as in incorrect. They do the job they're supposed to do, at the expense of an awkward interface. Using properties is *exactly the same as Java getters/setters*, except that the interface is less awkward. And there are times when using getters and setters is the right choice. Properties should only be used for quite lightweight calculations, because attribute access is supposed to be fast. If your calculation is complex, time-consuming or might fail, using a property is a bad idea and you should use an explicit getter method, possibly with a setter if needed. There are lots of things in Python which are written as getter methods or functions, rather than attributes or properties. E.g.: py> (23).bit_length() 5 py> len("hello world!") # calls __len__ method 12 Files have quite a few examples. fileno, isatty and writable could all be written as read-only properties, and seek/tell could be written as a file.position property. But they're not, they're written as methods. [1] Except for Jythonistas, who are allowed to enjoy using Java. -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 31 21:09:16 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 01 Nov 2014 12:09:16 +1100 Subject: Classes References: <51755at03r0bidjqh3qf0hhpvjr8756ill@4ax.com> <545350c3$0$23449$426a74cc@news.free.fr> Message-ID: <545432bc$0$13000$c3e8da3$5496439d@news.astraweb.com> Dennis Lee Bieber wrote: > What you are being taught is NOT PYTHON. Of course it is. It uses Python syntax, Python terminology, and the Python compiler. It might not be the preferred Python idiom or best practice, but it's still Python code. Exaggeration does not help anyone, it just makes us look like religious fanatics. -- Steven From steve+comp.lang.python at pearwood.info Fri Oct 31 21:29:40 2014 From: steve+comp.lang.python at pearwood.info (Steven D'Aprano) Date: Sat, 01 Nov 2014 12:29:40 +1100 Subject: Challenge: optimizing isqrt Message-ID: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> There is an algorithm for calculating the integer square root of any positive integer using only integer operations: def isqrt(n): if n < 0: raise ValueError if n == 0: return 0 bits = n.bit_length() a, b = divmod(bits, 2) x = 2**(a+b) while True: y = (x + n//x)//2 if y >= x: return x x = y This returns the integer part of the square root of n, that is, the greatest whole number less than or equal to the square root of n: py> isqrt(35) 5 py> isqrt(36) 6 That makes it equivalent to int(math.sqrt(n)), which also happens to be much, much faster, at least for small values of n. However, for large values of n, using floating point intermediate calculations fail: py> import math py> int(math.sqrt(2**3000)) Traceback (most recent call last): File "", line 1, in OverflowError: long int too large to convert to float Another problem is that, above a certain size, the resolution of floats is larger than 1, so you can't convert every int into a float without loss: py> float(2**90-1) == 2**90-1 False which means that using math.sqrt is not correct: py> isqrt(2**90-1) 35184372088831 py> int(math.sqrt(2**90-1)) # Off by one. 35184372088832 So, the challenge is to identify when it is safe to optimise isqrt(n) as int(math.sqrt(n)): Q1: What is the largest value of M, such that all(isqrt(i) == int(math.sqrt(n)) for n in range(M)) returns True? I have done a brute force test, and in nine hours confirmed that M is at least 7627926244. That took nine hours, and I expect that a brute force test of every int representable as a float would take *months* of processing time. Q2: For values above M, is there a way of identifying which values of n are okay to use the optimized version? Q3: What is the largest value of n beyond which you can never use the float optimization? You can assume that Python floats are IEEE-754 C doubles, and that math.sqrt() is correctly rounded. -- Steven From rosuav at gmail.com Fri Oct 31 22:12:54 2014 From: rosuav at gmail.com (Chris Angelico) Date: Sat, 1 Nov 2014 13:12:54 +1100 Subject: Challenge: optimizing isqrt In-Reply-To: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> References: <54543787$0$13005$c3e8da3$5496439d@news.astraweb.com> Message-ID: On Sat, Nov 1, 2014 at 12:29 PM, Steven D'Aprano wrote: > Q1: What is the largest value of M, such that > > all(isqrt(i) == int(math.sqrt(n)) for n in range(M)) > > returns True? > > I have done a brute force test, and in nine hours confirmed that M is at > least 7627926244. That took nine hours, and I expect that a brute force > test of every int representable as a float would take *months* of > processing time. Here's something that should be faster than pure brute-force: import math for i in range(2**34): # 2**34 should take about nine hours sqrt = int(math.sqrt(i)) if sqrt * sqrt > i: print("Too high at %d" % i) break if (sqrt+1) * (sqrt+1) <= i: print("Too low at %d" % i) break There are two ways int(math.sqrt(i)) can be wrong: it can return a number that's too high, or one that's too low. If it's too high, squaring it (btw, int*int seems to be faster than int**2) will produce a number higher than the original. If the result was too low, then the next number up would have been within the correct bounds. There's no need to actually calculate isqrt here. I was able to probe up to 2**29 in seven minutes on my computer (allocating one core, CPython 3.5 from trunk). If it's linear, going as far as 2**34 should take no more than the nine hours you spent. I expect time will be a bit worse than linear (working with small numbers is marginally faster than working with big numbers), but if it's at least reasonably close, probing as far as 2**53 would take 81555 days. So, uhh, a brute force by your method is going to take a lot more than months. (And 2**53 isn't technically where ints stop being representable, but I'd use that as the final cut-off, as it's where *all* ints stop being representable. In any case, there's a failure at 2**54-1, so there's no need to go past there.) Hmm. The speed difference between your brute force and mine isn't all that much. I'm estimating maybe doing at best twice as much in the same time. So you're probably already using something similar to the above, and this isn't adding much to the discussion. :( ChrisA From eploughe at digital-domain.us Thu Oct 30 15:45:57 2014 From: eploughe at digital-domain.us (eploughe at digital-domain.us) Date: Thu, 30 Oct 2014 12:45:57 -0700 Subject: Python tarfile module Message-ID: <20141030124557.a189e35ea408a3ed09790b10968c6784.e4486bee29.wbe@email17.secureserver.net> An HTML attachment was scrubbed... URL: